问题描述
我有一个使用 Flask
和 Flask-SQLAlchemy
构建的小型Web服务,仅包含一个模型.现在,我想使用相同的数据库,但使用命令行应用程序,因此我想删除 Flask
依赖项.
I had a small web service built using Flask
and Flask-SQLAlchemy
that only held one model. I now want to use the same database, but with a command line app, so I'd like to drop the Flask
dependency.
我的模型如下:
class IPEntry(db.Model):
id = db.Column(db.Integer, primary_key=True)
ip_address = db.Column(db.String(16), unique=True)
first_seen = db.Column(db.DateTime(),
default = datetime.datetime.utcnow
)
last_seen = db.Column(db.DateTime(),
default = datetime.datetime.utcnow
)
@validates('ip')
def validate_ip(self, key, ip):
assert is_ip_addr(ip)
return ip
由于 db
将不再是 flask.ext.sqlalchemy.SQLAlchemy(app)
的引用,因此如何转换模型以仅使用SQLAlchemy.两种应用程序(使用 Flask-SQLAlchemy
的其他应用程序和使用 SQLAlchemy
的其他应用程序)是否可以使用同一数据库?
Since db
will no longer be a reference to flask.ext.sqlalchemy.SQLAlchemy(app)
, how can I convert my model to use just SQLAlchemy. Is there a way for the two applications (one with Flask-SQLAlchemy
the other with SQLAlchemy
) to use the same database?
推荐答案
您可以执行此操作以替换 db.Model
:
you can do this to replace db.Model
:
from sqlalchemy import orm
from sqlalchemy.ext.declarative import declarative_base
import sqlalchemy as sa
base = declarative_base()
engine = sa.create_engine(YOUR_DB_URI)
base.metadata.bind = engine
session = orm.scoped_session(orm.sessionmaker())(bind=engine)
# after this:
# base == db.Model
# session == db.session
# other db.* values are in sa.*
# ie: old: db.Column(db.Integer,db.ForeignKey('s.id'))
# new: sa.Column(sa.Integer,sa.ForeignKey('s.id'))
# except relationship, and backref, those are in orm
# ie: orm.relationship, orm.backref
# so to define a simple model
class UserModel(base):
__tablename__ = 'users' #<- must declare name for db table
id = sa.Column(sa.Integer,primary_key=True)
name = sa.Column(sa.String(255),nullable=False)
然后创建表:
base.metadata.create_all()
这篇关于在不使用Flask的情况下使用Flask-SQLAlchemy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!