小编576*_*76i的帖子

如何在函数中键入提示文件名?

Python 中提示文件名的最佳方法是什么,以便将任何内容传递给您可以作为文件打开的函数?

尤其是通过 Pathlib 找到的字符串和文件。

def myfunc(filename: str) -> None:
    with open(filename) as f1:
        # do something here
Run Code Online (Sandbox Code Playgroud)

python type-hinting python-3.x

22
推荐指数
4
解决办法
4633
查看次数

以同步方式使用 FastAPI,如何获取 POST 请求的原始正文?

在同步而非非模式下使用 FastAPI async,我希望能够接收 POST 请求的原始、未更改的正文。

我能找到的所有示例都显示async代码,当我以正常同步方式尝试时,它们request.body()显示为协程对象。

XML当我通过向此端点发布一些内容来测试它时,我得到了一个500 "Internal Server Error".

from fastapi import FastAPI, Response, Request, Body

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.post("/input")
def input_request(request: Request):
    # how can I access the RAW request body here?  
    body = request.body()

    # do stuff with the body here  

    return Response(content=body, media_type="application/xml")
Run Code Online (Sandbox Code Playgroud)

这对于 FastAPI 来说是不可能的吗?

注意:简化的输入请求如下所示:

POST http://127.0.0.1:1083/input
Content-Type: application/xml

<XML>
    <BODY>TEST</BODY>
</XML>
Run Code Online (Sandbox Code Playgroud)

我无法控制输入请求的发送方式,因为我需要替换现有的 SOAP API。

python starlette fastapi

21
推荐指数
1
解决办法
2万
查看次数

使用 FastAPI 和 Pydantic,如何定义带有描述的可选字段

对于 FastAPI Pydanctic 类,我有这些值

class ErrorReportRequest(BaseModel):
    sender: Optional[str] = Field(..., description="Who sends the error message.")
    error_message_displayed_to_client: str = Field(..., description="The error message displayed to the client.")
Run Code Online (Sandbox Code Playgroud)

我使用该类作为输入模型

router = APIRouter()

@router.post(
    "/error_report",
    response_model=None,
    include_in_schema=True,

)
def error_report(err: ErrorReportRequest):
    pass
Run Code Online (Sandbox Code Playgroud)

当我运行它时,sender是必填字段。如果它未包含在传入的 JSON 中,我会收到验证错误。

输入:

{
  "error_message_displayed_to_client": "string"
}
Run Code Online (Sandbox Code Playgroud)

结果是:

