Flask之旅: 寫一個簡單的Python Web框架
下面圖來自網上:

WSGI

為什麼需要建立WSGI規範
pep-3333建議在Web伺服器和Web應用程式/Web框架之家建立一種簡單統一的介面規範, 即Python Web伺服器閘道器介面(簡稱WSGI)。以確保Web應用程式在不同的Web伺服器之間具有可移植性。
參考資料
編寫程式碼
程式碼部分參考的是 手擼個簡單的 python web 框架教程 , 我覺得這個python童鞋講的挺好。
# wsgi_demo.py import pprint # 匯入python內建的wsgi server from wsgiref.simple_server import make_server def application(environ, start_response): """ :param environ: 包含一些特定的WSGI環境資訊的字典, 由WSGI伺服器提供 :param start_response:生成WSGI響應的回掉函式, 接受兩個必要的位置引數和一個可選引數。status,response_headers和 exc_info :return: 響應體的的迭代器 """ pprint.pprint(environ) status = '200 ok' response_headers = [('Content-type', 'text/html;charset=utf8')] start_response(status, response_headers) return ['<h1>Hello, web!</h1>'.encode()] if __name__ == '__main__': httpd = make_server('0.0.0.0', 5000, application) httpd.serve_forever() 複製程式碼
通過命令列跑起這個server.
python wsgi_demo.py 複製程式碼
通過另外一個命令列使用curl連結:
~$ curl http://0.0.0.0:5000/ <h1>Hello, web!</h1> 複製程式碼
常用的environ
environ字典被用來包含這些CGI環境變數。 關於理解CGI/WSGI/uWSGI可以看看這個解釋 tornado cgi wsgi uwsgi之間的關係?
1. REQUEST_METHOD HTTP的請求方式,比如 "GET" 或者 "POST"。這個引數永遠不可能是空字串,故必須指定。 2. PATH_INFO URL請求中‘路徑’(‘path’)的其餘部分,指定請求的目標在應用程式內部的虛擬位置。如果請求的目標是應用程式根目錄並且末尾沒有'/'符號結尾的話,那麼PATH_INFO可能為空字串 。 3. QUERY_STRING URL請求中緊跟在“?”後面的那部分,它可以為空或不存在。 4. CONTENT_TYPE HTTP請求中Content-Type欄位包含的所有內容,它可以為空或不存在。 5. HTTP_ 變數組 這組變數對應著客戶端提供的HTTP請求報頭(即那些名字以 “HTTP_” 開頭的變數) ... 複製程式碼
我們其實上面通過
pprint.pprint(environ) 複製程式碼
可以檢視到裡面所包含的資訊。
{ 'Apple_PubSub_Socket_Render':'/private/tmp/com.apple.launchd.9BSE0tnnTO/Render', 'CLICOLOR': '1', 'COLORFGBG': '7;0', 'COLORTERM': 'truecolor', 'CONTENT_LENGTH': '', 'CONTENT_TYPE': 'text/plain', 'FLUTTER_STORAGE_BASE_URL': 'https://storage.flutter-io.cn', 'GATEWAY_INTERFACE': 'CGI/1.1', 'GOBIN': '/Users/xx/Documents/goBin', 'GOPATH': '/Users/xx/Documents/goWorkPlace', 'GOROOT': '/usr/local/go', 'HOME': '/Users/xx', 'HTTP_ACCEPT': '*/*', 'HTTP_HOST': '0.0.0.0:5000', 'HTTP_USER_AGENT': 'curl/7.54.0', 'ITERM_PROFILE': 'Default', 'ITERM_SESSION_ID': 'w0t0p0:D66287F5-65FC-4141-94AC-06A1B3CBEAE4', 'LANG': 'zh_CN.UTF-8', 'LOGNAME': 'xx', 'LSCOLORS': 'exfxhxhxgxhxhxgxgxbxbx', 'PATH': '/Users/xx/.local/share/virtualenvs/flask-demo-MqfCTpGB/bin:/Users/xx/Documents/flutter/bin:/Users/xx/.pyenv/plugins/pyenv-virtualenv/shims:/Users/xx/.pyenv/plugins/pyenv-virtualenv/shims:/Users/xx/.pyenv/shims:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin:/Users/xx/.local/bin:/usr/local/go/bin:/Users/xx/Documents/goBin', 'PATH_INFO': '/', 'PIPENV_ACTIVE': '1', 'PIP_DISABLE_PIP_VERSION_CHECK': '1', 'PIP_PYTHON_PATH': '/Users/xx/.pyenv/versions/3.6.0/bin/python3.6', 'PS1': '(flask-demo) \\[\\033[01;33m\\]\\u \\W\\$\\[\\033[00m\\] ', 'PUB_HOSTED_URL': 'https://pub.flutter-io.cn', 'PWD': '/Users/xx/Documents/GitHub/flask-demo', 'PYENV_SHELL': 'bash', 'PYENV_VIRTUALENV_INIT': '1', 'PYTHONDONTWRITEBYTECODE': '1', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_HOST': '', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'XxdeMacBook-Pro.local', 'SERVER_PORT': '5000', 'SERVER_PROTOCOL': 'HTTP/1.1', 'SERVER_SOFTWARE': 'WSGIServer/0.2', 'SHELL': '/bin/bash', 'SHLVL': '2', 'SSH_AUTH_SOCK': '/private/tmp/com.apple.launchd.qMWayGCpdP/Listeners', 'TERM': 'xterm-256color', 'TERM_PROGRAM': 'iTerm.app', 'TERM_PROGRAM_VERSION': '3.2.0', 'TERM_SESSION_ID': 'w0t0p0:D66287F5-65FC-4141-94AC-06A1B3CBEAE4', 'TMPDIR': '/var/folders/6g/kjvjmf8j59j2tf2mm360dqjm0000gn/T/', 'USER': 'xx', 'VIRTUAL_ENV': '/Users/xx/.local/share/virtualenvs/flask-demo-MqfCTpGB', 'XPC_FLAGS': '0x0', 'XPC_SERVICE_NAME': '0', '_': '/Users/xx/.local/share/virtualenvs/flask-demo-MqfCTpGB/bin/python', '__CF_USER_TEXT_ENCODING': '0x1F5:0x19:0x34', 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'wsgi.file_wrapper': <class 'wsgiref.util.FileWrapper'>, 'wsgi.input': <_io.BufferedReader name=6>, 'wsgi.multiprocess': False, 'wsgi.multithread': True, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0) } 複製程式碼
在application裡面我們通過environ獲得我們需要的很多引數, 比如請求的查詢字串等。
封裝Request物件
# request.py from six.moves import urllib class Request(object): """接受environ引數, 然後一些子函式供外界使用去獲取需要的值""" def __init__(self, environ): self.environ = environ def args(self): """ 把查詢引數轉成字典形式 """ get_arguments = urllib.parse.parse_qs( self.environ['QUERY_STRING'] ) return {k: v[0] for k, v in get_arguments.items()} def path(self): return self.environ['PATH_INFO'] 複製程式碼
封裝Response物件
# response.py import http.client from six.moves import urllib from wsgiref.headers import Headers class Response(object): """返回內容, 狀態碼, 字元編碼, 返回型別等""" def __init__(self, response=None, status=200, charset='utf-8', content_type='text/html'): self.response = [] if response is None else response self.charset = charset self.headers = Headers() content_type = '{content_type}; charset={charset}'.format( content_type=content_type, charset=charset) self.headers.add_header('content-type', content_type) self._status = status @property def status(self): status_string = http.client.responses.get(self._status, 'UNKNOWN') return '{status} {status_string}'.format( status=self._status, status_string=status_string) def __iter__(self): for val in self.response: if isinstance(val, bytes): yield val else: yield val.encode(self.charset) 複製程式碼
裝飾器函式
# transfer.py from request import Request def request_response_application(func): """把WSGI 函式轉換成使用Request/Response 物件""" def application(environ, start_response): request = Request(environ) response = func(request) start_response( response.status, response.headers.items() ) return iter(response) return application 複製程式碼
改版後的demo
# wsgi_demo.py import pprint # 匯入python內建的wsgi server from wsgiref.simple_server import make_server from transfer import request_response_application from response import Response @request_response_application def application(request): # 獲取查詢字串中的 name name = request.args().get('name', 'default_name') return Response(['<h1>hello {name}</h1>'.format(name=name)]) if __name__ == '__main__': httpd = make_server('0.0.0.0', 5000, application) httpd.serve_forever() 複製程式碼
測試demo
python wsgi_demo.py 複製程式碼
預設情況:
~$ curl http://0.0.0.0:5000/ <h1>hello default_name</h1> 複製程式碼
帶有name的查詢字串
~$ curl http://0.0.0.0:5000/demo?name=kobe <h1>hello kobe</h1> 複製程式碼