Flask
2024-01-13 本文已影响0人
倔犟的贝壳
Werkzeug
一个简单的WSGI应用
"""
created by 贝壳 on 2022/5/4
"""
__autor__ = 'shelly'
import os
import redis
from werkzeug.urls import url_parse
from werkzeug.wrappers import Request, Response
from werkzeug.routing import Map, Rule
from werkzeug.exceptions import HTTPException, NotFound
from werkzeug.middleware.shared_data import SharedDataMiddleware
from werkzeug.utils import redirect
from jinja2 import Environment, FileSystemLoader
#一个简单的WSGI 应用
class Shortly(object):
def __init__(self, config):
self.redis = redis.Redis(
config['redis_host'], config['redis_port'], decode_responses=True
)
def dispatch_request(self, request):
return Response('Hello World!')
def wsgi_app(self, environ, start_response):
#start_response 是一个方法function WSGIRequestHandler.run_wsgi.<locals>.start_response
request = Request(environ)
response = self.dispatch_request(request)
return response(environ, start_response)
def __call__(self, environ, start_response):
#每一个请求进来,都会进入,去到环境中的数据
return self.wsgi_app(environ, start_response)
def create_app(redis_host='localhost', redis_port=6379, with_static=True):
app = Shortly({
'redis_host': redis_host,
'redis_port': redis_port
})
#optionally with a piece of WSGI middleware that exports all the files on the static folder on the web
if with_static:
app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
'/static': os.path.join(os.path.dirname(__file__), 'static')
})
return app
if __name__ == '__main__':
from werkzeug.serving import run_simple
app = create_app()
run_simple('127.0.0.1', 5000, app, use_debugger=True, use_reloader=True)
Shortly就是一个简单的WSGI Application,每一个请求都会调用Shortly app,然后调用其call函数,在call函数里面,取到环境所有的环境参数,然后去处理请求。
重要的环境参数有:
'werkzeug.request': <Request 'http://127.0.0.1:5000/favicon.ico' [GET]>
'HTTP_COOKIE': 'csrftoken=WVWbK0r6HIOuGD1ybGmodXUqGWDQTS1E26WlbvhnoHIe1UVc31K9bz402YwedkUC
sessionid=hjyq9l4jxu4uwe3w7nyrjgmcpdmh39qn;
'QUERY_STRING': '',