Python实现Web服务器FastAPI的步骤详解

 更新时间:2022年06月13日 11:01:04   作者:爱看书的小沐  
FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python类型提示,这篇文章主要介绍了Python实现Web服务器FastAPI的过程,需要的朋友可以参考下

1、简介

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

文档: https://fastapi.tiangolo.com
源码: https://github.com/tiangolo/fastapi

关键特性:

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

2、安装

pip install fastapi
or
pip install fastapi[all]

运行服务器的命令如下:

uvicorn main:app --reload

3、官方示例

使用 FastAPI 需要 Python 版本大于等于 3.6。

3.1 入门示例 Python测试代码如下(main.py):

# -*- coding:utf-8 -*-
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
    return {"message": "Hello World"}

运行结果如下:
运行服务器的命令如下:

uvicorn main:app --reload

3.2 跨域CORS

CORS 或者「跨域资源共享」 指浏览器中运行的前端拥有与后端通信的 JavaScript 代码,而后端处于与前端不同的「源」的情况。

源是协议(http,https)、域(myapp.com,localhost,localhost.tiangolo.com)以及端口(80、443、8080)的组合。因此,这些都是不同的源:

http://localhost
https://localhost
http://localhost:8080

Python测试代码如下(test_fastapi.py):

# -*- coding:utf-8 -*-
from typing import Union
from fastapi import FastAPI, Request
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# 让app可以跨域
# origins = ["*"]
origins = [
    "http://localhost.tiangolo.com",
    "https://localhost.tiangolo.com",
    "http://localhost",
    "http://localhost:8080",
]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
# @app.get("/") 
# async def root(): 
#     return {"Hello": "World"}
@app.get("/")
def read_root():
    return {"message": "Hello World,爱看书的小沐"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}
@app.get("/api/sum") 
def get_sum(req: Request): 
    a, b = req.query_params['a'], req.query_params['b'] 
    return int(a) + int(b) 
@app.post("/api/sum2") 
async def get_sum(req: Request): 
    content = await req.json() 
    a, b = content['a'], content['b'] 
    return a + b
@app.get("/api/sum3")
def get_sum2(a: int, b: int): 
    return int(a) + int(b)
if __name__ == "__main__":
    uvicorn.run("test_fastapi:app", host="127.0.0.1", port=8000
                , log_level="info", reload=True, debug=True)

运行结果如下:

FastAPI 会自动提供一个类似于 Swagger 的交互式文档,我们输入 “localhost:8000/docs” 即可进入。

3.3 文件操作

返回 json 数据可以是:JSONResponse、UJSONResponse、ORJSONResponse,Content-Type 是 application/json;返回 html 是 HTMLResponse,Content-Type 是 text/html;返回 PlainTextResponse,Content-Type 是 text/plain。
还有三种响应,分别是返回重定向、字节流、文件。

(1)Python测试重定向代码如下:

# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
import uvicorn
app = FastAPI()
@app.get("/index")
async def index():
    return RedirectResponse("https://www.baidu.com")
@app.get("/")
def main():
    return {"message": "Hello World,爱看书的小沐"}
if __name__ == "__main__":
    uvicorn.run("test_fastapi:app", host="127.0.0.1", port=8000
                , log_level="info", reload=True, debug=True)

运行结果如下:

(2)Python测试字节流代码如下:

# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
import uvicorn
app = FastAPI()
async def test_bytearray():
    for i in range(5):
        yield f"byteArray: {i} bytes ".encode("utf-8")
@app.get("/index")
async def index():
    return StreamingResponse(test_bytearray())
@app.get("/")
def main():
    return {"message": "Hello World,爱看书的小沐"}
if __name__ == "__main__":
    uvicorn.run("test_fastapi:app", host="127.0.0.1", port=8000
                , log_level="info", reload=True, debug=True)

运行结果如下:

(3)Python测试文本文件代码如下:

# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
import uvicorn
app = FastAPI()
@app.get("/index")
async def index():
    return StreamingResponse(open("test_tornado.py", encoding="utf-8"))
@app.get("/")
def main():
    return {"message": "Hello World,爱看书的小沐"}
if __name__ == "__main__":
    uvicorn.run("test_fastapi:app", host="127.0.0.1", port=8000
                , log_level="info", reload=True, debug=True)

运行结果如下:

(4)Python测试二进制文件代码如下:

# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse, StreamingResponse
import uvicorn
app = FastAPI()
@app.get("/download_file")
async def index():
    return FileResponse("test_fastapi.py", filename="save.py")
