Python Forum
flask nginx full stack web app develepoment
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
flask nginx full stack web app develepoment
#1
Hi,
I am running pi with stretch lite 4gb card by ssh
I have followed several tutorials, and set up my web app, I now want to develop and expand this using the blog tutorial on the flask site, I want to create a light weight heating web app (like this) that is flexible and easy to adapt and that will help me learn python. I have followed a full stack nginx flask web app tutorial, it is old, ment for miniban and unfortunatly has many errors in the script, I have updated the script for stretch. My problem is how to intergrate the blog tutorial into this set up. I will start with all the script for the web app and then what I have done, followed by the error messages etc.
The set up:
Heating.py
from flask import Flask, request, render_template
app = Flask(__name__)
app.debug = True # Make this False if you are no longer debugging

@app.route("/")
def hello():
    return "Hello World!"

@app.route("/heating_temp")
def lab_temp():
        import sys
        import Adafruit_DHT
        humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT 11, 4)
        if humidity is not None and temperature is not None:
                return render_template("heating_temp.html",temp=temperature,hum$
        else:
                return render_template("no_sensor.html")


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080)
heating_nginx.conf
#working directory/app_nginx.conf

server {
    listen      80;
    server_name localhost;
    charset     utf-8;
    client_max_body_size 75M;

    location /static {
        root /var/www/heating/;
    }

    location / { try_files $uri @heating; }
    location @heating {
        include uwsgi_params;
        uwsgi_pass unix:/var/www/heating/heating_uwsgi.sock;
    }
}
heating_uwsgi.ini
#working directory/app_uwsgi.ini

[uwsgi]
#application's base folder
base = /var/www/heating

#python module to import
app = heating
module = %(app)

home = %(base)/env
pythonpath = %(base)

#socket file's location
socket = /var/www/heating/%n.sock

#permissions for the socket file
chmod-socket = 666

#the variable that holds a flask
#application inside the module
#imported at line #6
callable = app

#location of log files
logto = /var/log/uwsgi/%n.log
emperor.uwsgi.service
#/etc/systemd/system/emperor.uwsgi.service

[Unit]
Description=uWSGI Emperor
After=syslog.target
[Service]
ExecStart=/var/www/heating/env/bin/uwsgi --ini /var/www/heating/heating_uwsgi.ini
# Requires systemd version 211 or newer
RuntimeDirectory=uwsgi
Restart=always
KillSignal=SIGQUIT
Type=notify
StandardError=syslog
NotifyAccess=all
[Install]
WantedBy=multi-user.target

#systemctl start emperor.uwsgi.service
#systemctl status emperor.uwsgi.service
#systemctl enable emperor.uwsgi.service
This is a web app that restarts automatically on reboot and works on stretch all these files are in /var/www/heating/ in this folder I all so have a static folder venv environment, templates etc (everthing is done as root). I tried this set up in the home file but it does not work there it only works as root. I have started to follow the blog tutorial and to start I have created a test folder in home (flaskr) and set up the flask app factory (__init__.py) This appears to work and gives no error messages, but as I have no GUI i cant see the web page. Here is the __init__.py
import os

from flask import Flask


def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # a simple page that says hello
    @app.route('/hello')
    def hello():
        return 'Hello, World!'

    return app
and when I activate the app I get the following output
Output:
* Serving Flask app "flaskr" * Environment: development * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 855-212-761
I have now written this file in /var/www/heating/ next to my origional app, I have changed the heating_uwsgi.ini
#working directory/app_uwsgi.ini

[uwsgi]
#application's base folder
base = /var/www/heating

#python module to import
app = __init__
module = %(app)

home = %(base)/env
pythonpath = %(base)

#socket file's location
socket = /var/www/heating/%n.sock

#permissions for the socket file
chmod-socket = 666

#the variable that holds a flask
#application inside the module
#imported at line #6
callable = app

