python 開發api_使用FastAPI和Python快速開發高性能API

python 開發api

If you have read some of my previous Python articles, you know I’m a Flask fan. It is my go-to for building APIs in Python. However, recently I started to hear a lot about a new API framework for Python called FastAPI. After building some APIs with it, I can say it is amazing!

如果您閱讀過我以前的一些Python文章,您就會知道我是Flask的粉絲。 這是我用Python構建API的必修課。 但是,最近我開始聽到很多關于Python的新API框架FastAPI的信息 。 用它構建了一些API之后,我可以說它很棒!

This project was created by Sebastian Ramírez, and at the time of writing, it has accumulated almost 20K stars. Big names like Microsoft, Uber, Netflix, and others have been building APIs with it.

這個項目是由塞巴斯蒂安·拉米雷斯 ( SebastianRamírez)創建的,在撰寫本文時,它已經積累了近2萬顆星。 像Microsoft,Uber,Netflix等大公司都在使用它來構建API。

But why is this new library so popular and how does it compare to Flask or Django?

但是,為什么這個新庫如此受歡迎?與Flask或Django相比,它又如何呢?

特征 (Features)

FastAPI is a rather minimalistic framework. However, that doesn’t make it less powerful. FastAPI is built using modern Python concepts and is based on Python 3.6 type declarations. Let’s see some of the features this library is packed with.

FastAPI是一個相當簡單的框架。 但是,這并不會使它的功能降低。 FastAPI是使用現代Python概念構建的,并且基于Python 3.6類型聲明。 讓我們看一下該庫附帶的一些功能。

自動文檔 (Automatic docs)

A must-have for any API is documentation about the endpoints and types. A common approach to solve this problem is the use of OpenAPI and tools like Swagger UI or ReDoc to present the information. These come packed automatically with FastAPI, allowing you to focus more on your code than setting up tools.

任何API的必備組件都是有關端點和類型的文檔。 解決此問題的常用方法是使用OpenAPI和諸如Swagger UI或ReDoc之類的工具來顯示信息。 這些都與FastAPI自動打包在一起,使您可以比設置工具更專注于代碼。

鍵入Python (Typed Python)

This is a big one: FastAPI makes use of Python 3.6 type declarations (thanks to Pydantic). This means that it uses a Python feature that allows you to specify the type of a variable. And this framework makes extensive use out of it, providing you with great editor support. Autocompletion works amazingly well.

這是一個很大的問題:FastAPI使用Python 3.6類型聲明(感謝Pydantic)。 這意味著它使用Python功能,可讓您指定變量的類型。 并且該框架對其進行了廣泛使用,為您提供了強大的編輯器支持。 自動補全效果非常好。

Here is some sample code using typed declarations:

這是一些使用類型聲明的示例代碼:

We just went from:

我們剛從:

name

to:

至:

name: str

That’s it! And as a result:

而已! 結果是:

Image for post
Autocompletion in FastAPI using PyCharm
使用PyCharm在FastAPI中自動完成

Beautiful!

美麗!

驗證方式 (Validation)

Validation is already integrated into this framework thanks to Pydantic. You can validate standard Python types as well as some custom field validations. Here are a few examples:

由于Pydantic,驗證已集成到此框架中。 您可以驗證標準Python類型以及一些自定義字段驗證。 這里有一些例子:

  • JSON objects (dict)

    JSON對象( dict )

  • JSON array (list)

    JSON數組( list )

  • String (str) with min and max lengths

    最小長度和最大長度的字符串( str )

  • Numbers (int, float) with min and max values

    帶有最小值和最大值的數字( intfloat )

  • URL

    網址
  • Email

    電子郵件
  • UUID

    UUID
  • And many more…

    還有很多…

安全與認證 (Security and authentication)

This is a crucial part of any API and it’s code that we usually just repeat, so why not integrate much of it into the framework? FastAPI does exactly that.

這是任何API的關鍵部分,我們通常只重復其中的代碼,那么為什么不將其大量集成到框架中呢? FastAPI正是這樣做的。

The library provides support for the following:

該庫提供以下支持:

  • HTTP Basic

    HTTP基本
  • OAuth2 (JWT tokens)

    OAuth2(JWT令牌)
  • API keys in headers, query params, or cookies.

    標頭,查詢參數或cookie中的API密鑰。

文獻資料 (Documentation)

This is perhaps not exactly a feature of the framework, but it is worth mentioning. The documentation of the project is simply amazing. It’s very clear and covers topics with examples and explanations.

這也許不是框架的確切功能,但是值得一提。 該項目的文檔簡直太神奇了。 這非常清楚,并通過示例和解釋涵蓋了主題。

性能 (Performance)

FastAPI is fast! It is not only fast to code, but it also processes requests super fast! You can check the benchmarks across multiple frameworks using the TechEmpower benchmark tool. Here are the results I got for Python frameworks. Flask and Django are way behind on the list, with FastAPI being first and thus the most performant:

