刚开始学习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
我得到“文件”/home/puru991/flask-saas/flask-base/app/account/views.py“,第8行,在 来自..models导入用户,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(对象)动态创建类并成功导入它们? 我在这里经历了大约8-10个答案,我可以学到的最多是如何动态创建它们。我还了解到,MySQLAlchemy创建了与tablename同名的类,所以我认为通过表名引用(即“A_api”)就可以了。我错过了什么?
答案 0 :(得分:1)
您无法导入它们的原因是因为您的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”的表,除非你使用{{1覆盖表名称}}。允许定义表名允许您使用更多Pythonic命名的类名,但使用更传统的DB表名。
请参阅下面的工作代码简单演示,两个文件__tablename__
和models.py
:
<强> models.py 强>
run.py
<强> run.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']]