Flask框架服务器部署流程

Flask框架搭建web服务器

1.安装flask框架

pip install flask

2.编写hello.py文件

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
    return '<h1>Hello Flask!</h1>'

if __name__ == '__main__':
    app.run(host='0.0.0.0',port='8080',debug=True,load_dotenv=True)
    
# host:主机号                Type:str,默认为127.0.0.1
# port:端口号                Type:str/int,默认为5000
# debug:调试模式             Type:bool,默认为True:True为开启调试模式,False为关闭调试模式
# load_dotenv:加载到环境变量  Type:bool,默认为True:True为加载后缀为".env"或".flaskenv"的文件到环境变量中,False为不加载

3.执行hello.py文件

python3 hello.py

4.浏览器访问127.0.0.1:8080

python flask用什么服务器 flask服务器部署 hello_mysql

flask-script实现服务器部署

1.安装扩展包

pip install flask-script

2.编写hello.py文件

from flask import Flask
from flask_script import Manager

app = Flask(__name__)
manage = Manager(app=app)
@app.route('/')
def hello_world():
    return '<h1>Hello Flask!</h1>'

if __name__ == '__main__':
    manage.run()

3.执行hello.py文件

python hello.py runserver -h 0.0.0.0 -p 8080 -d -r --threaded

python xxx.py runserver 选项参数

optional arguments:
  -?, --help            show this help message and exit
  -h HOST, --host HOST
  -p PORT, --port PORT
  --threaded
  --processes PROCESSES
  --passthrough-errors
  -d, --debug           enable the Werkzeug debugger (DO NOT use in production
                        code)
  -D, --no-debug        disable the Werkzeug debugger
  -r, --reload          monitor Python files for changes (not 100% safe for
                        production use)
  -R, --no-reload       do not monitor Python files for changes
  --ssl-crt SSL_CRT     Path to ssl certificate
  --ssl-key SSL_KEY     Path to ssl key

4.访问127.0.0.1:8080

python flask用什么服务器 flask服务器部署 hello_App_02

路由视图管理

懒加载实现路由视图管理

1.目录结构

python flask用什么服务器 flask服务器部署 hello_mysql_03


2.代码文件

# manage.py
from flask_script import Manager
from App import create_app
app = create_app()
manager = Manager(app=app)

if __name__ == '__main__':
    manager.run()
# __init__.py
from flask import Flask
from App.view import init_app

def create_app():
    app = Flask(__name__)
    init_app(app)
    return app
# view.py
def init_app(app):
    @app.route('/')
    def index():
        return '<h1>Hello Flask!</h1>' \
               '<a href="http://127.0.0.1:5000/student">学生主页</a>' \
               '<a href="http://127.0.0.1:5000/teacher">教师主页</a>'

    @app.route('/student')
    def student_index():
        return '<h1>this is the index of student!</h1>' \
               '<a href="http://127.0.0.1:5000">主页</a>'

    @app.route('/teacher')
    def teacher_index():
        return '<h1>this is the index of teacher!</h1>' \
               '<a href="http://127.0.0.1:5000">主页</a>'

python flask用什么服务器 flask服务器部署 hello_flask_04


3.启动服务器

python manage.py runserver

4.浏览器访问

访问http://127.0.0.1:5000

python flask用什么服务器 flask服务器部署 hello_python flask用什么服务器_05


访问http://127.0.0.1:5000/student

python flask用什么服务器 flask服务器部署 hello_App_06


访问http://127.0.0.1:5000/teacher

python flask用什么服务器 flask服务器部署 hello_flask_07

flask-blueprint实现路由视图管理

1.安装扩展包

pip install flask-blueprint

2.目录结构

python flask用什么服务器 flask服务器部署 hello_flask_08

3.代码文件

# manage.py
from flask_script import Manager
from App import create_app
app = create_app()
manager = Manager(app=app)

if __name__ == '__main__':
    manager.run()
# App/__init__.py
from flask import Flask
from App.view.first_blue import first_blue
from .view import init_view

def create_app():
    app = Flask(__name__)
    init_view(app)
    return app
# view/__init__.py
from .first_blue import first_blue
from .second_blue import second_blue
from .blue import blue
def init_view(app):
    app.register_blueprint(first_blue)
    app.register_blueprint(second_blue)
    app.register_blueprint(blue)
# first_blue.py
from flask import Blueprint
first_blue = Blueprint('first_blue',__name__)

@first_blue.route('/first_blue')
def first_blue_index():
    return '<h1>(first_blue)Hello Flask!</h1>' \
           '<a href="http://127.0.0.1:5000/first_blue/student">学生主页</a><br>' \
           '<a href="http://127.0.0.1:5000/first_blue/teacher">教师主页</a>'

@first_blue.route('/first_blue/student')
def student_index():
    return '<h1>(first_blue)This is the index of student!</h1>' \
           '<a href="http://127.0.0.1:5000/first_blue">first_blue 主页</a>'

@first_blue.route('/first_blue/teacher')
def teacher_index():
    return '<h1>(first_blue)This is the index of teacher!</h1>' \
           '<a href="http://127.0.0.1:5000/first_blue">first_blue 主页</a>'
# second_blue.py
from flask import Blueprint
second_blue = Blueprint('second_blue',__name__)

@second_blue.route('/second_blue')
def second_blue_index():
    return '<h1>(second_blue)Hello Flask!</h1>' \
           '<a href="http://127.0.0.1:5000/second_blue/student">学生主页</a><br>' \
           '<a href="http://127.0.0.1:5000/second_blue/teacher">教师主页</a>'

@second_blue.route('/second_blue/student')
def student_index():
    return '<h1>(second_blue)This is the index of student!</h1>' \
           '<a href="http://127.0.0.1:5000/second_blue">second_blue 主页</a>'

@second_blue.route('/second_blue/teacher')
def teacher_index():
    return '<h1>(second_blue)This is the index of teacher!</h1>' \
           '<a href="http://127.0.0.1:5000/second_blue">second_blue 主页</a>'
# blue.py
from flask import Blueprint
blue = Blueprint('blue',__name__)

@blue.route('/')
def blue_index():
    return '<a href="http://127.0.0.1:5000/first_blue/student">学生主页(first_blue)</a><br>' \
           '<a href="http://127.0.0.1:5000/first_blue/teacher">教师主页(first_blue)</a><br><br>' \
           '<a href="http://127.0.0.1:5000/second_blue/student">学生主页(second_blue)</a><br>' \
           '<a href="http://127.0.0.1:5000/second_blue/teacher">教师主页(second_blue)</a><br>'

4.启动服务器

python manage.py runserver

5.浏览器访问

访问 http://127.0.0.1:5000

python flask用什么服务器 flask服务器部署 hello_App_09


访问 http://127.0.0.1:5000/first_blue/student

python flask用什么服务器 flask服务器部署 hello_App_10


访问 http://127.0.0.1:5000/first_blue/teacher

python flask用什么服务器 flask服务器部署 hello_flask_11


访问 http://127.0.0.1:5000/second_blue/student

python flask用什么服务器 flask服务器部署 hello_App_12


访问 http://127.0.0.1:5000/second_blue/teacher

python flask用什么服务器 flask服务器部署 hello_python flask用什么服务器_13


访问 http://127.0.0.1:5000/first_blue

python flask用什么服务器 flask服务器部署 hello_App_14


访问 http://127.0.0.1:5000/second_blue

python flask用什么服务器 flask服务器部署 hello_mysql_15

完整项目结构

创建ORM的数据模型

1.安装flask-flask-sqlalchemy扩展包

pip install flask-sqlalchemy

2.目录结构

python flask用什么服务器 flask服务器部署 hello_python flask用什么服务器_16


3.代码文件

# manage.py
from flask_script import Manager
from flask_migrate import MigrateCommand
from App import create_app
import os

env = os.environ.get('FLASK_ENV','develop')

app = create_app(env)
manager = Manager(app=app)
manager.add_command('db',MigrateCommand)


if __name__ == '__main__':
    manager.run()
# App/__init__.py
from flask import Flask
from App.views import init_view
from App.extension import init_extension
from App.settings import envs

def create_app(env):
    app = Flask(__name__)
    app.config.from_object(envs.get(env))
    # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sqlite.db'
    # app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    init_extension(app)
    init_view(app)
    return app
# settings.py
import os
BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__name__)))


def get_db_uri(database_info):
    engine   = database_info.get('ENGINE')   or 'sqlite'
    driver   = database_info.get('DRIVER')   or 'sqlite'
    user     = database_info.get('USER')     or ''
    password = database_info.get('PASSWORD') or ''
    host     = database_info.get('HOST')     or ''
    port     = database_info.get('PORT')     or ''
    db       = database_info.get('DB')       or ''

    return  '{}+{}://{}:{}@{}:{}/{}'.format(engine, driver, user, password, host, port, db)

class Config:
    DEBUG = False
    TESTING = False
    SQLALCHEMY_TRACK_MODIFICATIONS = False


class DevelopConfig(Config):
    """
    开发环境
    """
    DEBUG =  True
    DB_INFO = {
        'ENGINE'  :'mysql',
        'DRIVER'  :'pymysql',
        'USER'    :'root',
        'PASSWORD':'123456789',
        'HOST'    :'49.235.112.165',
        'PORT'    :'3306',
        'DB'      :'db1'
    }
    SQLALCHEMY_DATABASE_URI = get_db_uri(DB_INFO)

class TestConfig(Config):
    """
    测试环境
    """
    TESTING =  True
    DB_INFO = {
        'ENGINE'  :'mysql',
        'DRIVER'  :'pymysql',
        'USER'    :'root',
        'PASSWORD':'qwe123',
        'HOST'    :'localhost',
        'PORT'    :'3306',
        'DB'      :'db1'
    }
    SQLALCHEMY_DATABASE_URI = get_db_uri(DB_INFO)


class StagingConfig(Config):
    """
    模拟环境
    """
    DB_INFO = {
        'ENGINE'  :'mysql',
        'DRIVER'  :'pymysql',
        'USER'    :'root',
        'PASSWORD':'qwe123',
        'HOST'    :'localhost',
        'PORT'    :'3306',
        'DB'      :'db1'
    }
    SQLALCHEMY_DATABASE_URI = get_db_uri(DB_INFO)

class ProductConfig(Config):
    """
    生产环境
    """
    DB_INFO = {
        'ENGINE'  :'mysql',
        'DRIVER'  :'pymysql',
        'USER'    :'root',
        'PASSWORD':'qwe123',
        'HOST'    :'localhost',
        'PORT'    :'3306',
        'DB'      :'db1'
    }
    SQLALCHEMY_DATABASE_URI = get_db_uri(DB_INFO)

envs = {
        'develop':DevelopConfig,
        'testing':TestConfig,
        'staging':StagingConfig,
        'product':ProductConfig,
        'default':DevelopConfig
        }
# extensions.py
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
models = SQLAlchemy()
migrate = Migrate()

def init_extension(app):
    models.init_app(app)
    migrate.init_app(app,models)
# views/__init__.py
from .blue import blue
def init_view(app):
    app.register_blueprint(blue)
# blue.py
from flask import Blueprint,render_template
from App.models import models
from App.models import User
import time

blue = Blueprint('blue',__name__)
@blue.route('/index.html')
def index():
    service_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    return render_template('index.html',service_time=service_time)

@blue.route('/create_tb')
def create_db():
    models.create_all()
    return '<h1>数据库表创建成功!</h1>'

@blue.route('/drop_tb')
def drop_db():
    models.drop_all()
    return '<h1>数据库表删除成功!</h1>'

@blue.route('/add_user')
def add_user():
    user = User()
    user.name = 'Tom'
    user.save()
    return '用户添加成功!'
# index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>系统信息</h1><br>
当前服务器时间:{{ service_time }}
</body>
</html>
# models.py
from App.extension import models
class User(models.Model):
    id   = models.Column(models.INTEGER,primary_key=True)
    name = models.Column(models.String(16))
    sex  = models.Column(models.String(2))
    age  = models.Column(models.INTEGER)

    def save(self):
        models.session.add(self)
        models.session.commit()

flask-migrate实现数据模型迁移

1.安装flask-migrate扩展包

pip install flask-migrate

2.项目中第一次使用时初始化migrate

python manage.py db init
  • 初始化后会自动生成migrations文件夹

3.数据模型迁移

python manage.py db migrate
  • 生成迁移的py文件

4.将数据模型更新到数据库

python manage.py db upgrade
  • 数据被更新到数据库中