1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| from flask import Flask, request, redirect, g, send_from_directory import sqlite3 import os import uuid
app = Flask(__name__)
SCHEMA = """CREATE TABLE files ( id text primary key, path text ); """
def db(): g_db = getattr(g, '_database', None) if g_db is None: g_db = g._database = sqlite3.connect("database.db") return g_db
@app.before_first_request def setup(): os.remove("database.db") cur = db().cursor() cur.executescript(SCHEMA)
@app.route('/') def hello_world(): return """<!DOCTYPE html> <html> <body> <form action="/upload" method="post" enctype="multipart/form-data"> Select image to upload: <input type="file" name="file"> <input type="submit" value="Upload File" name="submit"> </form> <!-- /source --> </body> </html>"""
@app.route('/source') def source(): return send_from_directory(directory="/var/www/html/", path="www.zip", as_attachment=True)
@app.route('/upload', methods=['POST']) def upload(): if 'file' not in request.files: return redirect('/') file = request.files['file'] if "." in file.filename: return "Bad filename!", 403 conn = db() cur = conn.cursor() uid = uuid.uuid4().hex try: cur.execute("insert into files (id, path) values (?, ?)", (uid, file.filename,)) except sqlite3.IntegrityError: return "Duplicate file" conn.commit()
file.save('uploads/' + file.filename) return redirect('/file/' + uid)
@app.route('/file/<id>') def file(id): conn = db() cur = conn.cursor() cur.execute("select path from files where id=?", (id,)) res = cur.fetchone() if res is None: return "File not found", 404
with open(os.path.join("uploads/", res[0]), "r") as f: return f.read()
if __name__ == '__main__': app.run(host='0.0.0.0', port=80)
|