线程和异步 API 库
threaded and asyncio API library
在 Python 中,我正在尝试为连接的设备创建一个 API。我希望同时适用于线程化(使用请求)和异步应用程序(使用 aiohttp)。
我想到的是在装饰器中包装 requests
和 aiohttp
的 get 方法。此装饰器在初始化时传递,API 调用使用传递的装饰器显式包装。
它有效,但我想知道其他人如何看待这种方法?有没有更好的方法或者我以后会 运行 遇到问题?
感谢任何帮助!
def threaded_gett(function):
# The threaded decorator
def wrapper(*args, **kwargs):
url, params = function(*args)
response = requests.get(url, params)
_json = response.json()
return function.__self__.process_response(_json)
return wrapper
def async_gett(function):
# The async decorator
def wrapper(*args, **kwargs):
url, params = function(*args)
try:
resp = yield from function.__self__.session.get(url, params=params)
except Exception as ex:
lgr.exception(ex)
else:
_json = yield from resp.json()
yield from resp.release()
return function.__self__.process_response(_json)
# wrapping the decorator in the async coroutine decorator.
wrapper = asyncio.coroutine(wrapper)
return wrapper
class ThreadedApi(BaseApi):
def __init__(self,threaded_gett):
Base.__init(self,threaded_gett)
class AsyncApi(BaseApi):
def __init__(self,async_gett):
Base.__init(self,async_gett)
class BaseApi():
def __init__(self,get_wrapper):
self.status = get_wrapper(self.status)
def status(self):
return <status path>
您的代码不完整,但是是的,该方法可能适用于简单的情况(当 .process_response()
非常通用并且可以应用于所有 API 调用时)。
在 Python 中,我正在尝试为连接的设备创建一个 API。我希望同时适用于线程化(使用请求)和异步应用程序(使用 aiohttp)。
我想到的是在装饰器中包装 requests
和 aiohttp
的 get 方法。此装饰器在初始化时传递,API 调用使用传递的装饰器显式包装。
它有效,但我想知道其他人如何看待这种方法?有没有更好的方法或者我以后会 运行 遇到问题?
感谢任何帮助!
def threaded_gett(function):
# The threaded decorator
def wrapper(*args, **kwargs):
url, params = function(*args)
response = requests.get(url, params)
_json = response.json()
return function.__self__.process_response(_json)
return wrapper
def async_gett(function):
# The async decorator
def wrapper(*args, **kwargs):
url, params = function(*args)
try:
resp = yield from function.__self__.session.get(url, params=params)
except Exception as ex:
lgr.exception(ex)
else:
_json = yield from resp.json()
yield from resp.release()
return function.__self__.process_response(_json)
# wrapping the decorator in the async coroutine decorator.
wrapper = asyncio.coroutine(wrapper)
return wrapper
class ThreadedApi(BaseApi):
def __init__(self,threaded_gett):
Base.__init(self,threaded_gett)
class AsyncApi(BaseApi):
def __init__(self,async_gett):
Base.__init(self,async_gett)
class BaseApi():
def __init__(self,get_wrapper):
self.status = get_wrapper(self.status)
def status(self):
return <status path>
您的代码不完整,但是是的,该方法可能适用于简单的情况(当 .process_response()
非常通用并且可以应用于所有 API 调用时)。