当前位置: 首页>>代码示例>>Python>>正文


Python web.HTTPError方法代码示例

本文整理汇总了Python中tornado.web.HTTPError方法的典型用法代码示例。如果您正苦于以下问题:Python web.HTTPError方法的具体用法?Python web.HTTPError怎么用?Python web.HTTPError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tornado.web的用法示例。


在下文中一共展示了web.HTTPError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: put

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def put(self, bucket, object_name):
        object_name = urllib.unquote(object_name)
        bucket_dir = os.path.abspath(os.path.join(
            self.application.directory, bucket))
        if not bucket_dir.startswith(self.application.directory) or \
           not os.path.isdir(bucket_dir):
            raise web.HTTPError(404)
        path = self._object_path(bucket, object_name)
        if not path.startswith(bucket_dir) or os.path.isdir(path):
            raise web.HTTPError(403)
        directory = os.path.dirname(path)
        if not os.path.exists(directory):
            os.makedirs(directory)
        object_file = open(path, "w")
        object_file.write(self.request.body)
        object_file.close()
        self.finish() 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:19,代码来源:s3server.py

示例2: _read_notebook

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def _read_notebook(self, os_path, as_version=4):
        """Read a notebook from an os path."""
        with self.open(os_path, 'r', encoding='utf-8') as f:
            try:

                # NEW
                file_ext = _file_extension(os_path)
                if file_ext == '.ipynb':
                    return nbformat.read(f, as_version=as_version)
                else:
                    return convert(os_path, from_=self.format, to='notebook')

            except Exception as e:
                raise HTTPError(
                    400,
                    u"Unreadable Notebook: %s %r" % (os_path, e),
                ) 
开发者ID:rossant,项目名称:ipymd,代码行数:19,代码来源:contents_manager.py

示例3: _handle_versions

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def _handle_versions(self):
        args = {k: self.get_argument(k) for k in self.request.arguments}
        try:
            python_version = tuple(int(p) for p in args.pop('pyver').split('.')) \
                if 'pyver' in args else sys.version_info
            arrow_version = args.pop('arrow_version', None)
            pickle_protocol = int(args.pop('pickle_protocol', pickle.HIGHEST_PROTOCOL))
        except ValueError as ex:
            raise web.HTTPError(400, reason='Invalid version data: %s' % ex)
        if python_version[0] != sys.version_info[0]:
            raise web.HTTPError(400, reason='Python version not consistent')

        version_info = dict(python_version=python_version,
                            arrow_version=arrow_version,
                            arrow_compatible=self._check_arrow_compatibility(arrow_version),
                            pickle_protocol=min(pickle_protocol, pickle.HIGHEST_PROTOCOL))
        return version_info, args 
开发者ID:mars-project,项目名称:mars,代码行数:19,代码来源:apihandlers.py

示例4: post

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def post(self, session_id):
        try:
            graph = self.get_argument('graph')
            target = self.get_argument('target').split(',')
            names = self.get_argument('names', default='').split(',')
            compose = bool(int(self.get_argument('compose', '1')))
        except web.MissingArgumentError as ex:
            self.write(json.dumps(dict(msg=str(ex))))
            raise web.HTTPError(400, reason='Argument missing')

        try:
            graph_key = tokenize(str(uuid.uuid4()))
            self.web_api.submit_graph(session_id, graph, graph_key, target, names=names, compose=compose)
            self.write(json.dumps(dict(graph_key=graph_key)))
        except:  # noqa: E722
            self._dump_exception(sys.exc_info()) 
开发者ID:mars-project,项目名称:mars,代码行数:18,代码来源:apihandlers.py

