Python 使用SQLAlchemy和Tornado异步保存API输出

Python 使用SQLAlchemy和Tornado异步保存API输出,python,asynchronous,sqlalchemy,tornado,Python,Asynchronous,Sqlalchemy,Tornado,我想使用SQLAlchemy和Tornado将货币API的输出保存在MySQL表中,但当我循环返回JSON结果时,API返回了结果,我将每个结果插入数据库,应用程序就会卡住。发生这种情况时,在完成所有插入之前,不能执行任何其他过程 我想我应该将insert也作为一个协同程序来执行,但不确定如何执行。我知道异步SQLAlchemy有几个库,比如,但是使用Tornado时真的需要它们吗 下面的代码在对底部和货币汇率执行循环时阻塞 from datetime import datetime from

我想使用SQLAlchemy和Tornado将货币API的输出保存在MySQL表中,但当我循环返回JSON结果时,API返回了结果,我将每个结果插入数据库,应用程序就会卡住。发生这种情况时,在完成所有插入之前,不能执行任何其他过程

我想我应该将insert也作为一个协同程序来执行,但不确定如何执行。我知道异步SQLAlchemy有几个库,比如,但是使用Tornado时真的需要它们吗

下面的代码在对底部和货币汇率执行循环时阻塞

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()

不幸的是,SQLAlchemy不是异步的,对db的每个请求(操作)都将被阻塞。而且,ORM的概念很难使其异步工作(ref:)

您可能对项目(异步)感兴趣:

  • -基于postgres Tornado的客户端,它不是ORM
  • -基于postgres的客户端(Tornado 4.3及更高版本),支持sqlalchemy查询生成器
  • -基于MySQL Tornado的客户端
提示:


收益率还将在出错时引发HTTPError,因此无需显式引发。

谢谢kAlmAcetA!Asyncio看起来很棒,因为我可以使用SQLAlchemy。顺便说一下,谢谢你的提示:)
response = yield http_client.fetch(url)
if response.error:
    raise tornado.web.HTTPError(500)