简体   繁体   English

Flask-SQLAlchemy-SQL操作

[英]Flask-SQLAlchemy - SQL operations

Am using Flask with Flask-SQLAlchemy, for the SQL operations, i can able to successfully insert a record into mysql database from the 我将Flask与Flask-SQLAlchemy结合使用,以进行SQL操作,我可以成功地将记录从mysql数据库插入mysql数据库中。

Views.py Views.py

from models import *
user= adduser('test')
db.session.add(user)
db.session.commit()

models.py models.py

from flask_sqlalchemy import SQLAlchemy
from app import app
db = SQLAlchemy(app)

class adduser(db.Model):
__tablename__ = 'adduser'
id = db.Column('user_id', db.Integer, primary_key=True)
UserName = db.Column(db.String(16))

def __init__(self, UserName):
    self.UserName = UserName

How to do the same operation in a separate Python file (suppose i want to handle the insert operation in a file other than views.py, say insertuser.py) 如何在单独的Python文件中执行相同的操作(假设我想在非views.py的文件中处理插入操作,比如insertuser.py)

Create your project as a package with ___init__.py . 使用___init__.py将项目创建为一个包。 Then you just need to initialize the "app", "db", variables once and can re-use. 然后,您只需要初始化一次“ app”,“ db”,变量即可重复使用。 Something like: 就像是:

myproject/
    __init__.py
    models.py
    views.py
    insertuser.py

Now, in your __init__.py file, put the initialization code: 现在,在您的__init__.py文件中,放置初始化代码:

app = Flask(__name__)
db = SQLAlchemy(app)

Then just import these in the insertuser.py file: 然后将它们导入insertuser.py文件中:

from myproject import app, db
..insert code goes here...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM