Werkzeug
一個(gè)簡(jiǎn)單的WSGI應(yīng)用
"""
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
#一個(gè)簡(jiǎn)單的WSGI 應(yīng)用
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 是一個(gè)方法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):
#每一個(gè)請(qǐng)求進(jìn)來(lái)赁还,都會(huì)進(jìn)入,去到環(huán)境中的數(shù)據(jù)
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就是一個(gè)簡(jiǎn)單的WSGI Application坐漏,每一個(gè)請(qǐng)求都會(huì)調(diào)用Shortly app,然后調(diào)用其call函數(shù),在call函數(shù)里面敦姻,取到環(huán)境所有的環(huán)境參數(shù),然后去處理請(qǐng)求歧杏。
重要的環(huán)境參數(shù)有:
'werkzeug.request': <Request 'http://127.0.0.1:5000/favicon.ico' [GET]>
'HTTP_COOKIE': 'csrftoken=WVWbK0r6HIOuGD1ybGmodXUqGWDQTS1E26WlbvhnoHIe1UVc31K9bz402YwedkUC
sessionid=hjyq9l4jxu4uwe3w7nyrjgmcpdmh39qn;
'QUERY_STRING': '',