Flask

Werkzeug

一個簡單的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


#一個簡單的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 是一個方法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):
       #每一個請求進來,都會進入,去到環(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就是一個簡單的WSGI Application,每一個請求都會調(diào)用Shortly app,然后調(diào)用其call函數(shù),在call函數(shù)里面,取到環(huán)境所有的環(huán)境參數(shù),然后去處理請求。
重要的環(huán)境參數(shù)有:
'werkzeug.request': <Request 'http://127.0.0.1:5000/favicon.ico' [GET]>
'HTTP_COOKIE': 'csrftoken=WVWbK0r6HIOuGD1ybGmodXUqGWDQTS1E26WlbvhnoHIe1UVc31K9bz402YwedkUC
sessionid=hjyq9l4jxu4uwe3w7nyrjgmcpdmh39qn;
'QUERY_STRING': '',

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容