[Python] Uvicorn+FastAPI快速搞定Restful API開發


安裝模塊

# 一個現代的,快速(高性能)python web框架
pip install fastapi
# 主要用於加載和提供應用程序的服務器.
pip install uvicorn

運行代碼

import uvicorn as uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()  # 必須實例化該類,啟動的時候調用
class People(BaseModel):  # 必須繼承
    name: str
    age: int
    address: str
    salary: float

# 請求根目錄
@app.get('/')
def index():
    return {'message': '歡迎來到FastApi 服務!'}

# get請求帶參數數據
@app.get('/items/{item_id}')
def items(item_id: int):
    return {'message': '歡迎' + item_id + '來到接口頁面'}

# post請求帶參數數據
@app.post('/people')
def insert(people: People):
    age = people.age
    msg = f'名字:{people.name},年齡:{age}'
    return {'success': True, 'msg': msg}
if __name__ == '__main__':
    uvicorn.run(app=app, host="127.0.0.1", port=8080)

運行命令

uvicorn main:app --reload

快速文檔

http://127.0.0.1:8000/docs
http://127.0.0.1:8000/redoc

更多內容:https://fastapi.tiangolo.com/zh/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM