(完结篇)Python框架FastAPI:比Flask和Tornada更高性能的API 框架
0
前言
前几天给大家分别分享了(入门篇)简析Python web框架FastAPI——一个比Flask和Tornada更高性能的API 框架和(进阶篇)Python web框架FastAPI——一个比Flask和Tornada更高性能的API 框架。今天欢迎大家来到 FastAPI 系列分享的完结篇,本文主要是对于前面文章的补充和扩展。
当然这些功能在实际开发中也扮演者极其重要的角色。
1
中间件的使用
Flask 有 钩子函数,可以对某些方法进行装饰,在某些全局或者非全局的情况下,增添特定的功能。
同样在 FastAPI 中也存在着像钩子函数的东西,也就是中间件 Middleware了。
计算回调时间
-- coding: UTF-8 --
import time
from fastapi import FastAPI
from starlette.requests import Request
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time() response = await call_next(request) process_time = time.time() - start_time response.headers["X-Process-Time"] = str(process_time) print(response.headers) return response
@app.get("/")
async def main():
return {"message": "Hello World"}
if name == '__main__':
import uvicorn uvicorn.run(app, host="127.0.0.1", port=8000)
请求重定向中间件
from fastapi import FastAPI
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
app = FastAPI()
app.add_middleware(HTTPSRedirectMiddleware)
被重定向到 301
@app.get("/")
async def main():
return {"message": "Hello World"}
授权允许 Host 访问列表(支持通配符匹配)
from fastapi import FastAPI
from starlette.middleware.trustedhost import TrustedHostMiddleware
app = FastAPI()
app.add_middleware(
TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"]
)
@app.get("/")
async def main():
return {"message": "Hello World"}
跨域资源共享
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
app = FastAPI()
允许跨域请求的域名列表(不一致的端口也会被视为不同的域名)
origins = [
"https://gzky.live", "https://google.com", "http://localhost:5000", "http://localhost:8000",
]
通配符匹配,允许域名和方法
app.add_middleware(
CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"],
)
在前端 ajax 请求,出现了外部链接的时候就要考虑到跨域的问题,如果不设置允许跨域,浏览器就会自动报错,跨域资源 的安全问题。
所以,中间件的应用场景还是比较广的,比如爬虫,有时候在做全站爬取时抓到的 Url 请求结果为 301,302, 之类的重定向状态码,那就有可能是网站管理员设置了该域名(二级域名) 不在 Host 访问列表 中而做出的重定向处理,当然如果你也是网站的管理员,也能根据中间件做些反爬的措施。
更多中间件参考 https://fastapi.tiangolo.com/advanced/middleware
2
BackgroundTasks
创建异步任务函数,使用 async 或者普通 def 函数来对后端函数进行调用。
发送消息
-- coding: UTF-8 --
from fastapi import BackgroundTasks, Depends, FastAPI
app = FastAPI()
def write_log(message: str):
with open("log.txt", mode="a") as log: log.write(message)
def get_query(background_tasks: BackgroundTasks, q: str = None):
if q: message = f"found query: {q}\n" background_tasks.add_task(write_log, message) return q
@app.post("/send-notification/{email}")
async def send_notification(
email: str, background_tasks: BackgroundTasks, q: str = Depends(get_query)
):
message = f"message to {email}\n" background_tasks.add_task(write_log, message) return {"message": "Message sent"}
使用方法极其的简单,也就不多废话了,write_log 当成 task 方法被调用,先方法名,后传参。
3
自定义 Response 状态码
在一些特殊场景我们需要自己定义返回的状态码
from fastapi import FastAPI
from starlette import status
app = FastAPI()
201
@app.get("/201/", status_code=status.HTTP_201_CREATED)
async def item201():
return {"httpStatus": 201}
302
@app.get("/302/", status_code=status.HTTP_302_FOUND)
async def items302():
return {"httpStatus": 302}
404
@app.get("/404/", status_code=status.HTTP_404_NOT_FOUND)
async def items404():
return {"httpStatus": 404}
500
@app.get("/500/", status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
async def items500():
return {"httpStatus": 500}
if name == '__main__':
import uvicorn uvicorn.run(app, host="127.0.0.1", port=8000)
这么一来就有趣了,设想有个人写了这么一段代码
async def getHtml(self, url, session):
try: async with session.get(url, headers=self.headers, timeout=60, verify_ssl=False) as resp: if resp.status in [200, 201]: data = await resp.text() return data except Exception as e: print(e) pass
那么就有趣了,这段获取 Html 源码的函数根据 Http状态码 来判断是否正常的返回。那如果根据上面的写法,我直接返回一个 404 或者 304 的状态码,但是响应数据却正常,那么这个爬虫岂不是什么都爬不到了么。所以,嘿嘿你懂的!!
4
关于部署
部署 FastAPI 应用程序相对容易
Uvicorn
FastAPI 文档推荐使用 Uvicorn 来部署应用( 其次是 hypercorn),Uvicorn 是一个基于 asyncio 开发的一个轻量级高效的 Web 服务器框架(仅支持 python 3.5.3 以上版本)
安装
pip install uvicorn
启动方式
uvicorn main:app --reload --host 0.0.0.0 --port 8000
Gunicorn
如果你仍然喜欢用 Gunicorn 在部署项目的话,请看下面
安装
pip install gunicorn
启动方式
gunicorn -w 4 -b 0.0.0.0:5000 manage:app -D
Docker部署
采用 Docker 部署应用的好处就是不用搭建特定的运行环境(实际上就是 docker 在帮你拉取),通过 Dockerfile 构建 FastAPI 镜像,启动 Docker 容器,通过端口映射可以很轻松访问到你部署的应用。
Nginx
在 Uvicorn/Gunicorn + FastAPI 的基础上挂上一层 Nginx 服务,一个网站就可以上线了,事实上直接使用 Uvicorm 或 Gunicorn 也是没有问题的,但 Nginx 能让你的网站看起来更像网站。

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
redis为什么那么快?结论有三点,大家都知道,这里主要是分析。
redis为什么那么快?结论有三点,大家都知道,这里主要是分析。 首先第一点 redis是内存访问的,所以快 当然这个大家都知道,所以不是重点 1|0io密集型和cpu密集型 一般我们把任务分为io密集型和cpu密集型 1|1io密集型 IO密集型指的是系统的CPU性能相对硬盘、内存要好很多,此时,系统运作,大部分的状况是CPU在等I/O (硬盘/内存) 的读/写操作,此时CPU Loading并不高。对于io密集型的任务,它的主要时间都在磁盘io上,而io本身在发出中断告知cpu后,cpu只需要短暂的处理一下,之后就由DMA(详见附录)负责数据传输,整个过程对cpu的利用率很低。因此我们需要开更多的线程去充分利用cpu。即一般线程数 =cpu核心数 * 2,如数据库连接池 1|2cpu密集型 CPU密集型也叫计算密集型,指的是系统的硬盘、内存性能相对CPU要好很多,此时,系统运作大部分的状况是CPU Loading 100%,CPU要读/写I/O(硬盘/内存),I/O在很短的时间就可以完成,而CPU还有许多运算要处理,CPU Loading很高。对于cpu密集型的任务,它对cpu的利...
- 下一篇
(完结篇)Python web框架FastAPI——一个比Flask和Tornada更高性能的API 框架
0 前言 前几天给大家分别分享了(入门篇)简析Python web框架FastAPI——一个比Flask和Tornada更高性能的API 框架和(进阶篇)Python web框架FastAPI——一个比Flask和Tornada更高性能的API 框架。今天欢迎大家来到 FastAPI 系列分享的完结篇,本文主要是对于前面文章的补充和扩展。 当然这些功能在实际开发中也扮演者极其重要的角色。 1 中间件的使用 Flask 有 钩子函数,可以对某些方法进行装饰,在某些全局或者非全局的情况下,增添特定的功能。 同样在 FastAPI 中也存在着像钩子函数的东西,也就是中间件 Middleware了。 计算回调时间 -- coding: UTF-8 -- import timefrom fastapi import FastAPIfrom starlette.requests import Request app = FastAPI() @app.middleware("http")async def add_process_time_header(request: Request, call_...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- Linux系统CentOS6、CentOS7手动修改IP地址
- Red5直播服务器,属于Java语言的直播服务器
- Docker安装Oracle12C,快速搭建Oracle学习环境
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作
- Windows10,CentOS7,CentOS8安装MongoDB4.0.16
- CentOS7编译安装Cmake3.16.3,解决mysql等软件编译问题
- SpringBoot2更换Tomcat为Jetty,小型站点的福音
- CentOS7安装Docker,走上虚拟化容器引擎之路
- CentOS6,7,8上安装Nginx,支持https2.0的开启
- Windows10,CentOS7,CentOS8安装Nodejs环境