[Raspberry Pi] Publish a web application on https using Apache + WSGI + Python Flask

Overview

Publish a web application using Python's Flask framework on Raspberry Pi. At that time, SSL is also supported by linking with Apache using WSGI.

Introduction

This article is based on the assumption that the initial settings of Raspberry Pi, domain acquisition, Apache2 installation, port opening, SSL certificate acquisition, etc. have been completed. If you have not done so, we recommend that you make those settings first.

-Easy home server with raspberry pi web server version --Qiita -Made the Raspberry Pi web server compatible with https --Qiita

usage environment

Environment

Install mod_wsgi with the following command: Please note that if the Python version is 2 or less, the one to be installed is different.

$ sudo apt-get install libapache2-mod-wsgi-py3

If Python version is 2 or less

$ sudo apt-get install libapache2-mod-wsgi

If you don't have the Flask framework installed in Python, install it.

$ sudo pip3 install Flask

Preparing Flask application

file organization

The file structure of the Flask application is as follows.

└ var/
  └ www/
    └ flask/
      ├ app.py
      ├ app.wsgi
      └ templates/
        └ test.html

Creating a sample

app.py


#!/usr/bin/ python3
# -*- coding: utf-8 -*-

#Flask framework import
from flask import Flask
#Template engine import
from flask import render_template

#Creating a Flask instance
app = Flask(__name__)

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

#Execution content when the application starts
if __name__ == '__main__':
    app.run()

app.wsgi


#!/usr/bin/ python3
# -*- coding:utf-8 -*-

import sys

#Specifying the path
sys.path.insert(0, '/var/www/flask')
from app import app
application = app

test.html


<html>
  <body>
    <h1>Hello Flask!</h1>
  </body>
</html>

Sample operation check

Enter the command and check if the app works properly

$ python3 /var/www/flask/app.py

Finally, if you see Running on http://127.0.0.1: <port number>/(Press CTRL + C to quit), you are successful. Open another terminal as it is, enter the following command and check if html can be obtained normally.

$ curl localhost:<port number>

If you can get the contents of test.html, it is successful. Press CTRL + C to quit the app once.

Apache2 settings

Create the following files in/etc/apache2/sites-available /. Please do it with root privileges.

flask_wsgi.conf


#IfModule is not used for code simplification

#Redirect http communication to https communication
<VirtualHost *:80>
	RewriteEngine On
	RewriteCond %{HTTPS} off
	RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,END]
</VirtualHost>

#https communication settings
<VirtualHost *:443>
	ServerName <Server name>
	ServerAdmin <Administrator email address>

	DocumentRoot /var/www/flask

	WSGIDaemonProcess app user=<username> group=<User group> threads=5
	WSGIScriptAlias / /var/www/flask/app.wsgi

	ErrorLog ${APACHE_LOG_DIR}/error.log
	CustomLog ${APACHE_LOG_DIR}/access.log combined

	SSLEngine on

	SSLCertificateFile <SSL certificate fullchain.pem path>
	SSLCertificateKeyFile <SSL certificate prevkey.pem path>

	<FilesMatch "\.(cgi|shtml|phtml|php)$">
		SSLOptions +StdEnvVars
	</FilesMatch>
	<Directory /usr/lib/cgi-bin>
		SSLOptions +StdEnvVars
	</Directory>

	<Directory /var/www/flask/>
		WSGIProcessGroup app
		WSGIApplicationGroup %{GLOBAL}
		WSGIScriptReloading On

		Require all granted
		Options FollowSymLinks
		AllowOverride All
	</Directory>
</VirtualHost>

Then enter the following command to enable the config.

$ sudo a2ensite flask_wsgi

Check /etc/apache2/sites-enabled to see if other config files (such as 000-default.conf) are enabled. If the server names are not clearly separated, there is a possibility of conflict, so disable it with the following command.

$ sudo a2dissite <Other config files>

Once you've done that, restart Apache.

$ sudo service apache2 restart