FastAPI很快! 它不僅可以快速編碼,而且還可以超快地處理請求! 您可以使用TechEmpower基準測試工具來檢查多個框架中的基準 。 這是我為Python框架獲得的結果。 Flask和Django排在后面,FastAPI排名第一,因此也是性能最高的:

Image for post
TechEmpower benchmark results
TechEmpower基準測試結果

自然異步 (Asynchronous by Nature)

Let’s take a look at the following code:

讓我們看下面的代碼:

@app.post("/item/", response_model=Item)
async def create_item(item: Item):
result = await some_code_running_in_background(item)
return result

Is that JavaScript? I promise you it is not. Looks familiar, though, right? That snippet is actually Python using async methods.

那是JavaScript嗎? 我向你保證不是。 看起來很熟悉,對吧? 該片段實際上是使用異步方法的Python。

FastAPI supports asynchronous endpoints by default, which can simplify and make your code more efficient. This is a huge advantage over Flask. Django already made some async support work, but it is not as integrated as it is in FastAPI.

FastAPI默認情況下支持異步端點,這可以簡化并提高代碼效率。 與Flask相比,這是一個巨大的優勢。 Django已經進行了一些異步支持工作,但是集成程度不如FastAPI。

結論 (Conclusion)

FastAPI is a relatively new framework that follows the minimalist approach of Flask but adds crucial features that make it easier to work with and stunningly performant. It is a great choice for your next API project, and I will be writing more about it as I use it more and more on my APIs.

FastAPI是一個相對較新的框架,它遵循Flask的極簡主義方法,但增加了一些關鍵功能,使其更易于使用且性能驚人。 對于您的下一個API項目來說,這是一個不錯的選擇,隨著我在API上越來越多地使用它,我將對此進行更多的寫作。

Thanks for reading!

謝謝閱讀!

翻譯自: https://medium.com/better-programming/quickly-develop-highly-performant-apis-with-fastapi-and-python-4ac1f252c935

python 開發api

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/388087.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388087.shtml
英文地址,請注明出處:http://en.pswp.cn/news/388087.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Purley平臺Linpak測試,從踏坑開始一步步優化

Purley平臺Linpak測試,從踏坑開始一步步優化 #記2017年11月第一次踏坑事件 測試平臺配置: 6nodes CPU: Intel Gold 6132 2.6GHz 14C RAM: 8G *12 2666MHz NET: Infiband FDR OS: centos7.2 mpi: Intel-mpi hpl: xhpl.intel 開始踏第一坑 現象&#xff1a…

基于easyui開發Web版Activiti流程定制器詳解(一)——目錄結構

題外話(可略過): 前一段時間(要是沒記錯的話應該是3個月以前)發布了一個更新版本,很多人說沒有文檔看著比較困難,所以打算拿點時間出來詳細給大家講解一下,…

HDOJ 2037:今年暑假不AC_大二寫

AC代碼&#xff1a; #include <iostream> #include <cstdio> #include <algorithm> #define Max 105 using namespace std;struct TimeList {int start;int end; }timelist[Max]; bool compare(TimeList a, TimeList b) {if(a.end b.end)return a.start &l…

基于easyui開發Web版Activiti流程定制器詳解(二)——文件列表

&#xfeff;&#xfeff;上一篇我們介紹了目錄結構&#xff0c;這篇給大家整理一個文件列表以及詳細說明&#xff0c;方便大家查找文件。 由于設計器文件主要保存在wf/designer和js/designer目錄下&#xff0c;所以主要針對這兩個目錄進行詳細說明。 wf/designer目錄文件詳解…

杭電oj2047-2049、2051-2053、2056、2058

2047 阿牛的EOF牛肉串 1 #include<stdio.h>2 3 int main(){4 int n,i;5 _int64 s[51];6 while(~scanf("%d",&n)){7 s[1]3;s[2]8;8 for(i3;i<n;i){9 s[i] s[i-1]*2 s[i-2]*2; 10 } 11 print…

Power BI:M與DAX以及度量與計算列

When I embarked on my Power BI journey I was almost immediately slapped with an onslaught of foreign and perplexing terms that all seemed to do similar, but somehow different, things.當我開始Power BI之旅時&#xff0c;我幾乎立刻受到了外國和困惑術語的沖擊&am…

git 基本命令和操作

設置全局用戶名密碼 $ git config --global user.name runoob $ git config --global user.email testrunoob.comgit init:初始化倉庫 創建新的 Git 倉庫 git clone: 拷貝一個 Git 倉庫到本地 : git clone [url]git add:將新增的文件添加到緩存 : git add test.htmlgit status …

基于easyui開發Web版Activiti流程定制器詳解(三)——頁面結構(上)

