我爲我的大學工作。我們已經學習了python的基礎知識。任務是創建一個讀取fastq文件並分析它的小程序。我認爲用瓶子創建一個基於html的用戶界面會很好。但沒有一個真正的服務器。
我的問題是:我不知道如何訪問上傳的文件。該代碼不會創建新的目錄。我也不知道在哪裏可以找到「上傳」的文件,或者服務器上的新功能如何抓取該文件並使用它。
我讀過以下網站:
http://bottlepy.org/docs/dev/tutorial.html#file-uploads
http://bottlepy.org/docs/dev/api.html#bottle.FileUpload.file How do I access an uploaded file with Bottle?
Bottle file upload and process 等。使用Python3 Bottle訪問上傳的文件
此外,當我嘗試上傳文件時,錯誤令我感到困擾,錯誤是,文件已存在。有類UploadFile
與功能save
,它有一個覆蓋的選項,但我不知道如何實現它。
bottle_test.py:
from bottle import route, run, template, static_file, request, response, url, default_app, get, post, FileUpload
import bottle
import os
# Aufrufen der Hauptseite
@route('/')
def index():
return template('main_template')
# Einbinden unterschiedlicher Dateien z.B. Bilder oder CSS-Files
@route('/static/style/<filepath:re:.*\.css>')
def server_static(filepath):
return static_file(filepath, root='static/style')
@route('/static/images/<filepath:re:.*\.(jpg|png|gif|ico|svg)>')
def img(filepath):
return static_file(filepath, root="static/images")
@route('/static/sonstige-bilder/<filepath:re:.*\.(jpg|png|gif|ico|svg)>')
def img(filepath):
return static_file(filepath, root='static/sonstige-bilder')
# Formularabfrage
@route('/repeat', method='POST')
def do_login():
username = request.forms.get('username')
password = request.forms.get('password')
if username == 'arsenij' and password == '1234':
return "<p>Your login information was correct.</p>"
else:
return "<p>Login failed.</p>"
@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 ('.fastq'):
return 'File extension not allowed.'
save_path = '/tmp/(category)'
if not os.path.exists(save_path):
os.makedirs(save_path)
file_path = "{path}/{file}".format(path=save_path, file=upload.filename)
upload.save(file_path)
print(request.files.get('upload'))
return 'File uploaded'
if __name__ == '__main__':
bottle.debug(True)
bottle.run(host='0.0.0.0', port=8080, reloader=True)
main_template.tpl
<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>
僅供參考,我建議運行代碼通過'pylint'。 –