[英]Send / receive in parallel using websockets in Python FastAPI
[英]How to send and receive data in XML format using WebSockets and FastAPI?
我正在嘗試與指紋設備進行通信。 實際上它通過websocket
連接發送數據。 所以,我想我可以使用webscokets
與設備進行通信。 這里我使用的是 FastAPI,但它只接受JSON
數據。 問題是我需要處理XML
數據,但是,我不知道如何發送和接受XML
格式的數據。
FastAPI 也可以接受和驗證其他類型的數據,而不僅僅是您所說的JSON
。 看看文檔。 關於XML
,由於FastAPI 實際上是 Starlette 下面,您可以直接使用 Starlette 的Request
對象將請求body
讀取為字節,並返回帶有XML
數據的自定義Response
(如果需要)。 您可以檢查傳入的請求是否為所需的Content-Type
,如果是,則讓它通過; 否則,您可以引發HTTPException
。 下面是一個在客戶端使用 Python 請求並在服務器端使用普通HTTP
端點的工作示例。
HTTP
協議應用程序.py
from fastapi import FastAPI, Response, Request, HTTPException
app = FastAPI()
@app.post("/submit")
async def submit(request: Request):
content_type = request.headers['Content-Type']
if content_type == 'application/xml':
body = await request.body()
return Response(content=body, media_type="application/xml")
else:
raise HTTPException(status_code=400, detail=f'Content type {content_type} not supported')
測試.py
import requests
body = """<?xml version='1.0' encoding='utf-8'?><a>б</a>"""
headers = {'Content-Type': 'application/xml'}
url = 'http://127.0.0.1:8000/submit'
r = requests.post(url, data=body.encode('utf-8'), headers=headers)
print(r.content)
在 websockets 中,您可以使用send_bytes()
和receive_bytes()
進行通信,如Starlette 的文檔中所述,還允許您發送和接收(字節編碼的) XML
數據。 如果您想對收到的XML
數據執行驗證,請查看此答案。
WebSocket
協議應用程序.py
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
import uvicorn
app = FastAPI()
@app.websocket("/ws")
async def get_stream(websocket: WebSocket):
await websocket.accept()
try:
while True:
contents = await websocket.receive_bytes()
print(str(contents, 'utf-8'))
except WebSocketDisconnect:
print("Client disconnected")
if __name__ == '__main__':
uvicorn.run(app, host='127.0.0.1', port=8000)
測試.py
import websockets
import asyncio
async def main():
url = 'ws://127.0.0.1:8000/ws'
async with websockets.connect(url) as ws:
while True:
b = bytes("<?xml version='1.0' encoding='utf-8'?><a>б</a>", 'utf-8')
await ws.send(b)
await asyncio.sleep(1)
asyncio.run(main())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.