媲美go的python web框架fastapi

2021年11月21日 22:22 by wst

python高级

荣誉:

1. 2021 年最佳开源软件榜单 上榜

2. 非常高的性能,与 NodeJS 和 Go 相当

3. 自带接口文档 (个人添加,有点牵强,但特别有用)

简介:

FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。

关键特性:

  • 快速:可与 NodeJS 和 Go 比肩的极高性能(归功于 Starlette 和 Pydantic)。最快的 Python web 框架之一

  • 高效编码:提高功能开发速度约 200% 至 300%。*

  • 更少 bug:减少约 40% 的人为(开发者)导致错误。*
  • 智能:极佳的编辑器支持。处处皆可自动补全,减少调试时间。
  • 简单:设计的易于使用和学习,阅读文档的时间更短。
  • 简短:使代码重复最小化。通过不同的参数声明实现丰富功能。bug 更少。
  • 健壮:生产可用级别的代码。还有自动生成的交互式文档。
  • 标准化:基于(并完全兼容)API 的相关开放标准:OpenAPI (以前被称为 Swagger) 和 JSON Schema

上手:

安装

pip install fastapi

你还会需要一个 ASGI 服务器,生产环境可以使用 Uvicorn 或者 Hypercorn

pip install uvicorn[standard]

示例

1 创建

创建一个 main.py 文件并写入以下内容:

from typing import Optional

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}

2 运行

uvicorn main:app --reload

uvicorn main:app 命令含义如下:

  • mainmain.py 文件(一个 Python "模块")。
  • app:在 main.py 文件中通过 app = FastAPI() 创建的对象。
  • --reload:让服务器在更新代码后重新启动。仅在开发时使用该选项。

3 检查 

使用浏览器访问 http://127.0.0.1:8000/items/5?q=somequery

你将会看到如下 JSON 响应:

{"item_id": 5, "q": "somequery"}

你已经创建了一个具有以下功能的 API:

  • 通过 路径 / 和 /items/{item_id} 接受 HTTP 请求。
  • 以上 路径 都接受 GET 操作(也被称为 HTTP 方法)。
  • /items/{item_id} 路径 有一个 路径参数 item_id 并且应该为 int 类型。
  • /items/{item_id} 路径 有一个可选的 str 类型的 查询参数 q

4 交互式 API 文档

现在访问 http://127.0.0.1:8000/docs

你会看到自动生成的交互式 API 文档(由 Swagger UI生成):

5 示例升级

现在修改 main.py 文件来从 PUT 请求中接收请求体。

我们借助 Pydantic 来使用标准的 Python 类型声明请求体。

from typing import Optional

from fastapi import FastAPI

from pydantic import BaseModel


app = FastAPI()



class Item(BaseModel):

    name: str

    price: float

    is_offer: Optional[bool] = None



@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}



@app.put("/items/{item_id}")

def update_item(item_id: int, item: Item):

    return {"item_name": item.name, "item_id": item_id}

 服务器将会自动重载(因为在上面的步骤中你向 uvicorn 命令添加了 --reload 选项)

6 交互式 API 文档升级 

7 总结

总的来说,你就像声明函数的参数类型一样只声明了一次请求参数、请求体等的类型。

你使用了标准的现代 Python 类型来完成声明。

你不需要去学习新的语法、了解特定库的方法或类,等等。

只需要使用标准的 Python 3.6 及更高版本

举个例子,比如声明 int 类型:

item_id: int

或者一个更复杂的 Item 模型:

item: Item

......在进行一次声明之后,你将获得:

  • 编辑器支持,包括:
    • 自动补全
    • 类型检查
  • 数据校验:
    • 在校验失败时自动生成清晰的错误信息
    • 对多层嵌套的 JSON 对象依然执行校验
  • 转换 来自网络请求的输入数据为 Python 数据类型。包括以下数据:
    • JSON
    • 路径参数
    • 查询参数
    • Cookies
    • 请求头
    • 表单
    • 文件
  • 转换 输出的数据:转换 Python 数据类型为供网络传输的 JSON 数据:
    • 转换 Python 基础类型 (str、 int、 float、 bool、 list 等)
    • datetime 对象
    • UUID 对象
    • 数据库模型
    • ......以及更多其他类型
  • 自动生成的交互式 API 文档,包括两种可选的用户界面:
    • Swagger UI
    • ReDoc

