我需要为测试目的创建一个dB,我想用" some"来初始化它。用户。
import os
from flask import Flask
from flask.ext.script import Manager, Shell
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
manager = Manager(app)
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(64), unique = True)
email = db.Column(db.String(64), unique = True)
def __init__(self, user = None, email = None):
name = self.__tablename__
db.drop_all()
db.create_all()
for i in range(100):
user = User('user%d' % i, 'someone@example.com')
db.session.add(user)
db.session.commit()
def __repr__(self):
return '<User %r>' % self.name
致电usr_db = User()
生成RuntimeError: maximum recursion depth exceeded
。
问题是,在施工期间,课程已经准备好了#34;以递归方式调用以避免上述错误。
答案 0 :(得分:1)
我认为在模型类中创建测试用户是错误的方法。如果您在__init__()
内实例化User()
实例,则会以递归方式调用__init__()
。一个更好的地方是在单元测试setUp()
方法中。
但是,如果你真的想这样做,你可以防止多次实例化这些用户:
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(64), unique = True)
email = db.Column(db.String(64), unique = True)
_test_users_initialised = False
def _initialise_test_users(self):
if self._test_users_initialised:
return
self.__class__._test_users_initialised = True
for i in range(100):
user = User('user%d' % i, 'someone@example.com')
db.session.add(user)
def __init__(self, user = None, email = None):
name = self.__tablename__
db.drop_all()
db.create_all()
self._initialise_test_users()
db.session.commit()