最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實現(xiàn)Web服務(wù)器FastAPI的步驟詳解

 更新時間:2022年06月13日 11:01:04   作者:愛看書的小沐  
FastAPI?是一個用于構(gòu)建?API?的現(xiàn)代、快速(高性能)的?web?框架,使用?Python?3.6+?并基于標(biāo)準(zhǔn)的?Python類型提示,這篇文章主要介紹了Python實現(xiàn)Web服務(wù)器FastAPI的過程,需要的朋友可以參考下

1、簡介

FastAPI 是一個用于構(gòu)建 API 的現(xiàn)代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于標(biāo)準(zhǔn)的 Python類型提示。

文檔: https://fastapi.tiangolo.com
源碼: https://github.com/tiangolo/fastapi

關(guān)鍵特性:

  • 快速:可與 NodeJS 和 Go 比肩的極高性能(歸功于 Starlette 和 Pydantic)。最快的 Python web 框架之一。
  • 高效編碼:提高功能開發(fā)速度約 200% 至 300%。*
  • 更少 bug:減少約 40% 的人為(開發(fā)者)導(dǎo)致錯誤。*
  • 智能:極佳的編輯器支持。處處皆可自動補全,減少調(diào)試時間。
  • 簡單:設(shè)計的易于使用和學(xué)習(xí),閱讀文檔的時間更短。
  • 簡短:使代碼重復(fù)最小化。通過不同的參數(shù)聲明實現(xiàn)豐富功能。bug 更少。
  • 健壯:生產(chǎn)可用級別的代碼。還有自動生成的交互式文檔。
  • 標(biāo)準(zhǔn)化:基于(并完全兼容)API 的相關(guān)開放標(biāo)準(zhǔn):OpenAPI (以前被稱為 Swagger) 和 JSON Schema。

2、安裝

pip install fastapi
or
pip install fastapi[all]

運行服務(wù)器的命令如下:

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"}

運行結(jié)果如下:
運行服務(wù)器的命令如下:

uvicorn main:app --reload

3.2 跨域CORS

CORS 或者「跨域資源共享」 指瀏覽器中運行的前端擁有與后端通信的 JavaScript 代碼,而后端處于與前端不同的「源」的情況。

源是協(xié)議(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)

運行結(jié)果如下:

FastAPI 會自動提供一個類似于 Swagger 的交互式文檔,我們輸入 “localhost:8000/docs” 即可進(jìn)入。

3.3 文件操作

返回 json 數(shù)據(jù)可以是:JSONResponse、UJSONResponse、ORJSONResponse,Content-Type 是 application/json;返回 html 是 HTMLResponse,Content-Type 是 text/html;返回 PlainTextResponse,Content-Type 是 text/plain。
還有三種響應(yīng),分別是返回重定向、字節(jié)流、文件。

(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)

運行結(jié)果如下:

(2)Python測試字節(jié)流代碼如下:

# -*- 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)

運行結(jié)果如下:

(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)

運行結(jié)果如下:

(4)Python測試二進(jìn)制文件代碼如下:

# -*- 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)

運行結(jié)果如下:

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="發(fā)送"/>
</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>

運行結(jié)果如下:

到此這篇關(guān)于Python實現(xiàn)Web服務(wù)器(FastAPI的文章就介紹到這了,更多相關(guān)Python Web服務(wù)器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

将乐县| 澎湖县| 年辖:市辖区| 兴文县| 西吉县| 宣城市| 嵩明县| 高青县| 克拉玛依市| 景宁| 怀远县| 梁河县| 临漳县| 洛宁县| 云浮市| 湟中县| 梓潼县| 会东县| 噶尔县| 曲麻莱县| 青铜峡市| 宜州市| 黔西县| 太湖县| 三亚市| 信丰县| 金坛市| 阿巴嘎旗| 和林格尔县| 张家界市| 全椒县| 达州市| 沙洋县| 峡江县| 犍为县| 朝阳区| 周至县| 宣汉县| 乐东| 修水县| 历史|