欢迎访问宙启技术站
智能推送

使用WebOb进行文件上传和下载的实例教程

发布时间:2023-12-27 17:29:45

WebOb是一个用于处理HTTP请求和响应的Python库,可以用来处理文件上传和下载。它提供了方便的接口和方法来处理这些任务。以下是一个使用WebOb进行文件上传和下载的实例教程。

首先,需要安装WebOb库。可以使用以下命令安装WebOb:

pip install webob

接下来,我们将创建一个简单的Web应用程序来演示文件上传和下载的功能。

from wsgiref.simple_server import make_server
from webob import Request, Response

def upload_form(request):
    html = '''
    <html>
    <body>
        <h1>文件上传示例</h1>
        <form method="POST" action="/upload" enctype="multipart/form-data">
            <input type="file" name="file">
            <input type="submit" value="上传">
        </form>
    </body>
    </html>
    '''
    return Response(html)

def upload_file(request):
    file = request.POST['file']
    filename = file.filename
    file_content = file.file.read()
    
    with open(filename, 'wb') as f:
        f.write(file_content)
    
    return Response('文件上传成功')

def download_file(request):
    filename = 'example.txt'  # 下载的文件名
    
    with open(filename, 'rb') as f:
        file_content = f.read()
    
    response = Response(content_type='application/octet-stream')
    response.content_disposition = 'attachment; filename="%s"' % filename
    response.body = file_content
    
    return response

router = {
    '/': upload_form,
    '/upload': upload_file,
    '/download': download_file
}

def app(environ, start_response):
    request = Request(environ)
    path = request.path
    
    if path in router:
        response = router[path](request)
    else:
        response = Response('页面未找到', status=404)
    
    return response(environ, start_response)

if __name__ == '__main__':
    httpd = make_server('', 8000, app)
    print('Serving on port 8000...')
    httpd.serve_forever()

上述示例中的upload_form函数返回一个简单的HTML表单,其中包含一个文件上传字段。upload_file函数处理文件上传,将上传的文件保存到当前目录下以文件名命名的文件中。download_file函数提供文件下载功能,将文件内容以流的方式返回给客户端。

router是一个字典,将URL路径映射到相应的处理函数。app函数是一个符合WSGI协议的应用程序,根据请求的URL路径调用相应的处理函数。如果没有匹配的处理函数,返回一个404响应。

在运行该脚本后,可以打开浏览器访问http://localhost:8000,可以看到一个简单的文件上传表单。选择一个文件并点击上传按钮,文件将被上传到服务器。上传成功后,可以通过访问http://localhost:8000/download来下载上传的文件。

这是一个简单的使用WebOb进行文件上传和下载的实例教程。WebOb提供了简洁的API来处理HTTP请求和响应,非常适合用于构建Web应用程序中的文件上传和下载功能。