核心对象拆分出去
# 核心对象的设置和创建
import os
from flask import Flask
def create_app():
# 创建核心对象
mjh_app = Flask(__name__)
# 读取配置文件
# 方式一:从配置文件读取
# if isinstance(obj, str):
# obj = import_string(obj)
# for key in dir(obj):
# if key.isupper():
# self[key] = getattr(obj, key)
mjh_app.config.from_object('config.settings')
# 方式二:从环境变量读取
if 'FLASK_CONF' in os.environ:
mjh_app.config.from_envvar('FLASK_CONF')
# 运行到位
import router
# 将蓝图和app绑定
router.init_app(mjh_app)
return mjh_app
启动文件,程序入口
# 排查问题的两个大方向
# 1、新增文件有没有运行
# 2、有没有绑定到核心对象app上
from app import create_app
mjh_app = create_app()
from router import view01
mjh_app.run(host=mjh_app.config['HOST'],
port=mjh_app.config['PORT'],
debug=mjh_app.config['DEBUG'])
# 第二种方法:通过模块导入
# from config import settings
# mjh_app.run(host=settings.HOST,
# port=settings.PORT,
# debug=settings.DEBUG)
配置文件
DEBUG = True
HOST = '0.0.0.0'
PORT = 9000
管理视图
直接导入
from server2 import mjh_app
print("this is view")
@mjh_app.route("/")
def index():
return "this is index"
使用蓝图
__init__
from router.view01 import view01_bp
from router.register import register_bp
from router.login import login_bp
def init_app(app):
app.register_blueprint(view01_bp)
app.register_blueprint(register_bp)
app.register_blueprint(login_bp)
view01
from flask import Blueprint
# 创建蓝图对象
view01_bp = Blueprint("view01", __name__, url_prefix="/v1/")
@view01_bp.route("/index")
def index():
return "this is index"
注册用户
from flask import Blueprint, request
register_bp = Blueprint("register", __name__, url_prefix="/v1/")
user_dict = {}
@register_bp.route("/register")
def register():
username = request.json.get("username")
passwd = request.json.get("passwd")
re_pass = request.json.get("re_passwd")
if not (username and passwd and re_pass):
return "参数传递不完整"
if passwd != re_pass:
return "注册密码不一致!"
if username in user_dict:
return "用户已注册"
user_dict[username] = passwd
print(f"user_dict is {user_dict}")
return "register success!"
登录用户
from flask import Blueprint, request
user_dict = {'root':'123456'}
login_bp = Blueprint("login", __name__, url_prefix="/v1/")
@login_bp.route("/login")
def login():
user = request.json.get("username")
passwd = request.json.get("passwd")
local_user_passwd = user_dict.get(user)
if local_user_passwd and passwd == local_user_passwd:
return "login success!"
return "login fail!"