Skip to content

Instantly share code, notes, and snippets.

@othmanalikhan
Created January 27, 2022 13:43
Show Gist options
  • Save othmanalikhan/ebcb6f3ae12f3becf54b051ab39806be to your computer and use it in GitHub Desktop.
Save othmanalikhan/ebcb6f3ae12f3becf54b051ab39806be to your computer and use it in GitHub Desktop.
Bare bones Python (Flask) Upload/Download Server
"""
Bare bones download/upload Python server using Flask.
"""
import os
from flask import (
Flask, redirect, render_template_string, request, send_from_directory
)
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = '.'
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/<path:filename>')
def _downloadFile(filename):
return send_from_directory(
os.path.abspath('.'),
filename,
as_attachment=True
)
@app.route('/', methods=['GET', 'POST'])
def uploadFile():
if request.method == 'GET':
filenames = os.listdir('.')
return render_template_string(HOME_PAGE, files=filenames)
if request.method == 'POST':
if request.files['file']:
file = request.files['file']
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(request.url)
HOME_PAGE = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Logfiles</title>
</head>
<h1>Download File</h1>
<body>
<ul>
{% for file in files %}
<li><a href="{{ url_for('_downloadFile', filename=file) }}">{{ file }}</a></li>
{% endfor %}
</ul>
</body>
<h1>Upload File</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
</html>
"""
if __name__ == '__main__':
app.run(host='192.168.1.102', port=8000, debug=True, threaded=True)
@othmanalikhan
Copy link
Author

Below is a screenshot of the server in action:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment