Flask实践Python Web

(python)python flask部署

2018-09-29  本文已影响41人  CENDEAL

flask+ubuntu+gunicorn+supervisor+nginx

1.安装python虚拟环境

pip install virtualenv
mkdir project
cd project
virtualenv venv
source venv/bin/activate

2.venv环境下安装flask

pip install flask

3.书写python程序测试环境

#myapp.py
from flask import Flask
app = Flak(__name__)
@app.route('/')
def index():
    return 'hello world'
if __name__=='__main__':
    app.debug = True
    app.run()

运行:python myapp.py

4.安装Gunicorn

pip install gunicorn

5.使用gunicorn 启用myapp.py

gunicorn -w4 -b0.0.0.0:8888 myapp:app
#-w 后面接worker数量
#-b 后面接ip及端口

6.安装Supervisor

#在非venv环境下运行,要求是python2
pip install supervisor

7.配置supervisor

#输出supervisor.conf
echo_supervisord_conf > supervisor.conf
#修改
vim supervisor.conf
#最后添加
[program:myapp]
command=/详细路径/venv/bingunicorn -w4 -b0.0.0.0:8888 myapp:app
autostart=false
autorestart=false
directory=/myproject路径/
stdout_logfile=/home/ubuntu/pythonweb/myproject/log/gunicorn.log
stderr_logfile=/路径/

8.supervisor指令

#启动supervisor
supervisord -c supervisor.conf
#控制
supervisorctl -c supervisor.conf

9.安装nignx

sudo apt-get install nginx

10.配置nginx

主要是默认的default中的server配置

11.nginx使用

#开启
sudo service nginx start
#重启
sudo service nginx restart
#重载
sudo service nginx reload
#停止
sudo service nginx stop

12.mysql的安装

#中途会有账号密码设置
sudo apt-get install mysql-server mysql-client

13.mysql的使用

mysql -u USER -p PASSWORD

14.安装pymysql驱动

#venv下
pip install pymyql

15.安装SQLAlchemy

pip install flask-sqlalchemy

16.使用SQLAlchemy+pymsql

#1.连接
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
app = Flask(__main__)
#2.配置
app.config['SQLALCHEMY_DATABSE_URI']='mysql+pymyslq//root:passord//localhost/databasename?charser=utf-8'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True
#3.实例化
db=SQLAlchemy(app)
#4.创建table
db.create_all()
#5.添加
db.session.add(..)
db.session.add_all([..])
#6.提交
db.session.commit()
#7.其他
db.drop_all()
db.delete(..)

17.关于config

#数据库
数据库URL:SQLALCHEMY_DATABASE_URI
数据库自动提交的变动:SQLALCHEMY_COMMIT_ON_TERADOWN
#邮件
邮件服务器:MAIL_SERVER
邮件端口:MAIL_PORT
是否使用安全协议:MAIL_USER_TLS
邮件密码:MAIL_USERNAME
邮件账户:MAIL_PASSWORD
邮件管理员: MAIL_AMIN

18.数据库的初始化问题

No application found. Either work inside a view function or push an application context

解决方法:

#1
from yourapp import create_app
app = create_app()
app.app_context().push()
db.create_all()
#2
from yourapp import create_app
app = create_app()
db.create_all(app=app)

19 jinja2语法,渲染值时不转义

{{值变量|safe}}
上一篇下一篇

猜你喜欢

热点阅读