Flask / Threading-将模型中的数据作为参数传递给函数

时间:2019-11-19 21:39:43

标签: python flask flask-sqlalchemy

Python / Flask / Flask-SQLAlchemy的新手。我正在尝试为每个用户启动一个线程,以使用其用户名/电子邮件做某事。我一直在尝试将模型数据传递到模板并在其中使用它,但这让我很困惑。

#Create the user model to store usernames & emails
class User(db.Model):
 id = db.Column(db.Integer, primary_key=True)
 username = db.Column(db.String(20), unique=True, nullable=False)
 email = db.Column(db.String(120), unique=True, nullable=False)

#Function to do something with the each users username & email
def do_something(name, email):
    #code goes here that does stuff with the name & email

#Query to get the list of all users data
users = User.query.all()

#Start threads for each user and pass in the users data (usernames & emails) to the do_something function
with concurrent.futures.ThreadPoolExecutor() as executor:
    executor.map(do_something, users.username, users.email)

我收到以下错误

executor.map(do_something, users.username, users.email)
AttributeError: 'list' object has no attribute 'username'

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

users = User.query.all()返回所有Users列表列表没有username属性。您需要遍历列表以获取User

也许是这样的:

#Query to get the list of all users data
users = User.query.all()

#Start threads for each user and pass in the users data (usernames & emails) to the do_something function
with concurrent.futures.ThreadPoolExecutor() as executor:
    for user in users:
         executor.map(do_something, user.username, user.email)