Snippets Collections
import imghdr
import os
from flask import Flask, render_template, request, redirect, url_for, abort, \
    send_from_directory
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

def validate_image(stream):
    header = stream.read(512)
    stream.seek(0)
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')

@app.errorhandler(413)
def too_large(e):
    return "File is too large", 413

@app.route('/')
def index():
    files = os.listdir(app.config['UPLOAD_PATH'])
    return render_template('index.html', files=files)

@app.route('/', methods=['POST'])
def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            return "Invalid image", 400
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return '', 204

@app.route('/uploads/<filename>')
def upload(filename):
    return send_from_directory(app.config['UPLOAD_PATH'], filename)
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            return "Invalid image", 400
@app.errorhandler(413)
def too_large(e):
    return "File is too large", 413
<html>
  <head>
    <title>File Upload</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.1/min/dropzone.min.css">
  </head>
  <body>
    <h1>File Upload</h1>
    <form action="{{ url_for('upload_files') }}" class="dropzone">
    </form>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.1/min/dropzone.min.js"></script>
  </body>
</html>
@app.route('/uploads/<filename>')
@login_required
def upload(filename):
    return send_from_directory(os.path.join(
        app.config['UPLOAD_PATH'], current_user.get_id()), filename)
<!doctype html>
<html>
  <head>
    <title>File Upload</title>
  </head>
  <body>
    <h1>File Upload</h1>
    <form method="POST" action="" enctype="multipart/form-data">
      <p><input type="file" name="file"></p>
      <p><input type="submit" value="Submit"></p>
    </form>
    <hr>
    {% for file in files %}
      <img src="{{ url_for('upload', filename=file) }}" style="width: 64px">
    {% endfor %}
  </body>
</html>
import imghdr
import os
from flask import Flask, render_template, request, redirect, url_for, abort, \
    send_from_directory
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

def validate_image(stream):
    header = stream.read(512)  # 512 bytes should be enough for a header check
    stream.seek(0)  # reset stream pointer
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')

@app.route('/')
def index():
    files = os.listdir(app.config['UPLOAD_PATH'])
    return render_template('index.html', files=files)

@app.route('/', methods=['POST'])
def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            abort(400)
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return redirect(url_for('index'))

@app.route('/uploads/<filename>')
def upload(filename):
    return send_from_directory(app.config['UPLOAD_PATH'], filename)
import imghdr
import os
from flask import Flask, render_template, request, redirect, url_for, abort
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

def validate_image(stream):
    header = stream.read(512)
    stream.seek(0) 
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            abort(400)
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return redirect(url_for('index'))
import imghdr

def validate_image(stream):
    header = stream.read(512)
    stream.seek(0)
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')
import os
from flask import Flask, render_template, request, redirect, url_for, abort
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS']:
            abort(400)
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return redirect(url_for('index'))
>>> from werkzeug.utils import secure_filename
>>> secure_filename('foo.jpg')
'foo.jpg'
>>> secure_filename('/some/path/foo.jpg')
'some_path_foo.jpg'
>>> secure_filename('../../../.bashrc')
'bashrc'
uploaded_file.save(os.path.join('static/avatars', current_user.get_id()))
    filename = uploaded_file.filename
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in current_app.config['UPLOAD_EXTENSIONS']:
            abort(400)
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def upload_file():
    uploaded_file = request.files['file']
    if uploaded_file.filename != '':
        uploaded_file.save(uploaded_file.filename)
    return redirect(url_for('index'))
<!doctype html>
<html>
  <head>
    <title>File Upload</title>
  </head>
  <body>
    <h1>File Upload</h1>
    <form method="POST" action="" enctype="multipart/form-data">
      <p><input type="file" name="file"></p>
      <p><input type="submit" value="Submit"></p>
    </form>
  </body>
</html>
import threading

@app.route('/long-task')
def long_task():
	threading.Thread(target=do_long_task).start()
	return "Task started"
@app.route('/long-task')
def long_task():
	do_long_task()
	return "Task completed"
