1.文件上傳
如果要完成文件上傳,則需要對上文的form做一點改動,具體如下:
<form action="/upload" method="post" enctype="multipart/form-data"> Category: <input type="text" name="category" /> Select a file: <input type="file" name="upload" /> <input type="submit" value="Start upload" /> </form>
bottle把file的upload 是放在BaseRequest.files里的(以FileUpload進程的方式存在),這里,我們的例子,都是假設存在硬盤里的
@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'
2)有些js或者REST的客戶端,發送application/json 給服務器,通過這個方式來傳遞信息。這個時候,BaseRequest.json屬性就保存這些信息。
The raw request body
You can access the raw body data as a file-like object via BaseRequest.body. This is a BytesIO buffer or a
temporary file depending on the content length and BaseRequest.MEMFILE_MAX setting. In both cases the body
is completely buffered before you can access the attribute. If you expect huge amounts of data and want to get direct
unbuffered access to the stream, have a look at request[’wsgi.input’].
3)WSGI環境
每個的BaseRequest都保存着一個WSGI的環境字典。
舉例如下;
@app.route('/my_ip') def get_remote_ip(): ip=request.environ.get('REMOTE_ADDR') return template('Your IP is:{{IP}}',IP=ip)
4)template
bottle自帶一個模板,稱之為:SimpleTemplate Engine
使用這個模板,可以通過template()函數或者view()裝飾器。
只需要把模板名稱和要替換的參數信息傳遞進去即可。
比如:
@route('/hello') @route('/hello/<name>') def hello(name='World'): return template('hello_template', name=name)
bottle去哪里找這些模板呢:去./VIEWS/目錄下或者Bottle.template_path環境變量。
Templates are cached in memory after compilation. Modifications made to the template files will have no affect until
you clear the template cache. Call bottle.TEMPLATES.clear() to do so. Caching is disabled in debug mode.