{
  "detail": [
    {
      "loc": [
        "body",
        "sender"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

如果我像这样删除字段描述:

    class ErrorReportRequest(BaseModel):
        sender: Optional[str]
        error_message_displayed_to_client: str = Field(..., description="The error message displayed …
Run Code Online (Sandbox Code Playgroud)

pydantic fastapi

18
推荐指数
1
解决办法
4万
查看次数

可以在pandas中执行左连接,只选择右边的第一个匹配吗?

可以在pandas中执行左连接,只选择右边的第一个匹配吗?例:

left            = pd.DataFrame()
left['age']     = [11, 12]
right           = pd.DataFrame()
right['age']    = [10, 11, 11]
right['salary'] = [ 100, 150, 200 ]
left.merge( right, how='left', on='age' )
Run Code Online (Sandbox Code Playgroud)

返回

   age  salary
0   11     150
1   11     200
2   12     NaN
Run Code Online (Sandbox Code Playgroud)

但我想通过仅仅进行第一场比赛来保留左边的行数.那是:

   age  salary
0   11     150
2   12     NaN
Run Code Online (Sandbox Code Playgroud)

所以我一直在使用

left.merge( right.drop_duplicates(['age']), how='left', on='age')
Run Code Online (Sandbox Code Playgroud)

但我相信这是正确的完整副本.它闻起来很有趣.

有更优雅的方式吗?

python left-join pandas

12
推荐指数
1
解决办法
5675
查看次数

Python:从基类数据类继承的数据类,如何将值从基类升级到新类?

如何将值从基础数据类升级到继承自它的数据类?

示例(Python 3.7.2)

from dataclasses import dataclass

@dataclass
class Person:
    name: str 
    smell: str = "good"    

@dataclass
class Friend(Person):

    # ... more fields

    def say_hi(self):        
        print(f'Hi {self.name}')

friend = Friend(name='Alex')
f1.say_hi()
Run Code Online (Sandbox Code Playgroud)

打印“嗨亚历克斯”

random_stranger = Person(name = 'Bob', smell='OK')
Run Code Online (Sandbox Code Playgroud)

返回 random_stranger "Person(name='Bob',sole='OK')"

如何将 random_stranger 变成朋友?

Friend(random_stranger)
Run Code Online (Sandbox Code Playgroud)

返回“朋友(姓名=人(姓名='鲍勃',气味='OK'),气味='好')”

结果我想得到“朋友(名字=“鲍勃”,气味=“OK”)”。

Friend(random_stranger.name, random_stranger.smell)
Run Code Online (Sandbox Code Playgroud)

有效,但如何避免必须复制所有字段?

或者我是否可能无法在从数据类继承的类上使用 @dataclass 装饰器?

python python-3.7 python-dataclasses

11
推荐指数
1
解决办法
8099
查看次数

如何在德语区域设置中将字符串转换为Python Decimal(使用逗号而不是点)

我正在尝试将字符串转换为python小数.

这有效

from decimal import *
mystr = '123.45'
print(Decimal(mystr))
Run Code Online (Sandbox Code Playgroud)

但是,当我想使用千位分隔符和区域设置时,它不会.转换为float工作正常.

from locale import *
setlocale(LC_NUMERIC,'German_Germany.1252')
from decimal import *
mystr = '1.234,56'
print(atof(mystr))
print(Decimal(mystr))
Run Code Online (Sandbox Code Playgroud)

返回浮点数和错误

1234.56
InvalidOperation: [<class 'decimal.ConversionSyntax'>] 
Run Code Online (Sandbox Code Playgroud)

有没有一种正确的方法来转换字符串而无需通过float或hackier解决方案手动转换它?FYA,我目前的hacky解决方案是:

 print(Decimal(f'{atof(mystr):2.2f}'))
Run Code Online (Sandbox Code Playgroud)

python decimal type-conversion python-3.x

8
推荐指数
1
解决办法
1089
查看次数

使用 Playwright for Python,如何从下拉列表中选择选项?

这是关于 Playwright for Python 基本功能的问题的后续内容。

如何从下拉列表中选择一个选项

此示例远程控制一个 vuejs 网站,该网站具有“苹果”、“香蕉”、“胡萝卜”、“橙子”等水果的下拉列表

这里我想选择选项“香蕉”

from playwright import sync_playwright
import time

URL = '<my url>'

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    page = browser.newPage()
    page.goto(URL)

    # identify this element by ID. Wait for it first
    new_selector = 'id=name-fruit'
    page.waitForSelector(new_selector)
    handle = page.querySelector(new_selector)

    # at this point I have the element and can print the content
    print(handle.innerHTML())
Run Code Online (Sandbox Code Playgroud)

下拉列表 HTML 像这样

<select data-v-c2cef47a="" id="name-fruit" autocomplete="true" class="form-select__select">
    <option data-v-c2cef47a="" disabled="disabled" …
Run Code Online (Sandbox Code Playgroud)

python playwright playwright-python

8
推荐指数
1
解决办法
2万
查看次数

Python Telegram Bot - 如何更新我的机器人发送的最后一条消息的文本

我正在使用 python-telegram-bot (python-telegram-bot.org) 从 Python3 与 Telegram 进行通信

我想更新我发送的最后一条回复。目前,下面的代码发送消息,然后 5 秒后发送另一条消息。

def echo(bot, update):
    update.message.reply_text("Sorry, you're on your own, kiddo.")
    time.sleep(5)
    update.message.reply_text("Seriously, you're on your own, kiddo.")
Run Code Online (Sandbox Code Playgroud)

我想更新最后一条消息。

我试过

bot.editMessageText("Seriously, you're on your own, kiddo.",
                   chat_id=update.message.chat_id,
                   message_id=update.message.message_id)
Run Code Online (Sandbox Code Playgroud)

在示例中,它可以更新用消息替换内联键盘,但是会崩溃(并且不会更新我作为机器人发送的最后一条消息)。

python python-telegram-bot

7
推荐指数
1
解决办法
2万
查看次数

在 Python 的 FastAPI 自动生成的 OpenAPI/Swagger 文档页面中,如何添加更多错误 http 状态代码?

FastAPI 生成自动 swagger/openapi 文档。

https://fastapi.tiangolo.com/tutorial/response-status-code的教程中有一个例子

from fastapi import FastAPI
app = FastAPI()

@app.post("/items/", status_code=201)
async def create_item(name: str):
    return {"name": name}
Run Code Online (Sandbox Code Playgroud)

如果你运行它,.../docs 页面会显示两个 http 响应选项:

成功的状态代码 201 和验证错误的状态代码 422

上面的教程展示了这个页面的图片FastAPI 文档)

我想在文档中记录更多的响应状态代码描述,例如代码 403,“禁止”

虽然我可以在代码中运行这样的异常

raise HTTPException(status_code=403, detail="Forbidden")
Run Code Online (Sandbox Code Playgroud)

我还没有找到在自动生成的文档中描述它们的方法。

知道怎么做吗?

fastapi

7
推荐指数
1
解决办法
1693
查看次数

如何使用 CURL 将单个文件上传到 FastAPI 服务器

我正在尝试设置一个 FastAPI 服务器,它可以使用curl从命令行接收单个文件上传

我在这里关注 FastAPI 教程:

https://fastapi.tiangolo.com/tutorial/request-files/?h=upload+file

from typing import List
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse
app = FastAPI()

@app.post("/file/")
async def create_file(file: bytes = File(...)):
     return {"file_size": len(file)}

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

@app.post("/files/")
async def create_files(files: List[bytes] = File(...)):
    return {"file_sizes": [len(file) for file in files]}

@app.post("/uploadfiles/")
async def create_upload_files(files: List[UploadFile] = File(...)):
    return {"filenames": [file.filename for file in files]}
Run Code Online (Sandbox Code Playgroud)

运行此代码,然后在浏览器中打开“http://127.0.0.1:5094”,我会得到一个上传表单,其中包含四种选择文件和上传的方式

我遵循了本教程: https://medium.com/@petehouston/upload-files-with-curl-93064dcccc76 …

python curl fastapi

7
推荐指数
1
解决办法
5215
查看次数