@app.get("/get_file/")
async def download_files():
    return FileResponse("test_fastapi.py")
@app.get("/get_image/")
async def download_files_stream():
    f = open("static\\images\\sheep0.jpg", mode="rb")
    return StreamingResponse(f, media_type="image/jpg")
@app.get("/")
def main():
    return {"message": "Hello World,爱看书的小沐"}
if __name__ == "__main__":
    uvicorn.run("test_fastapi:app", host="127.0.0.1", port=8000
                , log_level="info", reload=True, debug=True)

运行结果如下:

3.4 WebSocket Python测试代码如下:

# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from fastapi.websockets import WebSocket
import uvicorn
app = FastAPI()
@app.websocket("/myws")
async def ws(websocket: WebSocket):
    await websocket.accept()
    while True:
        # data = await websocket.receive_bytes()
        # data = await websocket.receive_json()
        data = await websocket.receive_text()
        print("received: ", data)
        await websocket.send_text(f"received: {data}")
@app.get("/")
def main():
    return {"message": "Hello World,爱看书的小沐"}

if __name__ == "__main__":
    uvicorn.run("test_fastapi:app", host="127.0.0.1", port=8000
                , log_level="info", reload=True, debug=True)

HTML客户端测试代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tornado Websocket Test</title>
</head>
<body>
<body onload='onLoad();'>
Message to send: <input type="text" id="msg"/>
<input type="button" onclick="sendMsg();" value="发送"/>
</body>
</body>
<script type="text/javascript">
    var ws;

    function onLoad() {
        ws = new WebSocket("ws://127.0.0.1:8000/myws");
		ws.onopen = function() {
           console.log('connect ok.')
		   ws.send("Hello, world");
		};
		ws.onmessage = function (evt) {
		   console.log(evt.data)
		};
        ws.onclose = function () { 
            console.log("onclose") 
        }
    }
    function sendMsg() {
        ws.send(document.getElementById('msg').value);
    }
</script>
</html>

运行结果如下:

到此这篇关于Python实现Web服务器(FastAPI的文章就介绍到这了,更多相关Python Web服务器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • RC4文件加密的python实现方法

    RC4文件加密的python实现方法

    这篇文章主要介绍了RC4文件加密的python实现方法,实例分析了RC4文件加密的原理与Python实现技巧,需要的朋友可以参考下
    2015-06-06
  • tensorflow之自定义神经网络层实例

    tensorflow之自定义神经网络层实例

    今天小编就为大家分享一篇tensorflow之自定义神经网络层实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-02-02
  • Python实现批量修改图片大小

    Python实现批量修改图片大小

    在日常生活中经常有需要调整图片大小的需求,一张两张的还好,但是如果需要几十张几百张甚至几千张,就可以考虑使用Python脚本来执行了,下面小编就来和大家分享几个Python可以批量修改图片大小的脚本吧
    2023-07-07
  • Python读取ini文件、操作mysql、发送邮件实例

    Python读取ini文件、操作mysql、发送邮件实例

    这篇文章主要介绍了Python读取ini文件、操作mysql、发送邮件实例,本文重点在Mysql操作的讲解上,包含查询、插入、更新和删除操作,需要的朋友可以参考下
    2015-01-01
  • python对文件的操作方法汇总

    python对文件的操作方法汇总

    这篇文章主要介绍了python对文件的操作方法汇总,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02
  • 浅谈五大Python Web框架

    浅谈五大Python Web框架

    Python这么多框架,能挨个玩个遍的人不多,坦白的说我也只用过其中的三个开发过项目,另外一些稍微接触过,所以这里只能浅谈一下,欢迎懂行的朋友们补充
    2017-03-03
  • Python 文件处理注意事项总结

    Python 文件处理注意事项总结

    这篇文章主要介绍了Python 文件处理注意事项总结的相关资料,需要的朋友可以参考下
    2017-04-04
  • 关于torch.optim的灵活使用详解(包括重写SGD,加上L1正则)

    关于torch.optim的灵活使用详解(包括重写SGD,加上L1正则)

    今天小编就为大家分享一篇关于torch.optim的灵活使用详解(包括重写SGD,加上L1正则),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-02-02
  • Python多线程中阻塞(join)与锁(Lock)使用误区解析

    Python多线程中阻塞(join)与锁(Lock)使用误区解析

    这篇文章主要为大家详细介绍了Python多线程中阻塞join与锁Lock的使用误区,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-04-04
  • pyshp创建shp点文件的方法

    pyshp创建shp点文件的方法

    今天小编就为大家分享一篇pyshp创建shp点文件的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-12-12

最新评论