可以当作一个 demo 来玩吧,在这里分享一下。里面涉及的内容包含了文件上传,cookie 设置和读取,重定向(redirect)。
from bottle import run, post, get, request, response, redirect
import os login_page='''
<b>Sorry! Authentication is needed!</b>
<form action='/login' enctype="multipart/form-data" method='post'>
<fieldset>
<legend>Input passwd for Admin:</legend>
<label>passwd:</label>
<input type="password" name="passwd"/>
<input type='submit' value='submit'>
</fieldset>
</form>
'''
upload_page='''
<!DOCTYPE html>
<html>
<head>
<title>
Firmware Update
</title>
</head>
<body>
<form action='/upload' enctype="multipart/form-data" method='post'>
<fieldset>
<legend>Firmware Update:</legend>
<label>Select the file:</label>
<input type="file" name="upload"/>
<input type='submit' value='submit'>
</fieldset>
</form>
</body>
</html>
''' @get('/')
def home():
usr = request.get_cookie("account")
if usr:
redirect('/upload')
else:
return login_page @post('/login')
def login():
passwd = request.POST['passwd'] if passwd == '':
response .set_cookie("account", 'admin')
redirect('/upload')
else:
return 'wrong! go back & retry!' @get('/upload')
def upload():
usr = request.get_cookie("account")
if usr:
return upload_page
else:
redirect('/') @get('/logout')
def logout():
response.delete_cookie("account")
redirect('/') @post('/upload')
def do_upload():
usr = request.get_cookie("account")
if usr:
upload = request.files.get('upload')
name, ext = os.path.splitext(upload.filename)
if ext not in ('.tgz','.gz'):
return 'You give a wrong file. Retry!' save_path = "/opt/myapp/update.tar.gz"
with open(save_path, 'w') as open_file:
open_file.write(upload.file.read()) return '''
<b>Done! Please re-power the machine to fill the update! </b>
<a href="/logout" title="logout">logout</a>
'''
else:
redirect('/') run(host='192.168.1.230', port=80)