def create_app(): app = Flask(__name__) app.config.from_object(config) db.init_app(app) with app.test_request_context(): db.create_all() return app
def setUp(self) -> None: self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() self.client = self.app.test_client()
def init_db(): with app.app_context(): # 需要用这句来加载app的上下文环境 # 测试前按以下配置重置数据库 db.drop_all() db.create_all() def add_items(): u1 = User(username='******', password='******', email='*****@*****.**') u2 = User(username='******', password='******', email='*****@*****.**') c1 = Club(club_name='yuanhuo', introduction="yuanhuo introduction", president_id=1) c2 = Club(club_name='feiying', introduction="feiying introduction", president_id=2) po1 = Post(title='one', text='jd is too strong', club_id=1) po2 = Post(title='two', text="let's compliment jd", club_id=1) po3 = Post(title='three', text="let's compliment j", club_id=2) po4 = Post(title='four', text="let's compliment j", club_id=2) u1.followed_clubs.append(c1) u2.managed_clubs.append(c1) db.session.add_all([u1, u2, po1, po2, po3, po4, c1, c2]) db.session.commit() add_items()
def initOrder(): db.create_all() orderInit() requestInit() db.session.commit() db.session.close()
def init(): db.create_all() userInit() farmInit() couponInit() productInit() db.session.commit() db.session.close()
def register_extensions(app: Flask) -> None: """Registering the extensions to the app object""" bootstrap.init_app(app) login.init_app(app) db.init_app(app) # Creating the database TODO this comment is dumb with app.app_context(): db.create_all()
def get_pager(): db.drop_all() db.create_all() for i in range(100): user = User(name='{}'.format(str(i)), password='******'.format(str(i))) db.session.add(user) db.session.commit() page = request.args.get('page', 1, type=int) pagination = User.query.paginate(page, 10) messages = pagination.items return render_template('get_pager.html', pagination=pagination, messages=messages)
def init_db_command(): '''Clear existing data and create new tables.''' db.drop_all() db.create_all() db.engine.execute("INSERT INTO pink (id, name, active) " f"VALUES ('{'0' * 9}', 'SYSTEM', False);") now = datetime.datetime.utcnow() txn_info = f'None_0_0_init_{"0" * 9}_{now}' id_ = sha3_256(txn_info.encode('utf-16')).hexdigest() db.engine.execute( "INSERT INTO txn (id, previous_id, debit, credit, reason, pink_id, timestamp) " f"VALUES ('{id_}', '{id_}', 0, 0, 'init', '{'0' * 9}', '{now.isoformat()}');" ) click.echo('\nDatabase Initialized')
def init_db(app): # 生成数据库表 db.create_all() app.logger.debug('创建表') if Role.query.first(): return role_admin = Role(role_name="管理员", role_desc="系统管理员") role_audit = Role(role_name="审计员", role_desc="审计员") role_ordinary = Role(role_name="普通用户", role_desc="普通管理员") db.session.add_all([role_admin, role_audit, role_ordinary]) db.session.commit() app.logger.debug('初始化角色成功') admin = User(user_name="admin", role_id=1, create_time=TimeManager.now(), status=1, last_passwd_change_time=TimeManager.now()) admin.pwd = 'admin' db.session.add(admin) db.session.commit() app.logger.debug('初始化用户成功')
def create_db(): db.create_all()
from flask_migrate import MigrateCommand, Migrate from flask_script import Manager, Server from models import User, Questions from Demo import app from exts import db manager = Manager(app) migrate = Migrate(app, db) manager.add_command("server", Server()) manager.add_command("db", MigrateCommand) """ 需要将建立的所有的数据库模型都在dict里面声明,这样就可以在manager 的 shell 指令行来进行数据库表的创建了 python manage.py shell db.create_all() """ @manager.shell def make_shell_context(): return dict(app=app, db=db, User=User, Questions=Questions) @manager.command def createdb(): db.create_all() return '创建数据库成功' if __name__ == '__main__': manager.run()
# -- coding:utf-8 -- from flask import Flask, render_template, request, redirect, url_for, session import config from models import table_shouye from exts import db app = Flask(__name__) app.config.from_object(config) db.init_app(app) # 初始化db,并创建models中定义的表格 with app.app_context(): # 添加这一句,否则会报数据库找不到application和context错误 db.init_app(app) # 初始化db db.create_all() # 创建所有未创建的table #print(table_shouye.query.all()) # 首页函数 @app.route('/') def index(): context = table_shouye.query.all() return 'hello' + str(context[0]) if __name__ == '__main__': app.run()
from flask import Flask, url_for, redirect, render_template import config from exts import db from models import User, Book, BookType from config import * app = Flask(__name__) app.config.from_object(config) index = config.API_VERSION + "/index/" db.init_app(app) # 待app初始化完成(这块不太懂) with app.app_context(): db.create_all() @app.route(index) def index(): return 'index' @app.route('/') def hello(): # user = User.query.filter(User.username == 'jianyan').first() # print(user) # print(user.username) # print(user.password) # book_type = BookType.query.filter(BookType.id == 1).first()
def create(): """重置所有数据表""" from model.models import BostonHousingDataSet, Predict db.drop_all() db.create_all() return {'message': 'successful'}
def create_tables(): db.create_all()
def test_init(self): with app.app_context(): # 需要用这句来加载app的上下文环境 # 按以下配置重置数据库 db.drop_all() db.create_all() add_items()
def test_init(self): with app.app_context(): db.drop_all() db.create_all() add_items()
def createdb(): db.create_all() return "creatdb success"
def restartDB(): db.create_all() print('DB created.')
def setup(): # Recreate database each time for demo db.create_all()
def index(): db.create_all() # 创建数据库 # 第一次运行可以开启一下demo字段,下次运行可以关闭,防止字段混乱 goods1 = Goods(title='雪碧', price='3.0', num=250, type='饮料', produce_date='2018-9-25', guarantee_time=330, provider_id=2) goods2 = Goods(title='可乐', price='3.0', num=200, type='饮料', produce_date='2018-9-26', guarantee_time=300, provider_id=2) goods3 = Goods(title='牛奶', price='3.5', num=180, type='饮料', produce_date='2018-9-28', guarantee_time=45, provider_id=2) goods4 = Goods(title='泡面', price='4.0', num=150, type='食品', produce_date='2018-10-8', guarantee_time=180, provider_id=1) goods5 = Goods(title='火腿肠', price='1.5', num=320, type='食品', produce_date='2018-10-10', guarantee_time=150, provider_id=1) goods6 = Goods(title='果汁', price='4.0', num=300, type='饮料', produce_date='2018-10-9', guarantee_time=200, provider_id=1) goods7 = Goods(title='薯片', price='3.5', num=250, type='零食', produce_date='2018-8-20', guarantee_time=250, provider_id=3) goods8 = Goods(title='饼干', price='2.5', num=235, type='零食', produce_date='2018-8-22', guarantee_time=240, provider_id=3) company1 = Provider(provider='食品公司', provide_time='2018-10-15') company2 = Provider(provider='饮料公司', provide_time='2018-10-3') company3 = Provider(provider='零食公司', provide_time='2018-10-21') db.session.add_all( [goods1, goods2, goods3, goods4, goods5, goods6, goods7, goods8]) db.session.add_all([company1, company2, company3]) # 如果需要在代码中创建用户则手动添加代码 # db.session.drop(); 删除全部数据库 db.session.commit() username = session.get("username", "请先登录") return render_template('index.html', username=username)
from flask import Flask import config from models import Article # 这是必须要引用的 from exts import db app = Flask(__name__) app.config.from_object(config) # db = SQLAlchemy(app) # 这是原来的写法,现在是从exts.py文件中导入db db.init_app(app) # 在此初始化数据库 # class Article(db.Model): # 当模型很复杂时,文件会凌乱 # __tablename__ = 'article' # id = db.Column(db.Integer, primary_key=True, autoincrement=True) # title = db.Column(db.String(100), nullable=False) db.create_all(bind='__all__', app=app) # 将此app绑定到服务器app栈顶上 @app.route('/') def hello_world(): articel1 = Article(title='zzzz') db.session.add(articel1) db.session.commit() return 'Hello World!' if __name__ == '__main__': app.run()
def init(): db.drop_all() db.create_all() return 'init success'
def addModel(): db.create_all()
def init_db(): print('>>>>>>>>creating DB...') db.create_all()
def createdb(): db.create_all() return '创建数据库成功'
from flask import Flask, make_response, request from flask_cors import CORS from exts import db from models import Student import config import json app = Flask(__name__) app.config.from_object(config) db.init_app(app) # 处理跨域 CORS(app, resources=r'/*') db.create_all(app=app) @app.route('/') def hello_world(): return 'Hello World!' @app.route('/post', methods=['POST']) def post(): # 获取 参数 name = request.json.get('name') email = request.json.get('email') # 返回结果集 json_list = [] student_data = {} # 查询 符合条件的数据
def init_db(): print('>>>>>>>>creating DB...') db.create_all() print('create successful')
__author__ = 'XeanYu' from flask import Flask from conf import db_config from exts import db from models import Users from main import main from exts import login_manager login_manager.session_protection = 'strong' login_manager.login_view = 'main.sgin_in' # 定义验证登录页面 app = Flask(__name__) app.config.from_object(db_config) login_manager.init_app(app) # 传入app到login_manager进行初始化 db.init_app(app) # 初始化数据库 with app.app_context(): db.create_all() # 将 main 蓝本注册到 app 中 app.register_blueprint(main) if __name__ == '__main__': app.run(debug=True,host='0.0.0.0',port=8080)
def restartDB(): db.drop_all() db.create_all() print('DB restarted.')