概述
项目目录结构如下:
Flask-SQLAlchemy
sansa
views
account.py
__init__.py
models.py
create_table.py
run.py
settings.py
代码如下:
settings.py
class BaseConfig(object):
SQLALCHEMY_DATABASE_URI = "mssql+pyodbc://sa:Nuctech_50@dsn_name"
SQLALCHEMY_POOL_SIZE = 5
SQLALCHEMY_POOL_TIMEOUT = 30
SQLALCHEMY_POOL_RECYCLE = -1
#追踪对象的修改并且发送信号
SQLALCHEMY_TRACK_MODIFICATIONS = False
class ProductionConfig(BaseConfig):
pass
class DevelopmentConfig(BaseConfig):
pass
class TestingConfig(BaseConfig):
pass
run.py
from sansa import create_app
app = create_app()
if __name__ == '__main__':
app.run()
create_table.py
from sansa import create_app
from sansa import db
app = create_app()
with app.app_context():
db.create_all()
sansa/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from .models import *#需要导入,且放在db下面,因为models文件中需要引入db,from . import db
from .views import account
def create_app():
app = Flask(__name__)
app.config.from_object('settings.DevelopmentConfig')
#将db注册到app中
db.init_app(app)
#注册蓝图
app.register_blueprint(account.account)
return app
sansa/models.py
from . import db
class Users(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(80),unique=True,nullable=False)
email = db.Column(db.String(120),unique=True,nullable=False)
def __repr__(self):
return '<User %r>'%self.username
sansa/views/account.py
from flask import Blueprint
from .. import db
from .. import models
account = Blueprint('account',__name__)
@account.route("/login")
def login():
# db.session.add(models.Users(username='alex',email="alex@live.com"))
# db.session.commit()
# db.session.close()
user_list = db.session.query(models.Users).all()
db.session.close()
for item in user_list:
print(item.username,item.email)
return "login"
最后
以上就是从容歌曲为你收集整理的Flask-SQLAlchemy项目实战的全部内容,希望文章能够帮你解决Flask-SQLAlchemy项目实战所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复