# Flask與Python內建wsgi :house: [回筆記首頁](https://www.mirai.tw) ###### tags: `python` `flask `wsgi` [toc] WSGI (Web Server Gateway Interface) Bottle 是一個很小的 Python wsgi server (Web Server Gateway Interface),較內建的wsgi server可以快速開發app。 我們先介紹Python內建Wsgi Server,再介紹Bottle ## 1. python內建wsgi 新增wsgi.py,內容如下 ```python= from wsgiref.simple_server import make_server def application(environ, start_response): status = '200 OK' headers = [('Content-Type', 'text/html; charset=utf8')] start_response(status, headers) return [b'Hello, World!'] if __name__ == '__main__': print('Starting server now...') try: httpd = make_server('127.0.0.1', 8000, application) print('Successful! Press Ctrl-C to stop the server.') httpd.serve_forever() except: print('Stop service!') ``` 在python環境中執行 python wsgi.py http://127.0.0.1:8000 Hello World! [成功!!!] 但這個陽春的wsgi使用起來卻極不方便,自己要處理Get、Post與傳入參數。 因此我們建議使用現成的wsgi模組。 常用的模組有 Bottle、Flask與Django: Flask有wsgi與asgi模組(需搭配其他模組才行),如果需要使用到wsgi又不想寫太大的架構,Flask是最佳的選擇。 Bottle只有wsgi功能,極小需要且不再安裝其他模組、只有一個py檔,因此很適合拿來寫 Bot的app,而且它還內建http server。 Django是一個高級的 Python 網路框架,可以快速開發安全和可維護的網站。由經驗豐富的開發者構建,Django 負責處理網站開發中麻煩的部分,因此你可以專注於編寫應用程序,而無需重新開發。Django有多受歡迎? 有名的Pinterest與Instagram都是以Django所開發的,不過它的學習曲線最難。 ## 2. Flask 模組 使用 flask,要先安裝 pip install flask ### 2-1: Hello World! 第一個flask app 新增 myapp.py 它比使用內建的wsgi的程式碼簡化許多,且易懂易讀 ```python from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' ``` 執行myapp.py的方法(Flask官方的建議方法) ```bash= $ (Linux的bash/csh) $ export FLASK_APP=myapp.py $ export FLASK_DEBUG=on $ (Windows的power shell) $ $env:FLASK_APP = "myapp" $ $env:FLASK_DEBUG = "on" $ (Windows的cmd) $ set FLASK_APP=myapp $ set FLASK_DEBUG=on $ flask run --port 8000 或 執行 python myapp.py 在開發階段要加上可使得flask具備Hot reload功能,不需要一直關閉與重啟。 ``` ### 2-2: 除了Hello World外,新增一些功能 新增 myapp1.py ```python= from flask import Flask app=Flask(__name__) @app.route('/') @app.route('/hello/') @app.route('/hello/<name>') def hello(name='World'): return 'Hello %s !' % name ``` 執行與測試的方法同 myapp.py 測試 http://localhost:8000/ 與 http://localhost:8000/hello/whsh ## 3. 使用Gunicorn將Flask API背景執行 Gunicorn 又稱綠色獨角獸(源於icon)是Python Web服務器網關接口HTTP服務器 pip install gunicorn ```python= # myapp2.py from flask import Flask app=Flask(__name__) @app.route('/') def hello(): return 'Hello World!' if __name__ == '__main__': app.run(host='0.0.0.0',port=8000) gunicorn -w 1 -b 0.0.0.0:8000 myapp2:app 背景執行(登出後依然會執行) gunicorn -w 1 -b 0.0.0.0:8000 myapp2:app --daemon 相關連結 [Flask入門指南](https://devs.tw/post/448) [Flask2.2官方文件](https://flask.palletsprojects.com/en/2.2.x/) Author: - [name=林奇賢]