myapp
|
|--app
|    |--main
|    |    |--__init__.py
|    |    |--main.py
|    |
|    |--auth
|    |    |--__init__.py
|    |    |--auth.py
|    |
|    |--__init__.py
|    |--errors.py
|    |--models.py
|    |-- templates/
|    |--static/
|
|--tests/
|--config.py
|--myapp.py
|--requirements.txt
ecommerce/
|
├── static/
|   ├── logo.png
|   ├── main.css
|   ├── generic.js
|   └── product_view.js
|
├── templates/
|   ├── login.html
|   ├── forgot_password.html
|   ├── signup.html
|   ├── checkout.html
|   ├── cart_view.html
|   ├── index.html
|   ├── products_list.html
|   └── product_view.html
|
├── app.py
├── config.py
└── models.py
<!doctype html>
<html>
<head>
    <title>Home page</title>
    </head>
    <body>
	{% if content == "true" %}
            <p>True!</p>
        {% else %}
            <p>False :(</p>
        {% endif %}
    </body>
</html>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>{% block title %}{% endblock %}</title>
        <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='site.css')}}" />
    </head>

    <body>
        <div class="navbar">
            <a href="{{ url_for('home') }}" class="navbar-brand">Home</a>
            <a href="{{ url_for('about') }}" class="navbar-item">About</a>
            <a href="{{ url_for('contact') }}" class="navbar-item">Contact</a>
        </div>

        <div class="body-content">
            {% block content %}
            {% endblock %}
            <hr/>
            <footer>
                <p>© 2018</p>
            </footer>
        </div>
    </body>
</html>

export FLASK_ENV=development                         

export FLASK_ENV=production 

FLASK_APP=hello.py flask run






If you have installed many dependencies in your system and you need requirements.txt for a specific project, you can install first pipreqs:

$ pip install pipreqs

and execute the below command under the project folder.

$ pipreqs

This command will generate requirements.txt file for the particular project.
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"
from flask import Flask,render_template,request, redirect
 
 
app = Flask(__name__)
app.config['SECRET_KEY'] = 'dajdsjas'
 
 
@app.route('/home')
def home():
    return 'Home page'
 
 
 
@app.route('/take_parameter', methods = ["POST"])
def takeparam():
    try:
        pas = request.args(silent=True)
        #app.logger.info(json)
        return 'OK'
    except:
        return 'INTERNAL ERROR', 500
    
 
@app.route('/take_json', methods = ["POST"])
def takejson():
    try:
        pas = request.get_json(silent=True)
        #app.logger.info(json)
        return 'OK'
    except:
        return 'INTERNAL ERROR', 500
    
if __name__ =='__main__':
    app.run(debug=True)
 
star

Tue Sep 06 2022 14:21:28 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #validation #uploadfile
star

Tue Sep 06 2022 14:20:40 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #validation #flask #uploadfile
star

Tue Sep 06 2022 14:19:49 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #validation
star

Tue Sep 06 2022 13:31:07 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#html #flask #uploadform
star

Tue Sep 06 2022 13:30:25 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #uploadfile #flask
star

Tue Sep 06 2022 13:20:51 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#html #uploadform #flask
star

Tue Sep 06 2022 13:20:18 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #uploadfile #validation
star

Tue Sep 06 2022 13:13:22 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #uploadfile #validation
star

Tue Sep 06 2022 13:12:28 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #uploadfile #validation
star

Tue Sep 06 2022 13:11:41 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #uploadfile #secure
star

Tue Sep 06 2022 13:10:37 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #uploadfile
star

Tue Sep 06 2022 13:10:00 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #flask-login #uploadfile
star

Tue Sep 06 2022 13:08:58 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #uploadfile
star

Tue Sep 06 2022 13:08:14 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#flask #uploadfile
star

Tue Sep 06 2022 13:07:54 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#flask #uploadfile
star

Tue Sep 06 2022 12:37:21 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #uploadfile
star

Tue Sep 06 2022 12:13:13 GMT+0000 (UTC) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #inputfile
star

Tue Sep 06 2022 12:12:03 GMT+0000 (UTC) undefined

#python #flask
star

Tue Feb 22 2022 15:40:56 GMT+0000 (UTC)

#flask #python
star

Tue Feb 22 2022 15:37:55 GMT+0000 (UTC)

#flask #python
star

Fri Dec 10 2021 17:11:35 GMT+0000 (UTC) https://dev.to/blankgodd/creating-a-blueprint-based-flask-app-199h

#flask
star

Fri Dec 10 2021 17:03:04 GMT+0000 (UTC) https://realpython.com/flask-blueprint/

#flask
star

Thu Dec 09 2021 18:07:50 GMT+0000 (UTC) https://www.techwithtim.net/tutorials/flask/html-templates/

#flask
star

Thu Dec 09 2021 17:50:06 GMT+0000 (UTC) https://code.visualstudio.com/docs/python/tutorial-flask

#flask
star

Sun Jun 27 2021 14:09:50 GMT+0000 (UTC) https://stackoverflow.com/questions/31252791/flask-importerror-no-module-named-flask

#python #flask
star

Sun Jun 27 2021 14:09:38 GMT+0000 (UTC) https://stackoverflow.com/questions/31252791/flask-importerror-no-module-named-flask

#python #flask
star

Thu Oct 22 2020 09:00:37 GMT+0000 (UTC)

#python #flask
star

Wed May 13 2020 18:55:25 GMT+0000 (UTC) https://www.youtube.com/watch?v=zdgYw-3tzfI

#flask

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension