Web服务器系列相关文章编写如下:
FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python类型提示。
文档: https://fastapi.tiangolo.com
源码: https://github.com/tiangolo/fastapi
关键特性:
pip install fastapi
or
pip install fastapi[all]
uvicorn main:app --reload
使用 FastAPI 需要 Python 版本大于等于 3.6。
# -*- coding:utf-8 -*-
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
uvicorn main:app --reload
CORS 或者「跨域资源共享」 指浏览器中运行的前端拥有与后端通信的 JavaScript 代码,而后端处于与前端不同的「源」的情况。
源是协议(http,https)、域(myapp.com,localhost,localhost.tiangolo.com)以及端口(80、443、8080)的组合。因此,这些都是不同的源:
http://localhost
https://localhost
http://localhost:8080
# -*- 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)
返回 json 数据可以是:JSONResponse、UJSONResponse、ORJSONResponse,Content-Type 是 application/json;返回 html 是 HTMLResponse,Content-Type 是 text/html;返回 PlainTextResponse,Content-Type 是 text/plain。
还有三种响应,分别是返回重定向、字节流、文件。
# -*- 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)
# -*- 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)
# -*- 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)
# -*- 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)
# -*- 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)
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tornado Websocket Testtitle>
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>
如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;
╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;
o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;
(✿◡‿◡)
感谢各位童鞋们的支持!
( ´ ▽´ )ノ ( ´ ▽´)っ!!!