wsgi 建立简单的服务器及解析post请求参数

论坛 期权论坛 脚本     
匿名网站用户   2020-12-20 03:31   141   0
from wsgiref.simple_server import make_server
from urllib.parse import parse_qs
from html import escape


def app(environ, start_response):   # 定义应用
    # print(environ)
    start_response("200 OK", [("Content_Type", "text/html")])
    func = None
    for item in routes():
        if environ['PATH_INFO'] == item[0]:
            func = item[1]
    if func:
        return [func(environ)]
    return [b"<h1>page is not exist</h1>"]


def example(req):   # 定义路由对应的处理方法
    with open('example.html', 'rb') as f:
        lines = f.read()
    return lines


def login(req):      # 解析post请求参数
    # the environment variable CONTENT_LENGTH may be empty or missing
    try:
        request_body_size = int(req.get('CONTENT_LENGTH', 0))
    except (ValueError):
        request_body_size = 0

    # When the method is POST the variable will be sent
    # in the HTTP request body which is passed by the WSGI server
    # in the file like wsgi.input environment variable.
    request_body = req['wsgi.input'].read(request_body_size)
    d = parse_qs(request_body)
    print(d)   # 返回的dict中的键值对类型 {bytes:[bytes,..]}
    user_name = escape(d.get(bytes('user', encoding="utf-8"))[0].decode("utf-8"))
    password = escape(d.get(bytes('pwd', encoding="utf-8"))[0].decode("utf-8"))
    print(user_name, password)
    if user_name == "example" and password == "example":
        return example(req)
    else:
        return b'<h1>username or password is wrong</h1>'
    pass


def routes():    # 配置路由
    route_pattern = [
        ("/example", example),
        ("/login", login)
    ]
    return route_pattern


if __name__ == '__main__':

    my_server = make_server('', 9998, app=app)   # 创建server实例

    my_server.serve_forever()   # server监听

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP