python-flask-2 安装及设定 flask
https://linoxide.com/linux-how-to/install-flask-python-ubuntu/
1. prerequisites
> create a new user: sudo adduser bob
> grant admin privileges: sudo usermode -aG sudo bob
2. install components from the ubuntu repositories
sudo apt-get update
sudo apt-get install python3-pip python3-dev nginx
3. create python3 virtual environment
sudo pip3 install virtualenv
> generate a project folder
> then: mkvirtualenv flask
4. install flask
> activate flask
> pip3 install gunicorn flask
5. create a sample app: flaskproject.py
~/flaskproject/flaskproject.py
##########
from flask import Flask
app = Flask(__name__)
@app.route("/")
def greeting():
return "<h1 style='color:green'>Hello World!</h1>"
if __name__ == "__main__":
app.run(host='0.0.0.0')
#############
6. open server
(flaskprojectenv) $ sudo ufw allow 5000
(flaskprojectenv) $ python flaskproject.py
http://0.0.0.0:5000
then you can get a "Hello world" on the browser
7. create the wsgi entry point:create wsgi.py
~/flaskproject/wsgi.py from flaskproject import app if __name__ == "__main__": app.run()
8. check gunicorn works or not:
(in the flaskproject folder) > gunicorn --bind 0.0.0.0:5000 wsgi:app
9. create a systemd unit file: allow unbuntu automatically start Gunicorn and serve the Flask application whenever the server boots
create a unit file ending in .service in /etc/systemd/system folder
> sudo vim /etc/systemd/system/flaskproject.service
###
[Unit]
Description=Gunicorn instance to serve flaskproject
After=network.target
[Service]
User=westmole
Group=www-data
WorkingDirectory=/home/westmole/workspace/prj/flaskproject
Environment="PATH=/home/westmole/workspace/prj/flaskproject/flask/bin"
ExecStart=/home/westmole/workspace/prj/flaskproject/flask/bin/gunicorn --workers 3 --bind unix:flaskproject.sock -m 007 wsgi:app
[Install]
WantedBy=multi-user.target
###
> group=www-data: Nginx can communicate with Gunicorn processes
> gunicorn is in the virtualenv of flask
> --workers 3: 3 worker projcesses
> -m 007: umask value so the socket file to give access to the owner and group
> wsgi:app : pass in the WSGI entry point
10. start the gunicorn service and enable it to start at boot:
> sudo systemctl start flaskproject
> sudo systemctl enable flaskproject
11. configuring Nginx to proxy request
Nginx to pass web requests to scoket; create a new server block configuration file in Nginx's 'sites-available' directory
> sudo vim /etc/nginx/sites-available/flaskproject
server { listen 80; server_name server_domain_or_IP; location / { include proxy_params; proxy_pass http://unix:/home/bobby/flaskproject/flaskproject.sock; } }
> sudo ln -s /etc/nginx/sites-available/flaskproject /etc/nginx/sites-enabled
> sudo nginx -t
> sudo systemctl restart nginx
> sudo ufw delete allow 5000
> sudo ufw allow 'Nginx Full'