Difference between revisions of "Flask"

From wiki
Jump to navigation Jump to search
Line 37: Line 37:
 
Mayor part is from this site [https://vladikk.com/2013/09/12/serving-flask-with-nginx-on-ubuntu/].
 
Mayor part is from this site [https://vladikk.com/2013/09/12/serving-flask-with-nginx-on-ubuntu/].
  
* Install [[uwsgi]] it's python plugin.
+
* Install [[uwsgi]].
  
 
* Create a virtual webserver (port 80 is save enough if you have a secure front-end server)
 
* Create a virtual webserver (port 80 is save enough if you have a secure front-end server)
Line 58: Line 58:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
=Generate web pages=
+
===Super simple app===
https://flask.palletsprojects.com/en/1.1.x/patterns/templateinheritance/#template-inheritance
+
In /var/www/flask/app1/app1.py
 
 
 
 
[https://www.idkrtm.com/creating-a-webpage-using-python-and-flask/ Source for this basic app]
 
 
 
Put a index.html in <app-base>/templates/
 
 
 
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
 
#!/usr/bin/env python3
 
#!/usr/bin/env python3
  
from flask import Flask, render_template
+
from flask import Flask
 +
import os
  
print(__name__)
+
application = Flask(__name__)
app = Flask(__name__)
 
  
@app.route('/html')
+
@application.route('/app1')
def static_page():
+
def app1():
  return render_template('index.html')
+
    return "App 1 live and kicking"
  
 
if __name__ == '__main__':
 
if __name__ == '__main__':
     app.run(host='0.0.0.0',port=5000,debug=True)
+
     application.run(host='0.0.0.0', port=8080,debug=True)
 +
</syntaxhighlight>
  
</syntaxhighlight>
+
That's it. Point your webbrowser to http://<your webserver fdqn>/app1</code> and it will show you: "App 1 live and kicking"
  
 
=Microservices and/or more applications on 1 web-server=  
 
=Microservices and/or more applications on 1 web-server=  
 +
You can make any number of application by adding more apps to [[uwsgi]] and a location in [[nginx]] for each of them. However with only 1 app you can run all python scripts you want.
  
Starting with [https://jawher.me/multiple-python-apps-with-nginx-uwsgi-emperor-upstart/ this page] and additional a lot more we got it working on [https://www.raspberrypi.org/software/ raspberry pi debian].
 
 
# Make python3 the default<br><code>cd /usr/bin;rm python;ln -s python3 python</code>
 
# Install uwsgi and python plugin<br><code>apt install uwsgi uwsgi-plugin-python3</code>
 
# install nginx<br><code>apt install nginx-full</code>
 
I had to make a small change in the nginx configuration;<br>
 
<code>vi /etc/nginx/conf.d/my.conf<br>
 
server_names_hash_bucket_size 64;
 
</code>
 
 
===Super simple app===
 
In /var/www/flask/app1/app1.py
 
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
 
#!/usr/bin/env python3
 
#!/usr/bin/env python3
  
from flask import Flask
+
from flask import Flask, render_template
 
import os
 
import os
 +
import subprocess
  
 +
### Application whitelist
 +
whitelist = {
 +
    'script as in URL' :'<scriptlocation>',
 +
    'script as in URL' :'<another scriptlocation>',
 +
    }
 +
   
 
application = Flask(__name__)
 
application = Flask(__name__)
  
@application.route('/app1')
+
@application.route('/app1/<script>/<path:arguments>')
def app1():
+
def func1(script,arguments):
     return "App 1 live and kicking"
+
    if script in whitelist:
 +
        arglist = arguments.split('/')
 +
        result = subprocess.run([whitelist[script]]+arglist, stdout=subprocess.PIPE)
 +
        output = result.stdout
 +
    else:
 +
        output = '{} does not exist in whitelist'.format(script)
 +
    return output
 +
   
 +
@application.route('/app1/<script>')
 +
def func2(script):
 +
    if script in whitelist:
 +
        result = subprocess.run([whitelist[script]], stdout=subprocess.PIPE)
 +
        output = result.stdout
 +
    else:
 +
        output = '{} does not exist in whitelist'.format(script)
 +
     return output
  
 
if __name__ == '__main__':
 
if __name__ == '__main__':
Line 113: Line 119:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Pointing your browser at <code><webserver>:/app1</code> will now show you: "App 1 live and kicking"
+
The route is the request URI as passed by the webserver. In this case 'app1' is the location. The things in <> are converted to python variables. <path:arguments> will put everything, including the '/'-es into 1 variable (arguments). So you can have a variable number of arguments that all will be passed to the pythonscript called by subprocess.
 +
 
 +
The whitelist is there for security to avoid one can run any script is knows the location for.
  
===Create a nginx virtual host===
+
=Generate web pages=
 +
https://flask.palletsprojects.com/en/1.1.x/patterns/templateinheritance/#template-inheritance
  
/etc/nginx/sites-enabled/apps.conf
 
  
<syntaxhighlight lang=nginx>
+
[https://www.idkrtm.com/creating-a-webpage-using-python-and-flask/ Source for this basic app]
server {
+
 
  listen 80;
+
Put a index.html in <app-base>/templates/
  server_name <your webserver fdqn>;
 
  index index.html;
 
  
  root /var/www/flask;
+
<syntaxhighlight lang=python>
 +
#!/usr/bin/env python3
  
  location /app1 {
+
from flask import Flask, render_template
    include uwsgi_params;
 
    uwsgi_param SCRIPT_NAME /app1;
 
    uwsgi_modifier1 30;
 
    uwsgi_pass unix://tmp/app1.sock;
 
  }
 
  
  location /app2 {
+
print(__name__)
    include uwsgi_params;
+
app = Flask(__name__)
    uwsgi_param SCRIPT_NAME /app2;
 
    uwsgi_modifier1 30;
 
    uwsgi_pass unix://tmp/app2.sock;
 
  }
 
}
 
</syntaxhighlight>
 
  
===Start things===
+
@app.route('/html')
<syntaxhighlight lang=bash>
+
def static_page():
service uwsgi start
+
  return render_template('index.html')
service nginx start
 
</syntaxhighlight>
 
  
That's it. Point your webbrowser to http://<your webserver fdqn>/app1
+
if __name__ == '__main__':
 +
    app.run(host='0.0.0.0',port=5000,debug=True)
  
Optimization still to be done. I think I start on [https://www.techatbloomberg.com/blog/configuring-uwsgi-production-deployment/ this place]
+
</syntaxhighlight>

Revision as of 17:43, 19 July 2021

Basics

Check this[1]

Hello world app:

#!/usr/bin/env python3

from flask import Flask
print(__name__)
app = Flask(__name__)

@app.route('/')

def welcome():
    return 'Welcome'

if __name__ == '__main__':         # When executed on the commandline (build in webserver)
    app.run(host='0.0.0.0',port=5000) # Listen to localhost port 5000, you can also use flask run for options
    #app.run(host='0.0.0.0',port=8080,Debug=True)  # Run in debug mode, listen to all hosts on port 8080

Run the build-in server listening to all

export FLASK_APP=welcome_app.py 
flask run --host=0.0.0.0
welcome_app
 * Serving Flask app "welcome_app"
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

Now you can browse to <serverIP>:5000

https://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-python-flask-and-mysql--cms-22972

Integrate with nginx

Mayor part is from this site [2].

  • Create a virtual webserver (port 80 is save enough if you have a secure front-end server)
server {
    listen 80 ;
    listen [::]:80;

    root /var/www/flask;
    server_name <fqdn>;

    location /app1 {
        include uwsgi_params;
        uwsgi_param SCRIPT_NAME /app1;
        uwsgi_modifier1 30;
        uwsgi_pass unix://tmp/app1.sock;
    }
}

Super simple app

In /var/www/flask/app1/app1.py

#!/usr/bin/env python3

from flask import Flask
import os

application = Flask(__name__)

@application.route('/app1')
def app1():
    return "App 1 live and kicking"

if __name__ == '__main__':
    application.run(host='0.0.0.0', port=8080,debug=True)

That's it. Point your webbrowser to http://<your webserver fdqn>/app1 and it will show you: "App 1 live and kicking"

Microservices and/or more applications on 1 web-server

You can make any number of application by adding more apps to uwsgi and a location in nginx for each of them. However with only 1 app you can run all python scripts you want.

#!/usr/bin/env python3

from flask import Flask, render_template
import os
import subprocess 

### Application whitelist
whitelist = {
    'script as in URL' :'<scriptlocation>',
    'script as in URL' :'<another scriptlocation>',
    }
    
application = Flask(__name__)

@application.route('/app1/<script>/<path:arguments>')
def func1(script,arguments):
    if script in whitelist:
        arglist = arguments.split('/')
        result = subprocess.run([whitelist[script]]+arglist, stdout=subprocess.PIPE)
        output = result.stdout
    else:
        output = '{} does not exist in whitelist'.format(script)
    return output
    
@application.route('/app1/<script>')
def func2(script):
    if script in whitelist:
        result = subprocess.run([whitelist[script]], stdout=subprocess.PIPE)
        output = result.stdout
    else:
        output = '{} does not exist in whitelist'.format(script)
    return output

if __name__ == '__main__':
    application.run(host='0.0.0.0', port=8080,debug=True)

The route is the request URI as passed by the webserver. In this case 'app1' is the location. The things in <> are converted to python variables. <path:arguments> will put everything, including the '/'-es into 1 variable (arguments). So you can have a variable number of arguments that all will be passed to the pythonscript called by subprocess.

The whitelist is there for security to avoid one can run any script is knows the location for.

Generate web pages

https://flask.palletsprojects.com/en/1.1.x/patterns/templateinheritance/#template-inheritance


Source for this basic app

Put a index.html in <app-base>/templates/

#!/usr/bin/env python3

from flask import Flask, render_template

print(__name__)
app = Flask(__name__)

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

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=5000,debug=True)