如何使用python starlette解码上传到postman的文件

ctrmrzij  于 2022-11-07  发布在  Postman
关注(0)|答案(1)|浏览(214)

我已经在postman中上传了一个.mp4文件,现在我需要将文件内容读入python中的一个变量。这是我的postman上传


这是我的python文件,如果我的请求将在此函数中捕获,现在将如何解码此函数中上传的文件

from starlette.requests import Request
from starlette.routing import Route, Mount
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse, FileResponse   

class Post:
    async def PostValuesToDb(requests: Request):
        return PlainTextResponse("true")

routes = [
    Route("/post", Post.PostValuesToDb,
          name="PostValuesToDb", methods=["POST"]),

]

app = Starlette(
    routes=routes
)

PostValuesToDb(请求数:Request)捕获 Postman 请求。

oyxsuwqo

oyxsuwqo1#

根据文档
目前我选择将内容保存在本地目录中,您可以根据需要从contents变量中进行操作

from starlette.requests import Request
from starlette.routing import Route, Mount
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse, FileResponse   

class Post:
    async def PostValuesToDb(requests: Request):
        form = await requests.form()
        # print(dir(form)) # check what methods and attrs are available
        # print(form.multi_items) # check all form fields submitted
        filename = form["image"].filename # my particular form field
        contents = await form["image"].read()
        with open(f'./data/{filename}', 'wb') as uploaded_file:
            uploaded_file.write(contents)
        return PlainTextResponse("true")

routes = [
    Route("/post", Post.PostValuesToDb,
          name="PostValuesToDb", methods=["POST"]),

]

app = Starlette(
    routes=routes
)

相关问题