Python Sanic 框架下的文件上传功能实现

2024-12-28 22:25:00   小编

Python Sanic 框架下的文件上传功能实现

在当今的 Web 开发中,文件上传是一个常见且重要的功能。Python 的 Sanic 框架以其高效和简洁的特点,为实现文件上传提供了便捷的途径。

确保已经安装了 Sanic 框架。然后,我们来创建一个基本的 Sanic 应用。

from sanic import Sanic
from sanic.response import json

app = Sanic(__name__)

接下来,定义文件上传的路由和处理函数。

@app.route('/upload', methods=['POST'])
async def upload_file(request):
    # 检查是否有文件上传
    if 'file' not in request.files:
        return json({'message': 'No file part'}, status=400)

    file = request.files['file']

    # 进行文件保存等操作
    # 例如,保存到指定目录
    file_path = f'uploads/{file.name}'
    with open(file_path, 'wb') as f:
        f.write(file.body)

    return json({'message': 'File uploaded successfully'}, status=200)

在上述代码中,我们首先检查请求中是否包含文件。如果没有,返回错误信息。如果有文件,我们获取文件对象,并指定保存的路径和文件名,然后将文件内容写入到该路径中。

为了确保文件上传的安全性和有效性,还可以添加一些额外的处理,比如文件类型的检查、文件大小的限制等。

@app.route('/upload', methods=['POST'])
async def upload_file(request):
    if 'file' not in request.files:
        return json({'message': 'No file part'}, status=400)

    file = request.files['file']

    # 检查文件类型
    allowed_types = ['jpg', 'png', 'pdf']  # 允许的文件类型列表
    if file.name.split('.')[-1] not in allowed_types:
        return json({'message': 'Invalid file type'}, status=400)

    # 检查文件大小
    max_size = 1024 * 1024  # 最大文件大小,例如 1MB
    if len(file.body) > max_size:
        return json({'message': 'File size exceeded'}, status=400)

    file_path = f'uploads/{file.name}'
    with open(file_path, 'wb') as f:
        f.write(file.body)

    return json({'message': 'File uploaded successfully'}, status=200)

通过以上步骤,我们在 Sanic 框架中成功实现了文件上传功能。在实际应用中,可以根据具体需求进一步完善和优化代码,以满足项目的特定要求。

Sanic 框架为文件上传提供了简洁而强大的支持,使得开发人员能够快速高效地实现这一常见功能,为 Web 应用增添更多的实用性和用户友好性。

TAGS: 文件上传功能 Python Sanic 框架 Sanic 框架应用 Python 开发实践

欢迎使用万千站长工具!

Welcome to www.zzTool.com