【Flask】Hello Flask

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

在這裏插入圖片描述

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

在這裏插入圖片描述

路由視圖管理

懶加載實現路由視圖管理

1.目錄結構
在這裏插入圖片描述
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>'

在這裏插入圖片描述
3.啓動服務器

python manage.py runserver

4.瀏覽器訪問

訪問http://127.0.0.1:5000
在這裏插入圖片描述
訪問http://127.0.0.1:5000/student
在這裏插入圖片描述
訪問http://127.0.0.1:5000/teacher
在這裏插入圖片描述

flask-blueprint實現路由視圖管理

1.安裝擴展包

pip install flask-blueprint

2.目錄結構
在這裏插入圖片描述

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
在這裏插入圖片描述
訪問 http://127.0.0.1:5000/first_blue/student
在這裏插入圖片描述
訪問 http://127.0.0.1:5000/first_blue/teacher
在這裏插入圖片描述
訪問 http://127.0.0.1:5000/second_blue/student
在這裏插入圖片描述
訪問 http://127.0.0.1:5000/second_blue/teacher
在這裏插入圖片描述
訪問 http://127.0.0.1:5000/first_blue
在這裏插入圖片描述
訪問 http://127.0.0.1:5000/second_blue
在這裏插入圖片描述

完整項目結構

創建ORM的數據模型

1.安裝flask-flask-sqlalchemy擴展包

pip install flask-sqlalchemy

2.目錄結構
在這裏插入圖片描述
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
  • 數據被更新到數據庫中
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章