&#xfeff;&#xfeff;上一篇介紹了定制器相關的文件&#xff0c;這篇我們來看看整個定制器的界面部分&#xff0c;了解了頁面結構有助于更好的理解定制器的實現&#xff0c;那么現在開始吧&#xff01; 首先&#xff0c;我們來看看整體的結構&#xff1a; 整體結構比較簡單…

bzoj 4300 絕世好題 —— 思路

題目&#xff1a;https://www.lydsy.com/JudgeOnline/problem.php?id4300 記錄一下 mx[j] 表示以第 j 位上是1的元素結尾的子序列長度最大值&#xff0c;轉移即可。 代碼如下&#xff1a; #include<iostream> #include<cstdio> #include<cstring> #include&…

基于easyui開發Web版Activiti流程定制器詳解(四)——頁面結構(下)

&#xfeff;&#xfeff;題外話&#xff1a; 這兩天周末在家陪老婆和兒子沒上來更新請大家見諒&#xff01;上一篇介紹了調色板和畫布區的頁面結構&#xff0c;這篇講解一下屬性區的結構也是定制器最重要的一個頁面。 屬性區整體頁面結構如圖&#xff1a; 在這個區域可以定義工…

梯度下降法優化目標函數_如何通過3個簡單的步驟區分梯度下降目標函數

梯度下降法優化目標函數Nowadays we can learn about domains that were usually reserved for academic communities. From Artificial Intelligence to Quantum Physics, we can browse an enormous amount of information available on the Internet and benefit from it.如…

FFmpeg 是如何實現多態的?

2019獨角獸企業重金招聘Python工程師標準>>> 前言 眾所周知&#xff0c;FFmpeg 在解碼的時候&#xff0c;無論輸入文件是 MP4 文件還是 FLV 文件&#xff0c;或者其它文件格式&#xff0c;都能正確解封裝、解碼&#xff0c;而代碼不需要針對不同的格式做出任何改變&…

基于easyui開發Web版Activiti流程定制器詳解(五)——Draw2d詳解(一)

&#xfeff;&#xfeff;背景&#xff1a; 小弟工作已有十年有余&#xff0c;期間接觸了不少工作流產品&#xff0c;個人比較喜歡的還是JBPM&#xff0c;因為出自名門Jboss所以備受推崇&#xff0c;但是現在JBPM版本已經與自己當年使用的版本&#xff08;3.X&#xff09;大相徑…

Asp.net MVC模型數據驗證擴展ValidationAttribute

在Asp.Mvc項目中有自帶的一套完整的數據驗證功能&#xff0c;客戶端可以用HtmlHelper工具類&#xff0c;服務端可以用ModelState進行驗證。而他們都需要System.ComponentModel.DataAnnotations類庫中的特性功能&#xff0c;通過在屬性上方添加特性就可以達到驗證前后端驗證數據…

seaborn 子圖_Seaborn FacetGrid:進一步完善子圖

seaborn 子圖Data visualizations are essential in data analysis. The famous saying “one picture is worth a thousand words” holds true in the scope of data visualizations as well. In this post, I will explain a well-structured, very informative collection …

基于easyui開發Web版Activiti流程定制器詳解(六)——Draw2d的擴展(一)

&#xfeff;&#xfeff;題外話&#xff1a; 最近在忙公司的云項目空閑時間不是很多&#xff0c;所以很久沒來更新&#xff0c;今天補上一篇&#xff01; 回顧&#xff1a; 前幾篇介紹了一下設計器的界面和Draw2d基礎知識&#xff0c;這篇講解一下本設計器如何擴展Draw2d。 進…

深度學習網絡總結

1.Siamese network Siamese [sai? mi:z] 孿生 左圖的孿生網絡是指兩個網絡通過共享權值實現對輸入的輸出&#xff0c;右圖的偽孿生網絡則不共享權值(pseudo-siamese network)。 孿生神經網絡是用來衡量兩個輸入的相似度&#xff0c;可以用來人臉驗證、語義相似度分析、QA匹配…

異常檢測時間序列_時間序列的無監督異常檢測

異常檢測時間序列To understand the normal behaviour of any flow on time axis and detect anomaly situations is one of the prominent fields in data driven studies. These studies are mostly conducted in unsupervised manner, since labelling the data in real lif…

python設計模式(七):組合模式

組合&#xff0c;將對象組合成樹狀結構&#xff0c;來表示業務邏輯上的[部分-整體]層次&#xff0c;這種組合使單個對象和組合對象的使用方法一樣。 如描述一家公司的層次結構&#xff0c;那么我們用辦公室來表示節點&#xff0c;則總經理辦公司是根節點&#xff0c;下面分別由…

Django框架是什麼?

Django在新一代的Web框架中非常出色,為什么這么說呢&#xff1f;為回答該問題,讓我們考慮一下不使用框架設計Python網頁應用程序的情形.貫穿整本書,我們多次展示不使用框架實現網站基本功能的方法,讓讀者認識到框架開發的方便,&#xff08;不使用框架,更多情況是沒有合適的框架…