If you can restart without error, open your browser and check. If you can get the contents of test.html normally with your browser, it is successful. Thank you for your hard work.

reference

-Until you run Flask on Apache (Apache2 + wsgi + Flask)

Recommended Posts

[Raspberry Pi] Publish a web application on https using Apache + WSGI + Python Flask
Creating a web application using Flask ②
Creating a web application using Flask ①
Creating a web application using Flask ③
Creating a web application using Flask ④
Detect "temperature (using A / D converter)" using python on Raspberry Pi 3!
Detect "brightness" using python on Raspberry Pi 3!
Run servomotor on Raspberry Pi 3 using python
Detect temperature using python on Raspberry Pi 3!
Create a Python3.4 + Nginx + uWSGI + Flask Web application execution environment with haste using pyenv on Ubuntu 12.04
Detect analog signals with A / D converter using python on Raspberry Pi 3!
I want to make a web application using React and Python flask
Detect slide switches using python on Raspberry Pi 3!
Try using a QR code on a Raspberry Pi
Detect magnet switches using python on Raspberry Pi 3!
Sound the buzzer using python on Raspberry Pi 3!
Build a Python development environment on Raspberry Pi
Using the 1-Wire Digital Temperature Sensor DS18B20 from Python on a Raspberry Pi
(Python) Try to develop a web application using Django
Output to "7-segment LED" using python on Raspberry Pi 3!
Create a web application execution environment of Python3.4 + Nginx + uWSGI + Flask with haste using venv on Ubuntu 14.04 LTS
Web application with Python + Flask ② ③
Web application with Python + Flask ④
Access google spreadsheet using python on raspberry pi (for myself)
Try using ArUco on Raspberry Pi
Using a webcam with Raspberry Pi
Web application created with Python + Flask (using VScode) # 1-Virtual environment construction-
Build a Flask / Bottle-like web application on AWS Lambda with Chalice
[Note] Using 16x2-digit character LCD (1602A) from Python with Raspberry Pi
Try using the web application framework Flask
Finally ... Make a radio control using python on Raspberry Pi 3! (The motor moves while the button is pressed)
Adafruit Python BluefruitLE works on Raspberry Pi.
[Python] A quick web application with Bottle!
[GCP] Procedure for creating a web application with Cloud Functions (Python + Flask)
Until you publish (deploy) a web application made with bottle on Heroku
Run a Python web application with Docker
Start a web server using Bottle and Flask (I also tried using Apache)
Publish a web application for viewing data created with Streamlit on heroku
Implement a simple application with Python full scratch without using a web framework.
Working with GPS on Raspberry Pi 3 Python
Finally ... Make a radio control using python on Raspberry Pi 3! (The motor moves while the magnet is brought closer)
Source compile Apache2.4 + PHP7.4 with Raspberry Pi and build a Web server --2 PHP introduction
[ES Lab] I tried to develop a WEB application with Python and Flask ②
Source compile Apache2.4 + PHP7.4 with Raspberry Pi and build a Web server ―― 1. Apache introduction
I tried running Flask on Raspberry Pi 3 Model B + using Nginx and uWSGI
Until you install Python with pythonbrew and run Flask on a WSGI server
Until you publish a web service on GCP while studying JQuery and Python
[Python] Split a large Flask file using Blueprint
Build a Django environment on Raspberry Pi (MySQL)
Vienna with Python + Flask web app on Jenkins
Run Python web apps on NGINX + NGINX Unit + Flask
Create a web map using Python and GDAL
Steps to develop a web application in Python
Launch a web server with Python and Flask
A memorandum for touching python Flask on heroku
Make DHT11 available on Raspberry Pi + python (memo)
Create a visitor notification system using Raspberry Pi
Connect to MySQL with Python on Raspberry Pi
Source compile Apache2.4 + PHP7.4 with Raspberry Pi and build a web server --3. Use MySQL
Install PyCall on Raspberry PI and try using GPIO's library for Python from Ruby
A little trick to know when writing a Twilio application using Python on AWS Lambda