當前位置: 首頁>>代碼示例>>Python>>正文


Python gen.maybe_future方法代碼示例

本文整理匯總了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 
開發者ID:mosquito,項目名稱:pypi-server,代碼行數:26,代碼來源:package.py

示例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 
開發者ID:uber,項目名稱:tchannel-python,代碼行數:22,代碼來源:server.py

示例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 
開發者ID:uber,項目名稱:tchannel-python,代碼行數:26,代碼來源:server.py

示例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 
開發者ID:uber,項目名稱:tchannel-python,代碼行數:20,代碼來源:test_peer.py

示例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,
        ) 
開發者ID:uber,項目名稱:tchannel-python,代碼行數:20,代碼來源:test_event.py

示例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) 
開發者ID:binux,項目名稱:pyspider,代碼行數:33,代碼來源:tornado_fetcher.py

示例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)) 
開發者ID:binux,項目名稱:pyspider,代碼行數:31,代碼來源:tornado_fetcher.py

示例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) 
開發者ID:jupyterhub,項目名稱:kubespawner,代碼行數:6,代碼來源:spawner.py

示例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)
                    )
                )
            ) 
開發者ID:jupyterhub,項目名稱:kubespawner,代碼行數:38,代碼來源:spawner.py

示例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 
開發者ID:mosquito,項目名稱:pypi-server,代碼行數:17,代碼來源:__init__.py

示例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()) 
開發者ID:mosquito,項目名稱:pypi-server,代碼行數:14,代碼來源:package.py

示例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) 
開發者ID:mosquito,項目名稱:pypi-server,代碼行數:9,代碼來源:__init__.py

示例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 
開發者ID:jupyterhub,項目名稱:binderhub,代碼行數:37,代碼來源:utils.py

示例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)) 
開發者ID:jupyterhub,項目名稱:jupyter-server-proxy,代碼行數:7,代碼來源:websocket.py

示例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) 
開發者ID:GibbsConsulting,項目名稱:jupyter-plotly-dash,代碼行數:5,代碼來源:nbsrvext.py


注:本文中的tornado.gen.maybe_future方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。