目录
- 01 werkzurg了解wsgi
- 1. wsgi
- 2. flask之werkzurg源码流程
- 3. 总结
01 werkzurg了解wsgi
1. wsgi
django和flask内部都没有实现socket,而是wsgi实现。
wsgi是web服务网关接口,他是一个协议,实现它的协议的有:wsgiref/werkzurg/uwsgi
- django之前
from wsgiref.simple_server import make_server def run(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return [bytes('<h1>Hello, web!</h1>', encoding='utf-8'), ] if __name__ == '__main__': httpd = make_server('127.0.0.1', 8000, run) httpd.serve_forever()
- flask之前
from werkzeug.serving import run_simple from werkzeug.wrappers import BaseResponse def func(environ, start_response): print('请求来了') response = BaseResponse('你好') return response(environ, start_response) if __name__ == '__main__': run_simple('127.0.0.1', 5000, func)
2. flask之werkzurg源码流程
- 程序启动之
app.run()
from flask import Flask app = Flask(__name__) @app.route('/index') def index(): return 'hello world' if __name__ == '__main__': app.run()
- 执行里边
run_simple
方法的第三个参数加括号def run(self, host=None, port=None, debug=None, load_dotenv=True, **options): from werkzeug.serving import run_simple run_simple(host, port, self, **options)
- 触发执行
__call__
方法,然后去执行wsgi_app
方法def __call__(self, environ, start_response): return self.wsgi_app(environ, start_response)
- 执行
wsgi_app
方法里边的full_dispatch_request
方法def wsgi_app(self, environ, start_response): response = self.full_dispatch_request() return response(environ, start_response)
full_dispatch_request
def full_dispatch_request(self): return self.finalize_request(rv)
- 执行
finalize_request
方法,携带rv参数,rv为视图的返回值def finalize_request(self, rv, from_error_handler=False): response = self.make_response(rv) return response
- 执行
finalize_request
方法里边的make_response
方法def make_response(self, rv): if not isinstance(rv, self.response_class): if isinstance(rv, (text_type, bytes, bytearray)): rv = self.response_class(rv, status=status, headers=headers) return rv
response_class
response_class
=Response
Response
继承werkzurg的BaseResponse
3. 总结
- 请求过来,经过一系列,最后由BaseResponse返回
from werkzeug.serving import run_simple
from werkzeug.wrappers import BaseResponse
def func(environ, start_response):
print('请求来了')
response = BaseResponse('你好')
return response(environ, start_response)
if __name__ == '__main__':
run_simple('127.0.0.1', 5000, func)
原文地址:https://www.cnblogs.com/liubing8/p/11930066.html
时间: 2024-11-05 14:54:04