700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python bottle 上传文件_bottle.py 实现批量文件上传

python bottle 上传文件_bottle.py 实现批量文件上传

时间:2023-12-20 07:50:46

相关推荐

python bottle 上传文件_bottle.py 实现批量文件上传

bottle.py是python的一个Web框架,整个框架只有一个文件,几十K,却自带了路径映射、模板、简单的数据库访问等web框架组件,确实是个可用的框架。初学web开发可以拿来玩玩,其语法简单,部署也很方便。官方文档: /docs/dev/tutorial.html (官方文档的介绍挺好懂的,主要是这个框架比较小)

先演示一个简单的例子吧:

from bottle import route, run

@route('/:name')

def index(name='World'):

return 'Hello %s!' % name

run(host='localhost', port=8080)

我准备使用bottle.py实现一个批量文件上传的功能,但是根据官方文档的介绍,它只提供了一个上传一个文件的功能,文档介绍如下:

FILE UPLOADS

To support file uploads, we have to change the tag a bit. First, we tell the browser to encode the form data in a different way by adding an enctype=”multipart/form-data” attribute to the tag. Then, we add tags to allow the user to select a file. Here is an example:*

Category:

Select a file:

Bottle stores file uploads in BaseRequest.files as FileUpload instances, along with some metadata about the upload. Let us assume you just want to save the file to disk:

@route('/upload', method='POST')

def do_upload():

category = request.forms.get('category')

upload = request.files.get('upload')

name, ext = os.path.splitext(upload.filename)

if ext not in ('.png','.jpg','.jpeg'):

return 'File extension not allowed.'

save_path = get_save_path_for_category(category)

upload.save(save_path) # appends upload.filename automatically

return 'OK'

FileUpload. filename contains the name of the file on the clients file system, but is cleaned up and normalized to prevent bugs caused by unsupported characters or path segments in the filename. If you need the unmodified name as sent by the client, have a look at FileUpload.raw_filename.

The FileUpload.save method is highly recommended if you want to store the file to disk. It prevents some common errors (e.g. it does not overwrite existing files unless you tell it to) and stores the file in a memory efficient way. You can access the file object directly via FileUpload.file. Just be careful.

文档中提供了FileUpload.filename,FileUpload.raw_filename,FileUpload.file,FileUpload.save等接口,我们可以使用FileIpload.save来保存文件到磁盘,可以使用FileIpload.file来完成读取二进制流的任务,大家可以根据需要来完成相应的需求,下面我给出一个批量上传图片的例子,并以二进制流来读取它们(读完之后大家可以将这些数据保存到数据库中)

#!/usr/bin/env python

from bottle import run,post,get,request

@get(r'/')

def index():

return '''

Solution 4-5: Sending multiple files

Solution 4-5: Sending multiple files

Upload one or more files:

'''

@post(r'/up')

def uploadFile():

upload = request.files.getall('upload')

for meta in upload:

buf = meta.file.read()

print ('image:',str(buf))

run(host='localhost', port=8888,debug=True)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。