参考:

官方文档:https://fastapi.tiangolo.com/zh/

微信文章:https://mp.weixin.qq.com/s/QDLoKcPSW_KWlLMClMEpnA 


Comments(129) Add Your Comment

MGIAjA
It is particularly good news for the rotation which has suddenly hit some trouble, but also for the long term outlook of the Mets staff <a href=http://cial.cfd>cialis without a doctor's prescription</a> So for the moment the ratings can wait
Jbnmgc
buy lipitor 40mg for sale <a href="https://lipiws.top/">buy lipitor 20mg pills</a> lipitor 40mg drug
Bvehaw
ciprofloxacin 500mg canada - <a href="https://cipropro.top/augmentin500/">buy augmentin without prescription</a> buy clavulanate tablets
Widevk
buy baycip for sale - <a href="https://metroagyl.top/azithromycin/">order generic augmentin 625mg</a> order augmentin 375mg generic
Kgmprr
ciplox medication - <a href="https://septrim.top/trimox/">buy amoxicillin 250mg generic</a> buy erythromycin pills
Vpbsxi
buy metronidazole 200mg generic - <a href="https://metroagyl.top/clindamycin/">buy cleocin no prescription</a> buy azithromycin 250mg without prescription
Egltcs
ivermectin 6mg over counter - <a href="https://keflexin.top/">ciprofloxacin order online</a> tetracycline 250mg without prescription
Ozozmg
valtrex for sale online - <a href="https://gnantiviralp.com/zovirax/">brand acyclovir 400mg</a> buy acyclovir pills for sale
Lfecrw
buy generic acillin for sale <a href="https://ampiacil.top/penicillinused/">penicillin online</a> order amoxil pills
Nacicc
flagyl 200mg brand - <a href="https://metroagyl.top/keflexcapsule/">amoxil tablet</a> purchase zithromax generic
Uxsshk
lasix 40mg cost - <a href="https://antipathogenc.com/">buy lasix 100mg sale</a> buy captopril 25mg without prescription
Chpvtx
cost metformin - <a href="https://gnantiacidity.com/lincocin/">order lincocin 500 mg sale</a> lincocin us
Mgodoq
buy retrovir 300mg pills - <a href="https://canadiangnp.com/">order generic glucophage 1000mg</a> order zyloprim 100mg pill
Tnqtqz
cost clozaril 50mg - <a href="https://genonlinep.com/pepcid/">famotidine pills</a> famotidine 40mg oral
Xfhwzn
buy cheap seroquel - <a href="https://gnkantdepres.com/eskalith/">where to buy eskalith without a prescription</a> buy eskalith cheap
Pasdya
order clomipramine generic - <a href="https://antdeponline.com/celexa/">order citalopram 40mg sale</a> buy doxepin 25mg for sale
Qrwwzo
hydroxyzine generic - <a href="https://antdepls.com/">generic atarax</a> generic endep
Cgajcr
buy augmentin 1000mg online - <a href="https://atbioinfo.com/ethambutol/">cost ethambutol 600mg</a> order cipro 500mg generic
Jdflpx
buy amoxil generic - <a href="https://atbioxotc.com/cephalexin/">buy keflex without a prescription</a> ciprofloxacin 500mg tablet
Ysvbfi
cost zithromax 250mg - <a href="https://gncatbp.com/emetronidazole/">order metronidazole 400mg generic</a> order ciplox 500 mg online cheap
Apfxkv
cleocin 150mg price - <a href="https://cadbiot.com/doxycycline/">buy doxycycline pills</a> chloramphenicol oral
Adrexf
ivermectin 12 mg for sale - <a href="https://antibpl.com/ascefaclor/">cefaclor for sale online</a> order cefaclor online cheap
Mleqbu
albuterol cheap - <a href="https://antxallergic.com/oiphenergan/">purchase promethazine without prescription</a> theophylline 400mg ca
Hqipdn
purchase medrol pills - <a href="https://ntallegpl.com/getazelastine/">purchase astelin without prescription</a> azelastine online
Lvznpm
clarinex online buy - <a href="https://rxtallerg.com/getzaditor/">ketotifen tablet</a> albuterol online order
Kkmxoa
buy micronase - <a href="https://prodeprpl.com/">buy micronase 5mg pills</a> generic forxiga 10 mg
Dnkazp
order glycomet 500mg sale - <a href="https://arxdepress.com/acarbose50/">precose 50mg generic</a> buy precose no prescription
Xbwczu
prandin 2mg us - <a href="https://depressinfo.com/">order repaglinide 2mg pills</a> purchase empagliflozin for sale
Ssrrmn
rybelsus 14 mg sale - <a href="https://infodeppl.com/ddavpspray/">desmopressin cost</a> purchase DDAVP spray
Wpfmxs
lamisil 250mg uk - <a href="https://treatfungusx.com/adiflucanv/">diflucan medication</a> griseofulvin over the counter
Kyhscq
order ketoconazole 200mg pills - <a href="https://antifungusrp.com/butenafinecream/">purchase butenafine</a> sporanox 100mg for sale
Cwulev
order famciclovir - <a href="https://amvinherpes.com/">purchase famciclovir</a> buy valaciclovir tablets
Egzkvz
buy lanoxin 250 mg for sale - <a href="https://blpressureok.com/isoptinpillmg/">calan 120mg ca</a> buy furosemide for sale diuretic
Ujizbk
lopressor price - <a href="https://bloodpresspl.com/nifedipine/">adalat 30mg pill</a> nifedipine 30mg usa
Spfbaf
order microzide 25 mg generic - <a href="https://norvapril.com/lisinopril/">order zestril 5mg generic</a> order bisoprolol 5mg generic
Iczzgx
nitroglycerin for sale online - <a href="https://nitroproxl.com/">purchase nitroglycerin without prescription</a> valsartan 160mg canada
Orltcy
rosuvastatin online sinister - <a href="https://antcholesterol.com/pravastatin/">pravastatin online mad</a> caduet pills tomorrow
Jlnuwy
zocor thunder - <a href="https://canescholest.com/atorvastatin/">lipitor flame</a> lipitor squint
Qzqjfn
buy viagra professional else - <a href="https://edsildps.com/malegra/">malegra accustom</a> levitra oral jelly wrong
Brqlxs
dapoxetine gentlemen - <a href="https://promedprili.com/suhagra/">suhagra against</a> cialis with dapoxetine cease
Aaknsr
cenforce pound - <a href="https://xcenforcem.com/tadalissxtadalafil/">tadalis din</a> brand viagra online chuckle
Hvfger
brand cialis silk - <a href="https://probrandtad.com/">brand cialis bath</a> penisole supply
Nbbqlt
brand cialis otherwise - <a href="https://probrandtad.com/brandlevitra/">brand levitra portrait</a> penisole break
Huoqnw
cialis soft tabs pills box - <a href="https://supervalip.com/cialisoraljelly/">cialis oral jelly bundle</a> viagra oral jelly dare
Tupkjl
cialis soft tabs pills ghoul - <a href="https://supervalip.com/">cialis soft tabs online westward</a> viagra oral jelly mister
Vspsbj
cenforce temper - <a href="https://xcenforcem.com/tadalissxtadalafil/">tadalis online sail</a> brand viagra online relation
Viydsv
dapoxetine mankind - <a href="https://promedprili.com/fildena/">fildena beside</a> cialis with dapoxetine ashamed
Fihtqr
acne medication peace - <a href="https://placnemedx.com/">acne medication rouse</a> acne treatment throat
Utaisf
asthma treatment four - <a href="https://bsasthmaps.com/">inhalers for asthma absence</a> asthma medication example
Cmxmao
uti antibiotics read - <a href="https://amenahealthp.com/">uti treatment dread</a> treatment for uti good
Vtpzqx
prostatitis medications ball - <a href="https://xprosttreat.com/">prostatitis medications relative</a> pills for treat prostatitis bloom
Uukkpr
valtrex online aid - <a href="https://gnantiviralp.com/">valtrex pills sheep</a> valacyclovir online shut
Rrrnxe
claritin pills trouble - <a href="https://clatadine.top/">claritin truth</a> loratadine medication thomas
Niqzeg
priligy week - <a href="https://prilixgn.top/">priligy straighten</a> dapoxetine few
Jqwwpo
claritin pills repair - <a href="https://clatadine.top/">claritin pills ashamed</a> claritin grant
Fihjlx
ascorbic acid great - <a href="https://ascxacid.com/">ascorbic acid forget</a> ascorbic acid beauty
Edjpvd
promethazine name - <a href="https://prohnrg.com/">promethazine aim</a> promethazine preparation
Vzbemi
biaxin pills everyone - <a href="https://gastropls.com/">biaxin pills amount</a> cytotec peep
Dsmoqe
florinef pills distinguish - <a href="https://gastroplusp.com/">fludrocortisone return</a> lansoprazole connection
Lmnhbw
buy cheap rabeprazole - <a href="https://gastrointesl.com/reglanmetoclop/">metoclopramide 20mg oral</a> buy motilium 10mg pills
Jzylpq
cheap bisacodyl 5mg - <a href="https://gastroinfop.com/liv52/">liv52 20mg sale</a> buy liv52 no prescription
Ojkqmi
buy eukroma cheap - <a href="https://cerazestrel.com/">generic cerazette 0.075mg</a> order dydrogesterone 10mg
Jrkfce
cotrimoxazole tablet - <a href="https://cotrioxazo.com/">buy bactrim 480mg without prescription</a> buy tobra online
Odmhye
fulvicin 250 mg uk - <a href="https://fulviseoful.com/">griseofulvin generic</a> generic gemfibrozil 300mg
Smtiyz
purchase forxiga generic - <a href="https://sineqpin.com/">buy generic doxepin for sale</a> order precose online cheap
Zofjqx
buy dramamine 50mg pills - <a href="https://actodronate.com/">purchase actonel online cheap</a> order actonel 35 mg online
Cqwhrp
buy generic vasotec 5mg - <a href="https://xalanoprost.com/">zovirax online</a> latanoprost uk
Bgmajd
etodolac brand - <a href="https://etodograph.com/">generic monograph</a> purchase pletal
Uhymvw
buy feldene 20 mg online - <a href="https://rivastilons.com/">exelon cheap</a> exelon us
Uqcvtc
piracetam tablet - <a href="https://nootquin.com/praziquantel/">cheap praziquantel</a> sinemet for sale
Xsfekd
buy hydrea generic - <a href="https://hydroydrinfo.com/trecatorsc/">buy ethionamide no prescription</a> methocarbamol 500mg price
Utchwz
depakote 250mg generic - <a href="https://adepamox.com/mefloquine/">order mefloquine online</a> brand topamax
Yolrpq
buy disopyramide phosphate for sale - <a href="https://anorpica.com/">order norpace pill</a> buy thorazine paypal
Ekraaw
order spironolactone online - <a href="https://aldantinep.com/phenytoin/">order phenytoin 100mg without prescription</a> order revia 50 mg generic
Jspkxo
purchase cytoxan generic - <a href="https://cycloxalp.com/atomoxetine/">order strattera 25mg pills</a> vastarel generic
Ghoolm
buy generic flexeril - <a href="https://abflequine.com/primaquine/">buy primaquine tablets</a> buy enalapril 10mg online cheap
Gagsbj
zofran cost - <a href="https://azofarininfo.com/tolterodine/">tolterodine uk</a> order requip 1mg generic
Yfzvnl
buy ascorbic acid - <a href="https://mdacidinfo.com/isosorbidedinitrate/">isosorbide dinitrate tablets</a> prochlorperazine pills
Zibqkw
order durex gel - <a href="https://xalaplinfo.com/latanoprosteyedrops/">cost zovirax</a> zovirax for sale online
Cabpzw
buy generic minoxidil online - <a href="https://hairlossmedinfo.com/finasteridepros/">purchase proscar generic</a> buy propecia paypal
Ovriya
order leflunomide 20mg pill - <a href="https://infohealthybones.com/calciumcarbonate/">order calcium carbonate online cheap</a> cheap cartidin generic
Blswcq
order verapamil 120mg pills - <a href="https://infoheartdisea.com/">buy cheap generic verapamil</a> tenoretic pill
Louswh
order tenormin 50mg for sale - <a href="https://heartmedinfox.com/sotalol/">buy sotalol pills</a> buy coreg 25mg online
Cwrexa
atorlip pill - <a href="https://infoxheartmed.com/enalapril/">pill vasotec 10mg</a> order generic nebivolol
Onxfeq
order gasex generic - <a href="https://herbalinfomez.com/diabecon/">buy diabecon medication</a> buy diabecon sale
Ttxtlu
buy lasuna generic - <a href="https://infoherbalmz.com/himcolin/">himcolin order online</a> purchase himcolin pills
Gctlfp
brand noroxin - <a href="https://gmenshth.com/flutamide/">eulexin generic</a> confido cheap
Trevri
finax sale - <a href="https://finmenura.com/">purchase finax sale</a> buy generic uroxatral 10mg
Baizby
buy speman tablets - <a href="https://spmensht.com/himplasia/">order himplasia online</a> order finasteride pill
Idendh
terazosin drug - <a href="https://hymenmax.com/dapoxetine/">buy dapoxetine 30mg without prescription</a> dapoxetine 30mg us
Trjhfy
trileptal price - <a href="https://trileoxine.com/">trileptal 600mg pills</a> purchase synthroid sale
Sltkto
purchase cyclosporine eye drops - <a href="https://asimusxate.com/gloperba/">how to buy colchicine</a> order colcrys 0.5mg online
Gkushq
purchase duphalac without prescription - <a href="https://duphalinfo.com/">buy lactulose without a prescription</a> buy betahistine 16 mg for sale
Pbubul
order calcort sale - <a href="https://lazacort.com/brimonidine/">purchase alphagan online</a> brimonidine order
Akvdvq
order besivance sale - <a href="https://besifxcist.com/sildamax/">buy sildamax no prescription</a> purchase sildamax without prescription
Toasbo
oral neurontin 600mg - <a href="https://aneutrin.com/sulfasalazine/">buy sulfasalazine</a> order azulfidine 500 mg generic
Unihtj
probalan drug - <a href="https://bendoltol.com/">buy probalan generic</a> cost tegretol 400mg
Cugdci
buy celecoxib without a prescription - <a href="https://celespas.com/indomethacin/">order indomethacin 50mg</a> indocin ca
Aeodnl
order colospa 135 mg without prescription - <a href="https://coloxia.com/">cost colospa</a> pletal tablet
Bpszlj
diclofenac order online - <a href="https://dicloltarin.com/aspirin/">buy aspirin online cheap</a> buy aspirin medication
Nhdjvc
order rumalaya online - <a href="https://rumaxtol.com/amitriptyline/">order amitriptyline 50mg pill</a> amitriptyline 10mg ca
Ezydyh
pyridostigmine 60 mg us - <a href="https://mestonsx.com/azathioprine/">imuran price</a> azathioprine buy online
Mjjcqr
purchase ozobax online cheap - <a href="https://baclion.com/nspiroxicam/">buy feldene sale</a> piroxicam 20mg brand
Yshuli
cheap diclofenac sale - <a href="https://vovetosa.com/">order diclofenac for sale</a> purchase nimodipine
Azbykt
order cyproheptadine 4mg online - <a href="https://periheptadn.com/">generic periactin 4 mg</a> tizanidine oral
Xczvli
meloxicam 7.5mg generic - <a href="https://meloxiptan.com/rtrizatriptan/">toradol generic</a> toradol 10mg generic
Qkrzce
buy cefdinir 300 mg sale - <a href="https://omnixcin.com/aminocycline/"></a> purchase cleocin for sale
Tkexgv
where to buy trihexyphenidyl without a prescription - <a href="https://voltapll.com.com/">trihexyphenidyl price</a> emulgel online buy
Vfnvnj
buy accutane generic - <a href="https://aisotane.com/asdeltasone/">purchase deltasone without prescription</a> buy deltasone 20mg
Fpkgfk
order deltasone 40mg generic - <a href="https://apreplson.com/permethrin/">zovirax online buy</a> order permethrin without prescription
Fpvbkn
permethrin cream - <a href="https://actizacs.com/asbenzac/">buy cheap benzoyl peroxide</a> brand tretinoin gel
Rqsmlb
buy generic betnovate 20gm - <a href="https://betnoson.com/">betnovate 20 gm cost</a> purchase monobenzone without prescription
Lezkjc
buy metronidazole 200mg pills - <a href="https://ametronles.com/">order flagyl for sale</a> buy cenforce without prescription
Ptdmpn
augmentin 1000mg oral - <a href="https://alevonted.com/">cheap levothroid sale</a> order levoxyl online
Wrqqwg
order cleocin pill - <a href="https://indometnp.com/">order indocin generic</a> indocin 75mg price
Fqxekh
losartan 50mg pills - <a href="https://cozartan.com/">hyzaar uk</a> cephalexin 250mg oral
Kopdwd
purchase crotamiton sale - <a href="https://aeuracream.com/abactroban/">mupirocin for sale</a> purchase aczone without prescription
Ujzznu
provigil 200mg uk - <a href="https://sleepagil.com/melatonin/">cost melatonin 3mg</a> buy meloset without a prescription
Aohkfq
order zyban generic - <a href="https://bupropsl.com/shuddhaguggulu/">cheap shuddha guggulu sale</a> cost shuddha guggulu
Eozjhm
capecitabine uk - <a href="https://xelocap.com/mefenamicacid/">mefenamic acid sale</a> order danocrine without prescription
Cjqmxx
prometrium 200mg usa - <a href="https://apromid.com/clomipheneferto/">fertomid sale</a> generic fertomid
Syjbwx
fosamax 35mg usa - <a href="https://pilaxmax.com/medroxyprogesterone/">buy provera 5mg without prescription</a> order medroxyprogesterone 5mg without prescription
Rjxkqf
order norethindrone 5 mg pills - <a href="https://norethgep.com/lumigan/">lumigan online</a> how to buy yasmin
Mngefa
estradiol 1mg cheap - <a href="https://festrolp.com/letrozole/">buy femara for sale</a> buy anastrozole 1mg
Ggjxxp
buy generic dostinex online - <a href="https://adostilin.com/">brand cabergoline 0.25mg</a> purchase alesse sale
Pntgpd
プレドニン おすすめ - <a href="https://jpaonlinep.com/">プレドニン の購入</a> 正規品ジスロマック錠の正しい処方
Wqyeec
バイアグラ どこで買える - <a href="https://jpedpharm.com/">バイアグラ おすすめ</a> タダラフィル の購入
Grivbv
プレドニン 薬局で買える - <a href="https://jpanfarap.com/jpadoxycycline/">ドキシサイクリンジェネリック 通販</a> アキュテイン通販 安全
Idajmc
eriacta thorough - <a href="https://eriagra.com/asildigrah/">sildigra mix</a> forzest stable