使用python实现WSGI静态资源服务

import os
from wsgiref.simple_server import make_server

def app(env, make_response):
    path = env.get('PATH_INFO')
    headers = []
    body = []
    static_dir = 'jquery'
	
    if path == '/favicon.ico':
        res_path = os.path.join(static_dir, 'images/a.png')
        headers.append(('content-type', 'image/*'))
    elif path == '/':
        # 主页
        res_path = os.path.join(static_dir, 'js/example_of_bootstrap.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:
            headers.append(('content-type', 'text/html;charset=utf-8'))

    status_code = 200
    if not os.path.exists(res_path):
        status_code = 404
        body.append('<h1>请求资源不存在:404</h1>'.encode('utf-8'))
    else:
        with open(res_path, 'rb') as f:
            body.append(f.read())

    #生成响应头
    make_response('%s OK' % status_code, headers)
    return body


host = '0.0.0.0'
port = 8000
httpd = make_server(host, port, app)

httpd.serve_forever() # 启动服务,开始监听客户端连接
posted @ 2021-11-16 00:20  安静ovo  阅读(156)  评论(0编辑  收藏  举报