Simple post and download web app in bottle.
server.py
import sys
import bottle
from bottle import request, response
import pymongo
import gridfs
from bson.objectid import ObjectId
import mimetypes
mimetypes.init()
# Mongo Connection
connection = pymongo.MongoClient("mongodb://localhost")
db = connection.pacman
test_col = db.test
fs = gridfs.GridFS(db)
# Static Routes
@bottle.get('/<filename:re:.*\.js>')
def javascripts(filename):
return bottle.static_file(filename, root='static/js')
@bottle.get('/<filename:re:.*\.css>')
def stylesheets(filename):
return bottle.static_file(filename, root='static/css')
@bottle.get('/<filename:re:.*\.(jpg|png|gif|ico)>')
def images(filename):
return bottle.static_file(filename, root='static/img')
@bottle.get('/<filename:re:.*\.(eot|ttf|woff|svg)>')
def fonts(filename):
return bottle.static_file(filename, root='static/fonts')
@bottle.route('/')
def home_page():
result = db.fs.files.find({"filename": {"$exists": True}})
return bottle.template('files_test/home', files=list(result))
@bottle.route('/add')
def add_page():
return bottle.template('files_test/add')
@bottle.route('/upload', method='POST')
def do_upload():
data = request.files.data
if data:
raw = data.file.read() # This is dangerous for big files
file_name = data.filename
try:
newfile_id = fs.put(raw, filename=file_name)
except:
return "error inserting new file"
print(newfile_id)
return bottle.redirect('/')
@bottle.route('/download')
def download():
file_id = ObjectId(bottle.request.query.id)
if file_id:
try:
file_to_download = fs.get(file_id)
except:
return "document id not found for id:" + file_id, sys.exc_info()[0]
file_extension = str(file_to_download.name)[(str(file_to_download.name).index('.')):]
response.headers['Content-Type'] = (mimetypes.types_map[file_extension])
response.headers['Content-Disposition'] = 'attachment; filename=' + file_to_download.name
response.content_length = file_to_download.length
# print response
return file_to_download
bottle.debug(True)
bottle.run(host='localhost', port=8080)
add.tpl
<!DOCTYPE html>
<!-- pass in files (dict)-->
<html>
<head>
<title>Preformance and Capacity Management</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="data" /><br>
<input type="submit"/>
</form>
</body>
</html>
home.tpl
<!DOCTYPE html>
<!-- pass in files (dict)-->
<html>
<head>
<title>Preformance and Capacity Management</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<br><br><br><br>
%for fileobj in files:
Filename: {{fileobj['filename']}}<br>
Size: {{fileobj['length']}}<br>
Date Uploaded: {{fileobj['uploadDate']}}<br>
md5: {{fileobj['md5']}}<br>
<a href="download?id={{fileobj['_id']}}"><--Download File--></a>
<br><br><br><br>
%end
</body>
</html>