我正在将 FastAPI 与 Pydantic 结合使用。
我的问题 - 我需要使用 Pydantic 引发 ValueError
from fastapi import FastAPI
from pydantic import BaseModel, validator
from fastapi import Depends, HTTPException
app = FastAPI()
class RankInput(BaseModel):
rank: int
@validator('rank')
def check_if_value_in_range(cls, v):
"""
check if input rank is within range
"""
if not 0 < v < 1000001:
raise ValueError("Rank Value Must be within range (0,1000000)")
#raise HTTPException(status_code=400, detail="Rank Value Error") - this works But I am looking for a solution using ValueError
return v
def …
Run Code Online (Sandbox Code Playgroud) 所以我正在学习 FastAPI,并试图弄清楚如何正确返回状态代码。我创建了一个用于上传文件的端点,并且我想在文件格式不受支持的情况下做出特殊响应。似乎我按照官方文档做了一切,但我总是收到422 Unprocessable Entity
错误。
这是我的代码:
from fastapi import FastAPI, File, UploadFile, status
from fastapi.openapi.models import Response
app = FastAPI()
@app.post('/upload_file/', status_code=status.HTTP_200_OK)
async def upload_file(response: Response, file: UploadFile = File(...)):
"""End point for uploading a file"""
if file.content_type != "application/pdf":
response.status_code = status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
return {f'File {file.filename} has unsupported extension type'}
return {'filename': file.content_type}
Run Code Online (Sandbox Code Playgroud)
先感谢您!
假设我有一个数据框:
A B C D E F
0 x R i R nan h
1 z g j x a nan
2 z h nan y nan nan
3 x g nan nan nan nan
4 x x h x s f
Run Code Online (Sandbox Code Playgroud)
我想替换所有单元格:
df.loc[0] == 'R'
)!= 'x'
)与np.nan
.
基本上我想做:
df.loc[2:,df.loc[0]=='R']!='x' = np.nan
Run Code Online (Sandbox Code Playgroud)
我收到错误:
SyntaxError: can't assign to comparison
Run Code Online (Sandbox Code Playgroud)
我只是不知道语法应该如何。
我试过了
df[df.loc[2:,df.loc[0]=='R']!='x']
Run Code Online (Sandbox Code Playgroud)
但这并没有列出我想要的值。
我有一个从数据库中获取所有数据的路由器。这是我的代码:
@router.get('/articles/', response_model=List[articles_schema.Articles])
async def main_endpoint():
query = articles_model.articles.select().where(articles_model.articles.c.status == 2)
return await db.database.fetch_all(query)
Run Code Online (Sandbox Code Playgroud)
响应是一个包含 JSON 对象的数组,如下所示
[
{
"title": "example1",
"content": "example_content1"
},
{
"title": "example2",
"content": "example_content2"
},
]
Run Code Online (Sandbox Code Playgroud)
但我想做出这样的回应:
{
"items": [
{
"title": "example1",
"content": "example_content1"
},
{
"title": "example2",
"content": "example_content2"
},
]
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?请帮忙。先感谢您
在python中,使用Fast API,我有一个在打印时显示的str(这是一个例子,真正的str更复杂):
[1592494390, 'test', -0.2761097089544078, -0.0852381808812182, -0.101153, nan]
Run Code Online (Sandbox Code Playgroud)
我想使用 Fast API 作为 JSON 数组返回它。
使用 JSONResponse
def get_json(dataset: str, timeseries: str):
test = "[1592494390, 'test', -0.2761097089544078, -0.0852381808812182, -0.101153, nan]"
print(test)
return JSONResponse(content=test)
Run Code Online (Sandbox Code Playgroud)
打印结果如预期所示:
[1592494390, 'test', -0.2761097089544078, -0.0852381808812182, -0.101153, nan]
Run Code Online (Sandbox Code Playgroud)
但是 API 在调用时的答案是:
"[1592494390, 'test', -0.2761097089544078, -0.0852381808812182, -0.101153, nan]"
Run Code Online (Sandbox Code Playgroud)
所以我的str
再次被连载,我不知道如何绕过它。
使用响应:
Fast API 的文档中有一个页面描述了如何直接返回响应(https://fastapi.tiangolo.com/advanced/response-directly/),其中写道:
当您直接返回响应时,其数据不会被验证、转换(序列化),也不会自动记录。
但使用这种方法会导致错误:
def get_json(dataset: str, timeseries: str):
test = "[1592494390, 'test', -0.2761097089544078, -0.0852381808812182, -0.101153, nan]"
print(test)
return Response(content=test, media_type="application/json")
Run Code Online (Sandbox Code Playgroud)
> line 53, in …
Run Code Online (Sandbox Code Playgroud) 我有一个tkinker
窗口,其中有几个使用 place 的按钮和布局。我尝试为整个窗口创建滚动条,但无法将按钮放置在框架中。有人可以帮我吗,我怎样才能在框架上添加这个按钮?
#btn1 = tk.Button(win,
text="Browse...",
compound="left",
fg="blue", width=22,
font=("bold", 10),
height=1,
)
#btn1.place(x=600, y=0)
import json
from tkinter import *
import tkinter as tk
from tkinter import filedialog as fd
win = Tk()
win.geometry("500x500")
# main
main_frame = Frame(win)
main_frame.pack(fill=BOTH, expand=1)
# canvas
my_canvas = Canvas(main_frame)
my_canvas.pack(side=LEFT, fill=BOTH, expand=1)
# scrollbar
my_scrollbar = tk.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)
# configure the canvas
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind(
'<Configure>', lambda e: my_canvas.configure(scrollregion=my_canvas.bbox("all"))
)
second_frame = Frame(my_canvas)
my_canvas.create_window((0, 0), window=second_frame, anchor="nw")
Run Code Online (Sandbox Code Playgroud)