gpt4 book ai didi

python-3.x - Falcon 和 falcon-multipart + POST 请求上传文件的实现

转载 作者:行者123 更新时间:2023-12-01 00:20:44 25 4
gpt4 key购买 nike

我正在尝试使用 Falcon 框架(python)实现上传文件的 POST 请求。

我已经使用 falcon-multipart 来实现 multipart/form-data,这允许我在 cgi.FieldStorage() 中检索我的文件,其中文件是二进制格式,但是现在,我需要将此文件写入一个目录中原始扩展名。

这是我正在使用的代码。

应用程序.py:

import falcon

from .files import Resource

from falcon_multipart.middleware import MultipartMiddleware

api = application = falcon.API(middleware=[MultipartMiddleware()])

files = Resource()
api.add_route('/files', files)

文件.py:
import io
import os
import shutil

import falcon
import json


class Resource(object):

_storage_path = './uploaded_files'

def on_post(self, req, resp):
"""
POST METHOD
"""
# Retrieve file extension
ext = req.get_param('extension')

# Retrieve input_file
input_file = req.get_param('file')

# Read file as binary
raw = input_file.file.read()

# Retrieve filename
filename = input_file.filename

# Define file_path
file_path = os.path.join(self._storage_path, filename)

# Write to a temporary file to prevent incomplete files from
# being used.
temp_file_path = file_path + '~'

# Finally write the data to a temporary file
with open(temp_file_path, 'wb') as output_file:
shutil.copyfileobj(raw, output_file)

# Now that we know the file has been fully saved to disk
# move it into place.
os.rename(temp_file_path, file_path)

resp.status = falcon.HTTP_201

最佳答案

我不得不学习 cgi

  • cgi - File upload
  • cgi - Big file upload

  • 这是我使用的实现:
    def on_post(self, req, resp):
    """
    POST METHOD
    """
    # Retrieve input_file
    input_file = req.get_param('file')

    # Test if the file was uploaded
    if input_file.filename:
    # Retrieve filename
    filename = input_file.filename

    # Define file_path
    file_path = os.path.join(self._storage_path, filename)

    # Write to a temporary file to prevent incomplete files
    # from being used.
    temp_file_path = file_path + '~'

    open(temp_file_path, 'wb').write(input_file.file.read())

    # Now that we know the file has been fully saved to disk
    # move it into place.
    os.rename(temp_file_path, file_path)

    resp.status = falcon.HTTP_201

    关于python-3.x - Falcon 和 falcon-multipart + POST 请求上传文件的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48940530/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com