示例5: get_file_checkpoint

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def get_file_checkpoint(self, checkpoint_id, path):
        """Get the content of a checkpoint for a non-notebook file.

         Returns a dict of the form:
         {
             "type": "file",
             "content": <str>,
             "format": {"text","base64"},
         }
        """
        self.log.info("restoring %s from checkpoint %s", path, checkpoint_id)
        cp = self._get_checkpoint_path(checkpoint_id, path)
        exists, blob = self.parent._fetch(cp)
        if not exists:
            raise web.HTTPError(404, u"No such checkpoint: %s for %s" % (
                checkpoint_id, path))
        content, fmt = self.parent._read_file(blob, None)
        return {
            "type": "file",
            "content": content,
            "format": fmt
        } 
开发者ID:src-d,项目名称:jgscm,代码行数:24,代码来源:__init__.py

示例6: get_notebook_checkpoint

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def get_notebook_checkpoint(self, checkpoint_id, path):
        """Get the content of a checkpoint for a notebook.

        Returns a dict of the form:
        {
            "type": "notebook",
            "content": <output of nbformat.read>,
        }
        """
        self.log.info("restoring %s from checkpoint %s", path, checkpoint_id)
        cp = self._get_checkpoint_path(checkpoint_id, path)
        exists, blob = self.parent._fetch(cp)
        if not exists:
            raise web.HTTPError(404, u"No such checkpoint: %s for %s" % (
                checkpoint_id, path))
        nb = self.parent._read_notebook(blob)
        return {
            "type": "notebook",
            "content": nb
        } 
开发者ID:src-d,项目名称:jgscm,代码行数:22,代码来源:__init__.py

示例7: _resolve_storagetype

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def _resolve_storagetype(self, path, storagetype):
        """Based on the arguments and status of GCS, return a valid type."""
        if "/" not in path or path.endswith("/") or path == "":
            if storagetype not in (None, "directory"):
                raise web.HTTPError(
                    400, u"%s is not a directory" % path, reason="bad type")
            return "directory"
        if storagetype is None and path.endswith(".ipynb"):
            return "notebook"
        if storagetype is not None:
            return storagetype
        # If type cannot be inferred from the argument set, use
        # the storage API to see if a blob or a prefix exists.
        if self.file_exists(path):
            return "file"
        if self.dir_exists(path):
            return "directory"
        raise web.HTTPError(
            404, u"%s does not exist" % path, reason="bad type") 
开发者ID:src-d,项目名称:jgscm,代码行数:21,代码来源:__init__.py

示例8: _save_directory

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def _save_directory(self, path, model):
        """Creates a directory in GCS."""
        exists, obj = self._fetch(path)
        if exists:
            if isinstance(obj, Blob):
                raise web.HTTPError(400, u"Not a directory: %s" % path)
            else:
                self.log.debug("Directory %r already exists", path)
                return
        bucket_name, bucket_path = self._parse_path(path)
        if bucket_path == "":
            self.client.create_bucket(bucket_name)
        else:
            bucket = self._get_bucket(bucket_name, throw=True)
            bucket.blob(bucket_path).upload_from_string(
                b"", content_type="application/x-directory") 
开发者ID:src-d,项目名称:jgscm,代码行数:18,代码来源:__init__.py

示例9: _capture_exception

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def _capture_exception(ty, value, tb):
    # type: (type, BaseException, Any) -> None
    hub = Hub.current
    if hub.get_integration(TornadoIntegration) is None:
        return
    if isinstance(value, HTTPError):
        return

    # If an integration is there, a client has to be there.
    client = hub.client  # type: Any

    event, hint = event_from_exception(
        (ty, value, tb),
        client_options=client.options,
        mechanism={"type": "tornado", "handled": False},
    )

    hub.capture_event(event, hint=hint) 
开发者ID:getsentry,项目名称:sentry-python,代码行数:20,代码来源:tornado.py

示例10: get

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def get(self, url_hash):
        """
        Redirects a short URL based on the given url hash.
        """
        long_url, android_url, android_fallback_url, ios_url, ios_fallback_url = self.load_urls(str(url_hash))

        if not long_url:
            raise HTTPError(404)
        else:
            user_agent = self.request.headers.get('User-Agent', '')
            if android_url and 'Android' in user_agent:
                logging.debug('Redirect Android device')
                self.redirect_android(android_url, android_fallback_url)
                return
            elif ios_url and ('iPhone' in user_agent or 'iPad' in user_agent):
                logging.debug('Redirect iOS device')
                self.redirect_ios(ios_url, ios_fallback_url)
                return
            else:
                logging.debug('Default redirect')
                self.redirect(long_url, permanent=True) 
