我正在构建一个 FastAPI 服务器来接收 slacklash 命令发送的请求。使用下面的代码,我可以看到以下内容:
token=BLAHBLAH&team_id=BLAHBLAH&team_domain=myteam&channel_id=BLAHBLAH&channel_name=testme&user_id=BLAH&user_name=myname&command=%2Fwhatever&text=test&api_app_id=BLAHBLAH&is_enterprise_install=false&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%BLAHBLAH&trigger_id=BLAHBLAHBLAH
Run Code Online (Sandbox Code Playgroud)
被打印出来,这正是我在官方文档中看到的有效负载。我正在尝试使用有效负载信息来做某事,我很好奇是否有一种解析此有效负载信息的好方法。我绝对可以使用 split 函数或任何其他漂亮的函数来解析这个有效负载,但我很好奇是否有一种“事实上的”方法来处理松弛有效负载。提前致谢!
from fastapi import FastAPI, Request
app = FastAPI()
@app.post("/")
async def root(request: Request):
request_body = await request.body()
print(request_body)
Run Code Online (Sandbox Code Playgroud) 我试图将一个名为“ethAddress”的值从客户端的输入表单传递到 FastAPI,以便我可以在函数中使用它来生成 matplotlib 图表。
我正在使用 fetch 将输入的文本发布到 Charts.tsx 文件中:
fetch("http://localhost:8000/ethAddress", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(ethAddress),
}).then(fetchEthAddresses);
Run Code Online (Sandbox Code Playgroud)
然后我的 api.py 文件设置如下:
#imports
app = FastAPI()
@app.get("/ethAddress")
async def get_images(background_tasks: BackgroundTasks, ethAddress: str):
image = EthBalanceTracker.get_transactions(ethAddress)
img_buf = image
background_tasks.add_task(img_buf.close)
headers = {'Content-Disposition': 'inline; filename="out.png"'}
return Response(img_buf.getvalue(), headers=headers, media_type='image/png')
@app.post("/ethAddress")
async def add_ethAddress(ethAddress: str):
return ethAddress
Run Code Online (Sandbox Code Playgroud)
据我了解,我使用请求将请求正文中的“ethAddress”从客户端传递到后端fetch POST,然后我可以访问@app.post在 FastAPI 中使用已发布的值。然后我将该值作为字符串返回。然后我在路线中使用它GET来生成图表。
我收到此错误:
INFO: 127.0.0.1:59821 - "POST /ethAddress HTTP/1.1" 422 Unprocessable Entity
INFO: 127.0.0.1:59821 …Run Code Online (Sandbox Code Playgroud) I have created a simple API using FastAPI, and I am trying to pass a URL to a FastAPI route as an arbitrary path parameter.
from fastapi import FastAPI
app = FastAPI()
@app.post("/{path}")
def pred_image(path:str):
print("path",path)
return {'path':path}
Run Code Online (Sandbox Code Playgroud)
When I test it, it doesn't work and throws an error. I am testing it this way:
http://127.0.0.1:8000/https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/zidane.jpg
Run Code Online (Sandbox Code Playgroud) 在Flask中,来自客户端的请求可以如下处理。
对于 JSON 数据:
payload = request.get_json()
对于令牌参数:
token = request.headers.get('Authorization')
对于参数:
id = request.args.get('url', None)
FastAPI 做同样事情的方法是什么?
无法理解,即使我删除所有内部函数并只打印一些内容仍然出现此错误,但是当我使用 fastapi 文档并尝试使用它进行签名时,它可以工作。
@auth_router.post('/signin')
async def sign_in(username: str = Form(...), password: str = Form(...)) -> dict:
user = await authenticate_user(username, password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Invalid username or password',
)
user_obj = await User_Pydantic.from_tortoise_orm(user)
user_token = await generate_token(user_obj)
return {
'access_token': user_token,
'token_type': 'bearer',
}
Run Code Online (Sandbox Code Playgroud)
在我使用 OAuth2PasswordRequestForm 之前,当出现 422 错误时,请尝试其他方法。
我的模型是 tortoise orm,当需要时我将其转换为 pydantic 模型,在文档中一切正常。
JS
handleEvent(signinform, 'submit', e => {
e.preventDefault();
if(!isEmpty(signinform)){
signInUsername = getElement('input[name="username"]', signinform).value;
signInPassword = getElement('input[name="password"]', signinform).value;
recaptchaV3 = getElement('[name="g-recaptcha-response"]').value;
if(recaptchaV3){
signInData = new …Run Code Online (Sandbox Code Playgroud) 我在尝试接受迂腐模型时遇到此错误。经过一段时间的调试后,我相信问题出在接受上CodeCreate
悬垂模型
class BaseCode(BaseModel):
index: Optional[int] = Field(None)
email: EmailStr
gen_time: datetime
expire_time: datetime
class CodeCreate(BaseCode):
code: int
used_time: Optional[datetime] = Field(None)
class Config:
orm_mode = True
class Message(BaseModel):
message: str
Run Code Online (Sandbox Code Playgroud)
代码 ORM
class Code(Base):
__tablename__ = 'code'
index = Column(Integer, primary_key=True, autoincrement=True)
code = Column(Integer)
email = Column(String, ForeignKey('user.email'))
gen_time = Column(DateTime)
expire_time = Column(DateTime)
used_time = Column(DateTime, nullable=True)
Run Code Online (Sandbox Code Playgroud)
处理程序
@app.post('/verify-code', response_model=schemas.Message, responses={404: {"model": schemas.Message}, 406: {"model": schemas.Message}})
async def verify_code(code: schemas.CodeCreate, response: Response, device_name: str = Body(..., …Run Code Online (Sandbox Code Playgroud)