标签:world sock one html text utf-8 main httpd finalize
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)
程序启动之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
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)
标签:world sock one html text utf-8 main httpd finalize
原文地址:https://www.cnblogs.com/liubing8/p/11930066.html