create a web upload with flask

(venv) lindas-MacBook-Air:hello linda$ cat main.py

import os

# import magic

import urllib.request

from app import app

from flask import Flask, flash, request, redirect, render_template

from werkzeug.utils import secure_filename


ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])



def allowed_file(filename):

return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS



@app.route('/')

def upload_form():

return render_template('upload.html')



@app.route('/', methods=['POST'])

def upload_file():

if request.method == 'POST':

# check if the post request has the file part

if 'file' not in request.files:

flash('No file part')

return redirect(request.url)

file = request.files['file']

if file.filename == '':

flash('No file selected for uploading')

return redirect(request.url)

if file and allowed_file(file.filename):

filename = secure_filename(file.filename)

file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

flash('File successfully uploaded')

return redirect('/')

else:

flash('Allowed file types are txt, pdf, png, jpg, jpeg, gif')

return redirect(request.url)



if __name__ == "__main__":

app.run()

(venv) lindas-MacBook-Air:hello linda$ cat app.py

from flask import Flask


UPLOAD_FOLDER = '/Users/linda/PycharmProjects/hello'


app = Flask(__name__)

app.secret_key = "secret key"

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

(venv) lindas-MacBook-Air:hello linda$ cat templates/upload.html

<!doctype html>

<title>Python Flask File Upload Example</title>

<h2>Select a file to upload</h2>

<p>

{% with messages = get_flashed_messages() %}

{% if messages %}

<ul class=flashes>

{% for message in messages %}

<li>{{ message }}</li>

{% endfor %}

</ul>

{% endif %}

{% endwith %}

</p>

<form method="post" action="/" enctype="multipart/form-data">

<dl>

<p>

<input type="file" name="file" autocomplete="off" required>

</p>

</dl>

<p>

<input type="submit" value="Submit">

</p>

</form>

(venv) lindas-MacBook-Air:hello linda$ python3 main.py

* Serving Flask app "app" (lazy loading)

* Environment: production

WARNING: This is a development server. Do not use it in a production deployment.

Use a production WSGI server instead.

* Debug mode: on

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

* Restarting with stat

* Debugger is active!

* Debugger PIN: 238-054-382