小编Ale*_*ill的帖子

在python中提取子字符串

我想解析一个字符串来提取花括号中的所有子串:

'The value of x is {x}, and the list is {y} of len {}'
Run Code Online (Sandbox Code Playgroud)

应该产生:

(x, y)
Run Code Online (Sandbox Code Playgroud)

然后我想格式化字符串以使用值打印初始字符串:

str.format('The value of x is {x}, and the list is {y} of len {}', x, y, len(y))
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Example usage:
def somefunc():
    x = 123
    y = ['a', 'b']
    MyFormat('The value of x is {x}, and the list is {y} of len {}',len(y))

output:
    The value of x is 123, and the list is ['a', 'b'] of len 2
Run Code Online (Sandbox Code Playgroud)

python regex string-formatting

5
推荐指数
1
解决办法
101
查看次数

FastAPI文件上传

我正在尝试使用请求将 JSON 数据+文件(二进制)上传到 FastAPI“POST”端点。

这是服务器代码:

@app.post("/files/")
async def create_file(
    file: bytes = File(...), fileb: UploadFile = File(...), timestamp: str = Form(...)
):
    return {
        "file_size": len(file),
        "timestamp": timestamp,
        "fileb_content_type": fileb.content_type,
    }
Run Code Online (Sandbox Code Playgroud)

这是客户端代码:

session = requests.Session()
adapter = requests.adapters.HTTPAdapter(max_retries=0)
session.mount('http://', adapter)

jpg_image = open(IMG_PATH, 'rb').read()

timestamp_str = datetime.datetime.now().isoformat()
files = {
    'timestamp': (None, timestamp_str),
    'file': ('image.jpg', jpg_image),
}
request = requests.Request('POST',
                           FILE_UPLOAD_ENDPOINT,
                           files=files)
prepared_request = request.prepare()
response = session.send(prepared_request)
Run Code Online (Sandbox Code Playgroud)

服务器失败并显示

“POST /files/ HTTP/1.1” 422 无法处理的实体

python-requests http-status-code-422 fastapi uvicorn

5
推荐指数
1
解决办法
9966
查看次数