开发者ID:nellessen,项目名称:tornado-shortener,代码行数:23,代码来源:handler.py

示例11: locate_file

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def locate_file(cls, path, roots):
        """locate a file to serve on our static file search path"""
        with cls._lock:
            if path in cls._static_paths:
                return cls._static_paths[path]
            try:
                abspath = os.path.abspath(filefind(path, roots))
            except IOError:
                # empty string should always give exists=False
                return ''
        
            # os.path.abspath strips a trailing /
            # it needs to be temporarily added back for requests to root/
            if not (abspath + os.path.sep).startswith(roots):
                raise HTTPError(403, "%s is not in root static directory", path)
        
            cls._static_paths[path] = abspath
            return abspath 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:20,代码来源:handlers.py

示例12: stop_cluster

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def stop_cluster(self, profile):
        """Stop a cluster for a given profile."""
        self.check_profile(profile)
        data = self.profiles[profile]
        if data['status'] == 'stopped':
            raise web.HTTPError(409, u'cluster not running')
        data = self.profiles[profile]
        cl = data['controller_launcher']
        esl = data['engine_set_launcher']
        if cl.running:
            cl.stop()
        if esl.running:
            esl.stop()
        # Return a temp info dict, the real one is updated in the on_stop
        # logic above.
        result = {
            'profile': data['profile'],
            'profile_dir': data['profile_dir'],
            'status': 'stopped'
        }
        return result 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:23,代码来源:clustermanager.py

示例13: on_first_message

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def on_first_message(self, msg):
        try:
            super(ZMQChannelHandler, self).on_first_message(msg)
        except web.HTTPError:
            self.close()
            return
        try:
            self.create_stream()
        except web.HTTPError:
            # WebSockets don't response to traditional error codes so we
            # close the connection.
            if not self.stream.closed():
                self.stream.close()
            self.close()
        else:
            self.zmq_stream.on_recv(self._on_zmq_reply) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:18,代码来源:handlers.py

示例14: save_new_notebook

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def save_new_notebook(self, data, name=None, format=u'json'):
        """Save a new notebook and return its notebook_id.

        If a name is passed in, it overrides any values in the notebook data
        and the value in the data is updated to use that value.
        """
        if format not in self.allowed_formats:
            raise web.HTTPError(415, u'Invalid notebook format: %s' % format)

        try:
            nb = current.reads(data.decode('utf-8'), format)
        except:
            raise web.HTTPError(400, u'Invalid JSON data')

        if name is None:
            try:
                name = nb.metadata.name
            except AttributeError:
                raise web.HTTPError(400, u'Missing notebook name')
        nb.metadata.name = name

        notebook_id = self.write_notebook_object(nb)
        return notebook_id 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:25,代码来源:nbmanager.py

示例15: delete_notebook

# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import HTTPError [as 别名]
def delete_notebook(self, notebook_id):
        """Delete notebook by notebook_id."""
        nb_path = self.get_path(notebook_id)
        if not os.path.isfile(nb_path):
            raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_id)
        
        # clear checkpoints
        for checkpoint in self.list_checkpoints(notebook_id):
            checkpoint_id = checkpoint['checkpoint_id']
            path = self.get_checkpoint_path(notebook_id, checkpoint_id)
            self.log.debug(path)
            if os.path.isfile(path):
                self.log.debug("unlinking checkpoint %s", path)
                os.unlink(path)
        
        self.log.debug("unlinking notebook %s", nb_path)
        os.unlink(nb_path)
        self.delete_notebook_id(notebook_id) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:20,代码来源:filenbmanager.py


注:本文中的tornado.web.HTTPError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。