0
我要保存使用SQLAlchemy的和龍捲風一個MySQL表中的貨幣API的輸出,但是當我遍歷所有的JSON產生的API返回,我插入每一個到數據庫中,應用程序卡住了。在發生這種情況之前,在所有插入完成之前,不能執行其他過程。節能API輸出異步使用SQLAlchemy的和龍捲風
我想我也應該執行插入的協程,但不知道該怎麼做。我知道有幾個用於異步SQLAlchemy的庫,例如Asyncio,但是在使用Tornado時它們真的需要嗎?
執行在底部環和Currency_rate
from datetime import datetime
from decimal import Decimal
import urllib
import tornado.web
import tornado.httpclient
from tornado import gen
from src.entities.currency import list_currencies, view_iso_a3_currency
from src.entities.currency_rate import Currency_rate
@gen.coroutine
def currencylayer_currency_rate():
http_client = tornado.httpclient.AsyncHTTPClient()
base_url = "http://apilayer.net/api/live?"
base_currency = view_iso_a3_currency('USD')
vars = {'access_key': 'APIKEY', 'source': base_currency.iso_a3, 'format': 1}
url = base_url + urllib.parse.urlencode(vars)
response = yield http_client.fetch(url)
if response.error:
raise tornado.web.HTTPError(500)
json = tornado.escape.json_decode(response.body)
timestamp = datetime.fromtimestamp(int(json['timestamp'])).strftime('%Y-%m-%d %H:%M:%S')
json_rates = json['quotes']
for key, value in json_rates.items():
quote_currency = view_iso_a3_currency(str(key)[-3:])
if not quote_currency:
continue
currency_rate = Currency_rate(m_currency_id1 = base_currency.id,
m_currency_id2 = quote_currency.id,
rate = Decimal(value),
date = timestamp,
create_user = 1,
update_user = 1,
active = 1)
currency_rate.add()
謝謝kAlmAcetA! Asyncio看起來不錯,因爲我可以使用SQLAlchemy。謝謝你的提示:) – user3159821