我有以下代码:
import time
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/ping")
async def ping(request: Request):
print("Hello")
time.sleep(5)
print("bye")
return {"ping": "pong!"}
Run Code Online (Sandbox Code Playgroud)
如果我在本地主机上运行我的代码 - 例如http://localhost:8501/ping- 在同一浏览器窗口的不同选项卡中,我得到:
Hello
bye
Hello
bye
Run Code Online (Sandbox Code Playgroud)
代替:
Hello
Hello
bye
bye
Run Code Online (Sandbox Code Playgroud)
我已经阅读过有关使用的内容httpx,但仍然无法实现真正的并行化。有什么问题?
python asynchronous concurrent-processing python-asyncio fastapi
抱歉,不精通Python。
我还没有找到该用例的文档。我如何获取请求正文,确保它是一个有效的 Json(任何有效的 json,包括数字、字符串、布尔值和空值,而不仅仅是对象和数组)并获取实际的 Json。使用 pydantic 强制 Json 具有特定的结构。
我正在构建一个简单的 API 来测试数据库。当我使用 get request 时一切正常,但如果我更改为 post,我会收到“无法处理的实体”错误:
这是 FastAPI 代码:
from fastapi import FastAPI
app = FastAPI()
@app.post("/")
def main(user):
return user
Run Code Online (Sandbox Code Playgroud)
然后,我的请求使用 javascript
let axios = require('axios')
data = {
user: 'smith'
}
axios.post('http://localhost:8000', data)
.then(response => (console.log(response.url)))
Run Code Online (Sandbox Code Playgroud)
并使用 Python
import requests
url = 'http://127.0.0.1:8000'
data = {'user': 'Smith'}
response = requests.post(url, json=data)
print(response.text)
Run Code Online (Sandbox Code Playgroud)
我也尝试解析为 json,使用 utf-8 编码,并更改标题。没有什么对我有用。
我根据官方文档使用fastapi上传文件,就像:
@app.post("/create_file/")
async def create_file(file: UploadFile=File(...)):
file2store = await file.read()
# some code to store the BytesIO(file2store) to the other database
Run Code Online (Sandbox Code Playgroud)
当我使用 python requests lib 发送请求时:
f = open(".../file.txt", 'rb')
files = {"file": (f.name, f, "multipart/form-data")}
requests.post(url="SERVER_URL/create_file", files=files)
Run Code Online (Sandbox Code Playgroud)
file2store 始终为空。有时(很少见),它可以获取文件字节,但几乎所有时间都是空的,所以我无法在另一个数据库上恢复文件。我还尝试了 'bytes' 而不是 'UploadFile',我得到了相同的结果。我的代码有什么地方不对,还是我使用fastapi上传文件的方式有问题?我google了很长时间,但没有成功。所以我在这里提出问题,希望知道答案的人可以帮助我。谢谢
我正在尝试与指纹设备进行通信。实际上它通过连接发送数据websocket。所以,我想我可以使用 与设备进行通信webscokets。这里我使用FastAPI,但它只接受JSON数据。问题是我需要处理XML数据,但是,我不知道如何以XML格式发送和接受数据。
fastapi ×5
python ×4
asynchronous ×1
axios ×1
file-upload ×1
json ×1
pydantic ×1
websocket ×1
xml ×1