本文整理汇总了Python中tornado.gen.maybe_future方法的典型用法代码示例。如果您正苦于以下问题:Python gen.maybe_future方法的具体用法?Python gen.maybe_future怎么用?Python gen.maybe_future使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado.gen
的用法示例。
在下文中一共展示了gen.maybe_future方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: authorization_required
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def authorization_required(func):
@wraps(func)
@coroutine
def wrap(self, *args, **kwargs):
auth_header = self.request.headers.get('Authorization')
if not auth_header:
self.set_header('WWW-Authenticate', 'Basic realm="pypi"')
self.set_status(401)
raise Return(self.finish("Authorization required"))
auth_type, data = auth_header.split()
if auth_type.lower() != 'basic':
raise Return(self.send_error(400))
username, password = map(lambda x: unquote_plus(x.decode("utf-8")), base64.b64decode(b(data)).split(b(":")))
try:
self.current_user = yield check_password(username, password)
except LookupError:
raise HTTPError(403)
result = yield maybe_future(func(self, *args, **kwargs))
raise Return(result)
return wrap
示例2: build_handler
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def build_handler(result_type, f):
@gen.coroutine
def handler(request):
result = ThriftResponse(result_type())
response = Response()
try:
response = yield gen.maybe_future(f(request))
except Exception:
result.write_exc_info(sys.exc_info())
else:
response = response_from_mixed(response)
result.write_result(response.body)
response.status = result.code
response.body = result.result
raise gen.Return(response)
return handler
示例3: deprecated_build_handler
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def deprecated_build_handler(result_type, f):
@gen.coroutine
def handler(request, response):
req = yield ThriftRequest._from_raw_request(request)
res = ThriftResponse(result_type())
try:
# TODO: It would be nice if we could wait until write_result was
# called or an exception was thrown instead of waiting for the
# function to return. This would allow for use cases where the
# implementation returns the result early but still does some work
# after that.
result = yield gen.maybe_future(f(req, res))
except Exception:
res.write_exc_info(sys.exc_info())
else:
if not res.finished and result is not None:
# The user never called write_result or threw an
# exception. The result was most likely returned by the
# function.
res.write_result(result)
response.code = res.code
response.write_header(res.headers)
response.write_body(res.result)
return handler
示例4: test_peer_incoming_connections_are_preferred
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def test_peer_incoming_connections_are_preferred(request):
incoming = mock.MagicMock()
incoming.closed = False
outgoing = mock.MagicMock()
outgoing.closed = False
peer = tpeer.Peer(mock.MagicMock(), 'localhost:4040')
with mock.patch(
'tchannel.tornado.connection.StreamConnection.outgoing'
) as mock_outgoing:
mock_outgoing.return_value = gen.maybe_future(outgoing)
peer.connect()
assert (yield peer.connect()) is outgoing
peer.register_incoming_conn(incoming)
assert (yield peer.connect()) is incoming
示例5: test_after_send_error_event_called
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def test_after_send_error_event_called():
tchannel = TChannel('test')
tchannel.listen()
with mock.patch(
'tchannel.event.EventEmitter.fire', autospec=True,
) as mock_fire:
mock_fire.return_value = maybe_future(None)
with pytest.raises(BadRequestError):
yield tchannel.call(
scheme=schemes.RAW,
service='test',
arg1='endpoint',
hostport=tchannel.hostport,
timeout=0.3,
)
mock_fire.assert_any_call(
mock.ANY, EventType.after_send_error, mock.ANY,
)
示例6: async_fetch
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def async_fetch(self, task, callback=None):
'''Do one fetch'''
url = task.get('url', 'data:,')
if callback is None:
callback = self.send_result
type = 'None'
start_time = time.time()
try:
if url.startswith('data:'):
type = 'data'
result = yield gen.maybe_future(self.data_fetch(url, task))
elif task.get('fetch', {}).get('fetch_type') in ('js', 'phantomjs'):
type = 'phantomjs'
result = yield self.phantomjs_fetch(url, task)
elif task.get('fetch', {}).get('fetch_type') in ('splash', ):
type = 'splash'
result = yield self.splash_fetch(url, task)
elif task.get('fetch', {}).get('fetch_type') in ('puppeteer', ):
type = 'puppeteer'
result = yield self.puppeteer_fetch(url, task)
else:
type = 'http'
result = yield self.http_fetch(url, task)
except Exception as e:
logger.exception(e)
result = self.handle_error(type, url, task, start_time, e)
callback(type, task, result)
self.on_result(type, task, result)
raise gen.Return(result)
示例7: can_fetch
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def can_fetch(self, user_agent, url):
parsed = urlsplit(url)
domain = parsed.netloc
if domain in self.robots_txt_cache:
robot_txt = self.robots_txt_cache[domain]
if time.time() - robot_txt.mtime() > self.robot_txt_age:
robot_txt = None
else:
robot_txt = None
if robot_txt is None:
robot_txt = RobotFileParser()
try:
response = yield gen.maybe_future(self.http_client.fetch(
urljoin(url, '/robots.txt'), connect_timeout=10, request_timeout=30))
content = response.body
except tornado.httpclient.HTTPError as e:
logger.error('load robots.txt from %s error: %r', domain, e)
content = ''
try:
content = content.decode('utf8', 'ignore')
except UnicodeDecodeError:
content = ''
robot_txt.parse(content.splitlines())
self.robots_txt_cache[domain] = robot_txt
raise gen.Return(robot_txt.can_fetch(user_agent, url))
示例8: _render_options_form_dynamically
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def _render_options_form_dynamically(self, current_spawner):
profile_list = yield gen.maybe_future(self.profile_list(current_spawner))
profile_list = self._init_profile_list(profile_list)
return self._render_options_form(profile_list)
示例9: load_user_options
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def load_user_options(self):
"""Load user options from self.user_options dict
This can be set via POST to the API or via options_from_form
Only supported argument by default is 'profile'.
Override in subclasses to support other options.
"""
if self._profile_list is None:
if callable(self.profile_list):
profile_list = yield gen.maybe_future(self.profile_list(self))
else:
profile_list = self.profile_list
self._profile_list = self._init_profile_list(profile_list)
selected_profile = self.user_options.get('profile', None)
if self._profile_list:
yield self._load_profile(selected_profile)
elif selected_profile:
self.log.warning("Profile %r requested, but profiles are not enabled", selected_profile)
# help debugging by logging any option fields that are not recognized
option_keys = set(self.user_options)
unrecognized_keys = option_keys.difference(self._user_option_keys)
if unrecognized_keys:
self.log.warning(
"Ignoring unrecognized KubeSpawner user_options: %s",
", ".join(
map(
str,
sorted(unrecognized_keys)
)
)
)
示例10: add_slash
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def add_slash(cls):
def redirect(self, *args, **kwargs):
pass
class WrappedClass(cls):
@coroutine
def prepare(self, *args, **kwargs):
if not self.request.path.endswith('/'):
raise Return(self.redirect("{0}/".format(self.request.path)))
else:
raise Return((yield maybe_future(cls.prepare(self, *args, **kwargs))))
WrappedClass.__name__ = cls.__name__
return WrappedClass
示例11: post
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def post(self):
try:
action = self.get_body_argument(':action')
self.request.body_arguments.pop(':action')
log.debug("Request to call action: %s", action)
method = getattr(self, "action_{0}".format(action), self._action_not_found)
except:
raise HTTPError(400)
log.info("Calling action: %s", action)
yield maybe_future(method())
示例12: _async_response
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def _async_response(self, data):
data = yield maybe_future(data)
resp = yield self._to_json(data)
if not self._finished:
log.debug("Sending: %r", resp)
self.finish(resp)
示例13: fetch
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def fetch(self, req_or_url, *args, **kwargs):
"""Mocked HTTP fetch
If the request URL is in self.mocks, build a response from the cached response.
Otherwise, run the actual request and store the response in self.records.
"""
if isinstance(req_or_url, HTTPRequest):
request = req_or_url
else:
request = HTTPRequest(req_or_url, *args, **kwargs)
url_key = self.url_key(request.url)
if url_key in self.mocks:
fetch = self.fetch_mock
else:
fetch = super().fetch
error = None
try:
response = await gen.maybe_future(fetch(request))
except HTTPError as e:
error = e
response = e.response
self._record_response(url_key, response)
# return or raise the original result
if error:
raise error
else:
return response
# async-request utility from jupyterhub.tests.utils v0.8.1
# used under BSD license
示例14: get
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def get(self, *args, **kwargs):
if self.request.headers.get("Upgrade", "").lower() != 'websocket':
return await self.http_get(*args, **kwargs)
else:
await maybe_future(super().get(*args, **kwargs))
示例15: wrapped_get
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import maybe_future [as 别名]
def wrapped_get(self, kernel_id):
# TODO wrap in maybe_future
yield current_get(self, kernel_id)