[PYTHON] Image uploader in Flask

Create a simple image uploader

Since I created the Twitter posting client last time, I will omit the installation of Flask.  http://qiita.com/Gen6/items/ff1d163acf0fa7687454

Make a template

index.html


{% extends "base.html" %}
{% block content %}
<form method="post" action="/send" enctype="multipart/form-data">
  <input type="file" id="img_file" name="img_file" class="col-sm-4">
  <input type="submit" value="Send" class="btn">
</form>
  {% if img_url %}
<p><img src="{{ img_url }}"></p>
  {% endif %}
{% endblock %}

enctype = "multipart / form-data" is important.

base.html


<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/css/style.css">
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <title>File</title>
</head>
<body>
  <div class="container">
    <div class="row">
        {% block content %}
        {% endblock %}
    </div>
  </div>
</body>
</html>

Create an application

After that, I will make a file upload. I'm just importing SQlite3 as I may use it in the future.

upload.py


import os
import sqlite3
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, session
from werkzeug import secure_filename
app = Flask(__name__)

UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'gif'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SECRET_KEY'] = os.urandom(24)

def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/')
def index():
    if 'username' in session:
        return render_template('index.html')
    return '''
        <p>Please login</p>
    '''

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        if username == 'admin':
            session['username'] = request.form['username']
            return redirect(url_for('index'))
        else:
            return '''<p>The user name is different</p>'''
    return '''
        <form action="" method="post">
            <p><input type="text" name="username">
            <p><input type="submit" value="Login">
        </form>
    '''

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('index'))

@app.route('/send', methods=['GET', 'POST'])
def send():
    if request.method == 'POST':
        img_file = request.files['img_file']
        if img_file and allowed_file(img_file.filename):
            filename = secure_filename(img_file.filename)
            img_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            img_url = '/uploads/' + filename
            return render_template('index.html', img_url=img_url)
        else:
            return ''' <p>Not allowed extension</p> '''
    else:
        return redirect(url_for('index'))

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

if __name__ == '__main__':
    app.debug = True
    app.run()

Like last time, I tried to make it a specification that can not be uploaded without logging in. Files that are allowed to be uploaded

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

Like this, you can allow .txt and so on, and as a result, it is easy to customize for uploaders other than images. It's useless without a secret key, so

app.config['SECRET_KEY'] = os.urandom(24)

I am generating it.

This time, I want to see only the image upload result immediately.

img_url = '/uploads/' + filename

I don't know because it's written in a sloppy way.

Execution result

スクリーンショット 2017-05-18 15.23.26.png

done.

Recommended Posts

Image uploader in Flask
Image sending / receiving memo in Python (Flask)
Image format in Python
Image normalization in TensorFlow
How to create an image uploader in Bottle (Python)
Tweet with image in Python
Image Processing Collection in Python
Image addition memo in reportlab
Simply check Content-Type in Flask (@content_type)
Celery asynchronous processing in Flask
Upload multiple files in Flask
Use <input type = "date"> in Flask
SLIC Superpixel segmentation in scikit image
Implemented image segmentation in python (Union-Find)
Django1.11.1 Image uploader Easy to stumble
Detect mosaic points in the image
[Image connection] Arrange images in tiles
Fixed Apscheduler running twice in Flask
flask
Hello World in Flask [Appropriate memo]
flask
Configuration file best practices in Flask
Image upload function with Vue.js + Flask
View image after Data Augmentation in PyTorch
Page cache in Python + Flask with Flask-Caching
Image recognition model using deep learning in 2016
Cut out A4 print in the image
(For myself) Put Flask in VS Code
Minimum knowledge to use Form in Flask
Launch a Flask app in Python Anywhere
Face image inference using Flask and TensorFlow
How to adjust image contrast in Python
Easy image processing in Python with Pillow
CG image quality evaluation memo in Python
Create and deploy Flask apps in PTVS
Automatically map controllers from URLs in Flask