使用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 = 'DailyPCP'
    if path == '/favicon.ico':
        res_path = os.path.join(static_dir, '/img/favicon.ico')
        headers.append(('Content-Type', 'images/*'))
    elif path == '/':
        # 主页
        res_path = os.path.join(static_dir, 'login.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/*;charset=utf-8'))
        else:
            headers.append(('Content-Type', 'text/*;charset=utf-8'))
    # 生成相应头
    # make_response("200 OK", [('Content-Type', 'text/html;charset=utf-8')])
    # 相应数据
    # return ['<h3>Hi,WSGI</h3>'.encode("utf-8")]

    # 判断资源是否存在
    status_code = 200
    if not os.path.exists(res_path):
        status_code = 404
        body.append('<h4 style="color:red">请求的资源不存在:404</h4>'.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)
print('Runing http://%s:%s' % (host, app))
# 启动服务开始监听客户端连接
httpd.serve_forever()


使用Python手动实现一个WSGI服务器
https://www.diaoyc.cn//archives/%E4%BD%BF%E7%94%A8python%E6%89%8B%E5%8A%A8%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AAwsgi%E6%9C%8D%E5%8A%A1%E5%99%A8
作者
Adiaoyc
发布于
2020年05月11日
许可协议