刚开始学习flask和python,我不得不创建10个以上具有相同结构和约束的表(MySQLAlchemy)。因此,在寻找比单独声明每个类更快的解决方案之后,我在models / user.py中执行了以下操作:
#models/users.py
class exchangeapis(object):
email = db.Column(db.String(50), primary_key=True)
api =db.Column(db.String(100))
secret= db.Column(db.String(100))
@declared_attr.cascading
# Makes sure all the dbs derived from this calss get the fK and PK
def email(cls):
#this is necessary to propagate fk and pk to the instances
return db.Column(db.String(50), db.ForeignKey('users.email'), primary_key=True)
#general methods to get class data
def get_api(self):
return self.api
def get_secret(self):
return self.secret
exchange=['A','B','C']
for exchange in exchanges:
cls=type(exchange.title(), (exchangeapis, db.Model), { '__tablename__' : str(exchange)+"_api"})
print(cls.__name__)
的
print(cls.__name__)
给我'A','B','C'我希望是'A_api','B_api'...
当我尝试将其导入到我的account / views.py文件中时,具有以下内容:
from ..models import User, A_api
我在第8行中找到“文件” /home/puru991/flask-saas/flask-base/app/account/views.py”
从..models导入User,A_api
ImportError:无法导入名称“ A_api””
但是如果我以以下方式定义类:
class A_api(db.Model):
__tablename__="A_api"
email = db.Column(db.String(50),ForeignKey("users.email"), primary_key=True)
api =db.Column(db.String(100))
secret= db.Column(db.String(100))
#general methods to get class data
def get_api(self):
return self.api
def get_secret(self):
return self.secret
没有错误。所以我的问题是如何基于exchangeapi(object)动态创建类并成功导入它们?
我在这里经历了大约8-10个答案,而我能学到的最多就是如何动态创建它们。我还了解到MySQLAlchemy创建了与表名同名的类,因此我认为通过表名(即“ A_api”)进行引用可以解决问题。我想念什么?
最佳答案
之所以不能导入它们,是因为在users.py
文件中没有名为A_api
的变量。
exchange=['A','B','C']
for exchange in exchanges:
cls=type(exchange.title(), (exchangeapis, db.Model), { '__tablename__' : str(exchange)+"_api"})
print(cls.__name__)
在上面的代码中,您将创建三个类,并且每次将类分配给名为
cls
的变量。一旦for循环完成,变量cls
将是最后一个创建的类,从技术上讲,您可以将此变量导入另一个模块(不过不要这样做)。如果运行以下代码,则可以看到此信息:
exchange=['A','B','C']
for exchange in exchanges:
cls=type(exchange.title(), (exchangeapis, db.Model), { '__tablename__' : str(exchange)+"_api"})
# This will print C_api as it's the last assignment to cls in the for loop
print(cls.__name__)
关于表名/类名;您会从类名中得到错误的解决方法Flask-SQLAlchemy derives the table name,将名为“ CamelCase”的类转换为名为“ camel_case”的表,除非您使用
__tablename__
覆盖表名。允许定义表名允许您使用更Pythonic的命名类名,但使用更常规的数据库表名。请参见以下工作代码的简单演示,两个文件
models.py
和run.py
:models.py
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.declarative import declared_attr
# This list will hold the dynamically created classes
dynamic_models = []
db = SQLAlchemy()
class User(db.Model):
__tablename__ = 'users'
email = db.Column(db.String(254), primary_key=True)
# Other User fields
class ExchangeApiMixin(object):
@declared_attr.cascading
def email(cls):
return db.Column(db.String(254), db.ForeignKey('users.email'), primary_key=True)
api = db.Column(db.String(100))
secret = db.Column(db.String(100))
for exchange in ['A_api', 'B_api', 'C_api']:
cls = type(exchange, (ExchangeApiMixin, db.Model), {})
print(cls.__name__)
dynamic_models.append(cls)
# This will print C_api as it's the last assignment to cls in the for loop
print(cls.__name__)
# Individual variables also reference the dynamically created classes. The could be any legal python variable name
A_API = dynamic_models[0]
B_API = dynamic_models[1]
C_API = dynamic_models[2]
# Succinct way of creating the dynamic classes
(D_API, E_API, F_API) = [type(exchange, (ExchangeApiMixin, db.Model), {}) for exchange in ['D_api', 'E_api', 'F_api']]
运行
import random, string
from flask import Flask, render_template_string
from models import db, dynamic_models, A_API, B_API, C_API, cls, D_API
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
db.init_app(app)
_template = '''
{% for rows in queries %}
<table border='1'>
<thead>
<tr>
<th>Class</th>
<th>Email</th>
<th>API</th>
<th>Secret</th>
</tr>
</thead>
{% for row in rows %}
<tr>
<td>{{row.__class__.__name__}}</td>
<td>{{row.email}}</td>
<td>{{row.api}}</td>
<td>{{row.secret}}</td>
</tr>
{% endfor %}
</table>
<p></p>
{% endfor %}
'''
@app.route('/')
def index():
# display all the A_API, B_API, C_API, D_API instances
a_rows = A_API.query.all()
b_rows = B_API.query.all()
c_rows = C_API.query.all()
d_rows = D_API.query.all()
return render_template_string(_template, queries=[a_rows, b_rows, c_rows, d_rows])
def build_sample_db():
with app.app_context():
db.drop_all()
db.create_all()
def create_from_model(Model, api_name):
for _ in range(0, 10):
_model = Model(
email='{mailbox}@example.com'.format(mailbox=''.join(random.choices(string.ascii_lowercase + string.digits, k=10))),
api=api_name,
secret='pa$$w0rd'
)
db.session.add(_model)
db.session.commit()
# Create instances using A_API, could pass dynamic_models[0]
create_from_model(Model=A_API, api_name='A API Name')
# Create using B_API instances
create_from_model(Model=dynamic_models[1], api_name='B API Name')
# Create using C_API instances using the cls variable (which is the 'C' class
create_from_model(Model=cls, api_name='C API Name')
# Create using D_API instances
create_from_model(Model=D_API, api_name='D API Name')
if __name__ == '__main__':
build_sample_db()
app.run()
关于python - 无法在flask-python中导入动态生成的sqlalchemy类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49332759/