私はデータベースレコードセット(約1000行)を持っていますが、現在、レコードごとに余分なDBクエリを使用してより多くのデータを統合するために、それらを繰り返しています。レコードセット内のPythonマルチスレッド
これを実行すると、処理時間が100秒になることがあります。
私がしたいことは、この機能を2-4のプロセスと共有することです。
私はPython 2.7を使用してAWSラムダ互換性を持っています。
def handler(event, context):
try:
records = connection.get_users()
mandrill_client = open_mandrill_connection()
mandrill_messages = get_mandrill_messages()
mandrill_template = 'POINTS weekly-report-to-user'
start_time = time.time()
messages = build_messages(mandrill_messages, records)
print("OVERALL: %s seconds ---" % (time.time() - start_time))
send_mandrill_message(mandrill_client, mandrill_template, messages)
connection.close_database_connection()
return "Process Completed"
except Exception as e:
print(e)
私がスレッドに入れたい機能を以下に示します。
def build_messages(messages, records):
for record in records:
record = dict(record)
stream = get_user_stream(record)
data = compile_loyalty_stream(stream)
messages['to'].append({
'email': record['email'],
'type': 'to'
})
messages['merge_vars'].append({
'rcpt': record['email'],
'vars': [
{
'name': 'total_points',
'content': record['total_points']
},
{
'name': 'total_week',
'content': record['week_points']
},
{
'name': 'stream_greek',
'content': data['el']
},
{
'name': 'stream_english',
'content': data['en']
}
]
})
return messages
私は何をしようとしたことはマルチプロセッシング・ライブラリをインポートします
試し内部のプールを作成しfrom multiprocessing.pool import ThreadPool
をブロックし、このプール内の関数をマップしました。
pool = ThreadPool(4)
messages = pool.map(build_messages_in, itertools.izip(itertools.repeat(mandrill_messages), records))
def build_messages_in(a_b):
build_msg(*a_b)
def build_msg(a, b):
return build_messages(a, b)
def get_user_stream(record):
response = []
i = 0
for mod, mod_id, act, p, act_created in izip(record['models'], record['model_ids'], record['actions'],
record['points'], record['action_creation']):
information = get_reference(mod, mod_id)
if information:
response.append({
'action': act,
'points': p,
'created': act_created,
'info': information
})
if (act == 'invite_friend') \
or (act == 'donate') \
or (act == 'bonus_500_general') \
or (act == 'bonus_1000_general') \
or (act == 'bonus_500_cancel') \
or (act == 'bonus_1000_cancel'):
response[i]['info']['date_ref'] = act_created
response[i]['info']['slug'] = 'attiki'
if (act == 'bonus_500_general') \
or (act == 'bonus_1000_general') \
or (act == 'bonus_500_cancel') \
or (act == 'bonus_1000_cancel'):
response[i]['info']['title'] = ''
i += 1
return response
最後に、ループのをbuild_message関数から削除しました。
「NoneType」オブジェクトは反復可能ではありません。
これを行う正しい方法ですか?
@GhostCat私は質問を提出し、私が試したことを書き留めるのを忘れました。以下は動作するコードですが、以下は動作するはずのコードですが、動作しません。基本的に私はbuild_messages関数をマルチプロセスしようとしています。 – mallix
今すぐ専門家にあなたを助けてもらおう;-) – GhostCat
あなたはそのエラーをどこにしているのかは言わなかった。私が収集できるものから、これは 'mailchimp' APIを使用しています。私は最も長い待ち時間がAPIレスポンスであると仮定していますか? – roganjosh