Python
静态资源服务
WSGI
- Django
- 组件最全、最强大的框架,用于后端服务器管理、运维(Ansible/Openstack)
- Flask
- 小巧又灵活的轻量级框架
- Tornado
- 基于协程、单进程、单线程的框架,实现非阻塞的网络
- Sanic
- 性能最优的Web非阻塞框架
代码示例:
from wsgiref.simple_server import make_server # 标准库函数
import os
def app(env, make_response):
# 处理业务最核心的函数
"""
1. 请求路径
· PATH_INFO,以'/'开头
2. 请求方法
· REQUEST_METHOD
3. 请求查询参数
· QUETY_STRING
4. 客户端的地址
· REMOTE_ADDR
5. 请求上传的数据类型
· CONTENT_TYPE
6. 客户端的代理浏览器
· HTTP_USER_AGENT
7. 读取请求上传的字节数据对象
· wsgi.input
8. wsgi是否使用了多线程
· wsgi.multithread:True
9. wsgi是否使用了多进程
· wsgi.multiprocess:False
10. any
· 可迭代对象内的元素只要有一个为真,那么返回值为真
11. all
· 可迭代对象内的元素只要有一个为假,那么返回值为假
12. zip()
· 相同下标归为一个元组(返回值:自定义类型,多余部分会被剔除)
"""
path = env.get('PATH_INFO') # 请求资源的路径
headers = [] # 响应头,根据响应的数据增加不同的响应头(K:V)
body = [] # 响应的数据
# 设置静态资源目录
static_dir = 'static'
if path == '/favicon.ico':
# ico
res_path = os.path.join(static_dir, 'image/favicon.webp')
headers.append(('content-type', 'image/*'))
elif path == '/':
# 主页
res_path = os.path.join(static_dir, 'index.html')
headers.append(('content-type', 'text/html;charset=utf-8'))
else:
# 其它资源
res_path = os.path.join(static_dir, path[1:])
if res_path.endswith('.html'):
headers.append(('content-type', 'text/html;charset=utf-8'))
elif any((res_path.endswith('.png'), res_path.endswith('.jpg'), res_path.endswith('.gif'))):
headers.append(('content-type', 'image/*'))
else:
# JS/CSS
headers.append(('content-type', 'txt/*;charset=utf-8'))
# 判断资源是否存在
status_code = 200
if not os.path.exists(res_path):
status_code = 404
body.append('<h1 style="color:red">请求的资源不存在:404</h1>'.encode('utf-8'))
else:
with open(res_path, 'rb') as f:
body.append(f.read())
make_response(f'{status_code} ok', headers)
return body # 响应的数据
if __name__ == '__main__':
# 生成Web服务进程
host = 'localhost'
port = 80
httpd = make_server(host, port, app)
print(f'正在运行 => http://{host}:{port}')
httpd.serve_forever() # 启动Web服务,开始监听客户端连接