赞
踩
Flask本身是一个轻量级的框架,所以使用很方便,我们要学习的是flask蓝图,组建企业级项目。
但是如果需求很小,使用flask开发,完全没有必要遵照蓝图模式,搭建一堆文件。
- import os
-
- # basedir = os.path.dirname(__file__)
- # print(basedir)
-
-
- class Config:
- DEBUG = False
- SQLALCHEMY_DATABASE_URI = "sqlite:code/flask/CompanyProject/app/flask.db"
- SQLALCHEMY_TRACK_MODIFICATIONS = True
- SECRET_KEY = os.environ.get("SECRET_KEY") or 'hard to guess string'
- @staticmethod
- def init_app(app):
- pass
-
- class Test(Config):
- DEBUG = True
- SQLALCHEMY_DATABASE_URI = "sqlite:code/flask/CompanyProject/app/test.db"
-
- class Run(Config):
- pass
-
- config={
- "test":Test,
- "run":Run
- }
-
- from flask import Flask, render_template
- from flask_sqlalchemy import SQLAlchemy
- from config import config
-
- db = SQLAlchemy()
-
-
- def create_app(config_name):
- app = Flask(__name__)
- app.config.from_object(config[config_name])
- config[config_name].init_app(app)
-
- db.init_app(app)
-
- from .main import main as main_blueprint
-
- app.register_blueprint(main_blueprint)
-
- return app
- from flask import Blueprint
-
- main = Blueprint("main", __name__)
- from . import views, errors
- from . import main
-
-
- @main.route("/")
- def index():
- return "hello world"
-
- import os
- from app import create_app, db
- from app.models import *
- from flask_script import Manager, Shell
- from flask_migrate import MigrateCommand, Migrate
-
- # os.getenv 获取环境变量,获取不到返回None
- app = create_app(os.getenv("FLASK_CONFIG") or "test")
-
- manager = Manager(app)
- migrate = Migrate(app, db)
-
-
- def make_shell_context():
- return dict(app=app, db=db, User=User, Type=Type)
-
-
- def create_db():
- db.create_all()
- print("create success")
-
-
- manager.add_command("shell", Shell(make_context=make_shell_context()))
- manager.add_command("db", MigrateCommand)
-
- if __name__ == '__main__':
- manager.run()
启动命令行,切换到当前项目所在的目录,并且激活环境
1、python manage.py runserver 启动服务
2、Python manage.py db init 实例化数据库
3、Python manage.py db migrate -m "initial migration" 生成数据库语句
4、Python manage.py db upgrade 同步数据库
5、Python manage.py shell 交互命令
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。