#location of log files
logto = /var/log/uwsgi/%n.log
to restart the app I have to reboot, after any alteration to any of the above files, now I get an "Internal Server Error" on the web page, I have changed the "app = ..." to "hello" and "hello" but still the same error messages. Here is the output of systemctl status emperor.uwsgi.service
Output:
● emperor.uwsgi.service - uWSGI Emperor Loaded: loaded (/etc/systemd/system/emperor.uwsgi.service; enabled; vendor preset: enabl Active: active (running) since Fri 2018-06-29 23:38:28 CEST; 8h ago Main PID: 227 (uwsgi) Status: "uWSGI is ready" CGroup: /system.slice/emperor.uwsgi.service └─227 /var/www/heating/env/bin/uwsgi --ini /var/www/heating/heating_uwsgi.ini Jun 29 23:38:25 heating2 systemd[1]: Starting uWSGI Emperor... Jun 29 23:38:25 heating2 uwsgi[227]: [uWSGI] getting INI configuration from /var/www/heatin Jun 29 23:38:28 heating2 systemd[1]: Started uWSGI Emperor. ~
and sudo nginx -t
Output:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
uwsgi error log shows
Output:
ImportError: No module named '__init__.py'; '__init__' is not a package unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode ***
I get the same message for every name I call it Wall
What I need to know is:
To create a flask app factory do I need the __init__.py file and how do I incorperate it here? Or is there another solution?
I am unable to advance until I solve this, I want to be able to use the module I created in my earlier thread
All help greatly appreciated, I hope I have given enough code.
Kind regards
Paul
Reply
#2
Check this link, maybe it could help you.
how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-14-04

I think you have to point to the module name in the heating_uwsgi.ini:
app = module_name # Heating?
Reply
#3
Hi gontajones
Thank you for your reply,
Quote:I think you have to point to the module name in the heating_uwsgi.ini:
Python Code: (Double-click to select all)
1 app = module_name # Heating?
I can make any app work except __init__.py which I understand to be an app factory? I made this "yummy cakes" work by entering the name of the file as
app = yummy_cakes
in the heating_uwsgi.ini and created a file called yummy_cakes.py
from flask import Flask
from flask import render_template
app = Flask(__name__)
app.debug = True
@app.route("/")
def index():
    return render_template('hello.html', message="Hello World!")
@app.route("/cakes")
def cakes():
    return "yummy cakes"
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080)
with some html templates in the templates directory and css in the static directory. but when i try the same with the __init__.py file by
app = __init__
I get the error messages. I dont understand yet what the __init__.py file does, i am working through the tutorial. But in the tutorial the _uwsgi.ini file is not mentioned. The Digital ocean tutorial is very much the same as the lab_app I followed including the .ini file and the flask app "myproject.py" which is named in the ini file.
Thank you for taking the time to look, it is great to see you again. I have been working on this for about 3 months and I am getting a bit frustrated, I hate asking for help!
Tommorrow is sunday so I will have a bit of time to look and research the __init__.py file.
Many thank
Kind regards
Paul
Reply
#4
From Modules:
Quote:The __init__.py files are required to make Python treat the directories as containing packages;

You need to specify the module name that you are using as a package.
Reply
#5
Hi gontajones
Thanks for your reply
Quote:You need to specify the module name that you are using as a package.
You are right, I need to create an app that is then the "index" of my web page I have found another good tutorial like the link you gave me here it is base on the flask tutorial but has additional information,
I decided rather than get bogged down in not what I cant do and try out both tutorials first and then see how they be inserted into the nginx web environement.
Many thanks
regards
Paul
Reply
#6
SOLVED
Hi, I have found the solution, I took a look at this tutorial and decided to follow the basic dossier set up of;
heating/
env/
app/
__init__.py
routes.py
heating.py
with __init__.py
from flask import Flask

app = Flask(__name__)

from app import routes
and routes.py
from app import app

@app.route('/')
@app.route('/index')
def index():
    return "Hello, World!"
and heating.py
from app import app
with no change to my origional nginx.conf, _uwsgi.ini and emperor.uwsgi.service, It all works, automatic restart on reboot.
I can now start coding the rest of my coding
heating.py is now
app = heating
regards Paul Big Grin
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to set up uwsgi and nginx? Stas43 2 1,156 Apr-21-2023, 10:51 AM
Last Post: Stas43
  Python flask uwsgi nginx docker mfaridi 2 1,769 Sep-14-2022, 11:07 AM
Last Post: mfaridi
  Multi-tier Web application File Storage (NginX, File System or FTP) ? draems 0 1,585 Apr-22-2019, 07:47 AM
Last Post: draems
  location settings for Django Uwsgi Nginx Configuration for production sandyman 0 2,930 Sep-15-2017, 09:08 AM
Last Post: sandyman

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020