# FastAPI與Python內建wsgi :house: [回筆記首頁](https://www.mirai.tw) ###### tags: `python` `fastapi` `wsgi` [toc] WSGI (Web Server Gateway Interface) FastAPI 是一個很小的 Python wsgi/asgi server (Web Server Gateway Interface),較內建的wsgi server可以快速開發app。 我們先介紹Python內建Wsgi Server,再介紹FastAPI ## 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模組。 常用的模組有 Fastapi、Bottle、Flask與Django: Flask有wsgi與asgi模組(需搭配其他模組才行),如果需要使用到wsgi又不想寫太大的架構,Flask是最佳的選擇。 Bottle只有wsgi功能,極小需要且不再安裝其他模組、只有一個py檔,因此很適合拿來寫 Bot的app,而且它還內建http server。 Django是一個高級的 Python 網路框架,可以快速開發安全和可維護的網站。由經驗豐富的開發者構建,Django 負責處理網站開發中麻煩的部分,因此你可以專注於編寫應用程序,而無需重新開發。Django有多受歡迎? 有名的Pinterest與Instagram都是以Django所開發的,不過它的學習曲線最難。 FastApi有wsgi與asgi,近期被使用度相當高。這次我們要介紹的就是他! ## 2. FastAPI 模組 使用 FastAPI,要先安裝 pip install fastapi ### 2-1: Hello World! 第一個FastAPI app 新增 app.py ```python= from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello, World!"} ``` 它與使用內建的wsgi的程式碼簡化許多,且易懂易讀 ### 2-2: 除了Hello World外,新增一些功能 新增 app1.py ```python= from fastapi import FastAPI app=FastAPI() @app.get("/") @app.get('/hello/{name}') async def hello(name='World'): return {'Hello', name } ``` 使用微伺服器 uvicorn app1:app來執行這個app 測試 http://localhost:8000/ 與 http://localhost:8000/hello/whsh 相關連結 [Flask](https:// "title") [Django](https:// "title") [uvicorn](https://www.uvicorn.org/) Author: - [name=林奇賢]
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.