编写一个验证电子邮件语法和MX记录列表的程序,由于阻塞编程非常耗时,我想进行异步或按线程,这是我的代码:
with open(file_path) as f:
# check the status of file, if away then file pointer will be at the last index
if (importState.status == ImportStateFile.STATUS_AWAY):
f.seek(importState.fileIndex, 0)
while True:
# the number of emails to process is configurable 10 or 20
emails = list(islice(f, app.config['NUMBER_EMAILS_TO_PROCESS']))
if len(emails) == 0:
break;
importState.fileIndex = importState.fileIndex + len(''.join(emails))
for email in emails:
email = email.strip('''<>;,'\r\n ''').lower()
d = threads.deferToThread(check_email, email)
d.addCallback(save_email_status, email, importState)
# set the number of emails processed
yield set_nbrs_emails_process(importState)
# do an insert of all emails
yield reactor.callFromThread(db.session.commit)
# set file status as success
yield finalize_import_file_state(importState)
reactor.callFromThread(reactor.stop)
检查电子邮件功能:
^{pr2}$我需要的是在同一时间处理10封电子邮件,然后等待结果。在
我不知道为什么示例代码中会涉及线程。你不需要线程与Twisted的电子邮件交互,也不需要同时这样做。在
如果有一个异步函数返回
Deferred
,那么只需调用它十次,十个不同的工作流将并行进行:如果您想知道何时所有10个结果都可用,可以使用gatherResults:
^{pr2}$all_results
是一个Deferred
,当email_results
中的所有Deferreds
都已触发时(或当其中的第一个用Failure
触发)时将触发。在相关问题 更多 >
编程相关推荐