亲宝软件园·资讯

展开

Python Web服务器

爱看书的小沐 人气:0

1、简介

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

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

关键特性:

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>

运行结果如下:

加载全部内容

相关教程
猜你喜欢
用户评论