【发布时间】:2016-11-16 07:31:39
【问题描述】:
我正在通过 Google App Engine 编写一个网络应用程序,我希望有一个脚本根据我从 XML 提要获得的实时临时信息频繁更新用户配置文件。我正在使用 GAE background_thread 执行此操作,因此该站点可以在运行时继续运行。
在这个后台线程之外,用户仍然可以浏览网站,从而更改他们的个人资料。
后台线程完全按照它应该做的事情,根据实时 XML 数据更新用户配置文件并将配置文件重新输入到数据存储中。但是,当用户对其个人资料进行更改时,后台线程不会接受更改。 ndb 数据存储查询返回的列表不反映用户所做的更改。
奇怪的细节是,如果将新用户添加到数据存储区,它确实会反映正确的更改,但如果修改了预先存在的用户配置文件,它只是不会反映更改。我应该能够从后台线程查询/放置数据存储区吧?
后台线程的肉:
def update_accounts():
while True:
# Get data from XML feed.
info_dict = get_live_data()
# Get all the users from the GAE database
gprofiles = mUserStats.query()
for profile in gprofiles:
# This isn't the actual condition but there's a condition here.
if needs_update in profile.m_needsUpdate:
# Modify the current profile.
profile.make_change(info_dict)
# Re enter into database.
profile.put()
# Add a sleep time as this doesn't need to run that frequently.
time.sleep(20)
类 updateAccounts():
def start_thread(self):
t =background_thread.start_new_background_thread(target=update_accounts())
这是修改配置文件的地方:
def post(self):
session = get_current_session()
user_key = mUserStats_key(session['me'].m_email)
curr_user = mUserStats.get_by_id(session['me'].m_email, user_key)
curr_user.change_profile()
curr_user.put()
【问题讨论】:
-
除非您执行祖先查询,否则执行查询(您的后台线程正在执行查询)的任何操作都受制于最终一致性。顺便说一句,前端请求中的后台线程真的不会给你买很多东西。如果您在等待 IO,那么只需使用异步 tasklet。如果你的 CPU 绑定,那么后台线程不会改善这种情况。此外,线程的寿命不能超过请求。
标签: python multithreading google-app-engine google-cloud-datastore gae-userservice