Python tornado.web.HTTPError() Examples

The following are 30 code examples of tornado.web.HTTPError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado.web , or try the search function .
Example #1
Source File: test_tornado_client.py    From jsonrpcclient with MIT License 8 votes vote down vote up
def post(self):
        request = json.loads(self.request.body.decode())
        raise web.HTTPError(request["params"]["code"]) 
Example #2
Source File: handler.py    From tornado-shortener with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: s3server.py    From tornado-zh with MIT License 6 votes vote down vote up
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() 
Example #4
Source File: category.py    From Doodle with MIT License 6 votes vote down vote up
def get(self, category_name):
        if not Category.exists(category_name):
            raise HTTPError(404)

        articles, next_cursor = CategoryArticles.get_articles(category_name, self.cursor)
        if articles:
            article_ids = [article.id for article in articles]
            hit_counts = ArticleHitCount.get_by_ids(article_ids)
            replies_dict = ArticleComments.get_comment_count_of_articles(article_ids)
        else:
            hit_counts = replies_dict = {}
            next_cursor = None

        self.set_cache(CONFIG.DEFAULT_CACHE_TIME, is_public=True)
        self.render('web/category_articles.html', {
            'title': u'分类《%s》' % category_name,
            'page': 'category_articles',
            'next_cursor': next_cursor,
            'category_name': category_name,
            'articles': articles,
            'hit_counts': hit_counts,
            'replies_dict': replies_dict
        }) 
Example #5
Source File: tag.py    From Doodle with MIT License 6 votes vote down vote up
def get(self, tag_name):
        if not Tag.exists(tag_name):
            raise HTTPError(404)

        articles, next_cursor = TagArticle.get_articles(tag_name, self.cursor)
        if articles:
            article_ids = [article.id for article in articles]
            hit_counts = ArticleHitCount.get_by_ids(article_ids)
            replies_dict = ArticleComments.get_comment_count_of_articles(article_ids)
        else:
            hit_counts = replies_dict = {}
            next_cursor = None

        self.set_cache(CONFIG.DEFAULT_CACHE_TIME, is_public=True)
        self.render('web/tag_articles.html', {
            'title': u'标签《%s》' % tag_name,
            'page': 'tag_articles',
            'next_cursor': next_cursor,
            'tag_name': tag_name,
            'articles': articles,
            'hit_counts': hit_counts,
            'replies_dict': replies_dict
        }) 
Example #6
Source File: search.py    From Doodle with MIT License 6 votes vote down vote up
def get(self):
        keywords = self.get_argument('keywords', None)
        if keywords:
            article_ids = KeywordArticle.query_by_keyword(keywords)
            if article_ids:
                articles = Article.get_by_ids(article_ids, public_only=True)
                article_ids = [article.id for article in articles]
                hit_counts = ArticleHitCount.get_by_ids(article_ids)
                replies_dict = ArticleComments.get_comment_count_of_articles(article_ids)
            else:
                articles = []
                hit_counts = replies_dict = {}

            self.set_cache(CONFIG.DEFAULT_CACHE_TIME, is_public=True)
            self.render('web/search.html', {
                'title': u'搜索《%s》' % keywords,
                'page': 'search',
                'keywords': keywords,
                'articles': articles,
                'hit_counts': hit_counts,
                'replies_dict': replies_dict
            })
        else:
            raise HTTPError(400) 
Example #7
Source File: azurenbmanager.py    From Computable with MIT License 6 votes vote down vote up
def read_notebook_object(self, notebook_id):
        """Get the object representation of a notebook by notebook_id."""
        if not self.notebook_exists(notebook_id):
            raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_id)
        try:
            s = self.blob_service.get_blob(self.container, notebook_id)
        except:
            raise web.HTTPError(500, u'Notebook cannot be read.')
        try:
            # v1 and v2 and json in the .ipynb files.
            nb = current.reads(s, u'json')
        except:
            raise web.HTTPError(500, u'Unreadable JSON notebook.')
        # Todo: The last modified should actually be saved in the notebook document.
        # We are just using the current datetime until that is implemented.
        last_modified = tz.utcnow()
        return last_modified, nb 
Example #8
Source File: filenbmanager.py    From Computable with MIT License 6 votes vote down vote up
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) 
Example #9
Source File: apihandlers.py    From mars with Apache License 2.0 6 votes vote down vote up
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 
Example #10
Source File: apihandlers.py    From mars with Apache License 2.0 6 votes vote down vote up
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()) 
Example #11
Source File: nbmanager.py    From Computable with MIT License 6 votes vote down vote up
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 
Example #12
Source File: __init__.py    From jgscm with MIT License 6 votes vote down vote up
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
        } 
Example #13
Source File: contents_manager.py    From ipymd with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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),
                ) 
Example #14
Source File: handlers.py    From Computable with MIT License 6 votes vote down vote up
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 
Example #15
Source File: clustermanager.py    From Computable with MIT License 6 votes vote down vote up
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 
Example #16
Source File: tornado.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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) 
Example #17
Source File: __init__.py    From jgscm with MIT License 6 votes vote down vote up
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") 
Example #18
Source File: handlers.py    From Computable with MIT License 6 votes vote down vote up
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) 
Example #19
Source File: __init__.py    From jgscm with MIT License 6 votes vote down vote up
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") 
Example #20
Source File: __init__.py    From jgscm with MIT License 6 votes vote down vote up
def get(self, path, content=True, type=None, format=None):
        if isinstance(path, Blob):
            obj = path
            path = self._get_blob_path(obj)
        elif path.startswith("/"):
            path = path[1:]
        if not path:
            path = self.default_path

        type = self._resolve_storagetype(path, type)
        if type == "directory":
            if path and not path.endswith("/"):
                path += "/"
            exists, members = self._fetch(path, content=content)
            if not exists:
                raise web.HTTPError(404, u"No such directory: %s" % path)
            model = self._dir_model(path, members, content=content)
        else:
            exists, blob = self._fetch(path)
            if not exists:
                raise web.HTTPError(404, u"No such file: %s" % path)
            if type == "notebook" or (type is None and path.endswith(".ipynb")):
                model = self._notebook_model(blob, content=content)
            else:
                model = self._file_model(blob, content=content, format=format)
        return model 
Example #21
Source File: __init__.py    From jgscm with MIT License 6 votes vote down vote up
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
        } 
Example #22
Source File: gen_test.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def prepare(self):
        yield gen.Task(IOLoop.current().add_callback)
        raise HTTPError(403) 
Example #23
Source File: nbmanager.py    From Computable with MIT License 5 votes vote down vote up
def get_notebook(self, notebook_id, format=u'json'):
        """Get the representation of a notebook in format by notebook_id."""
        format = unicode(format)
        if format not in self.allowed_formats:
            raise web.HTTPError(415, u'Invalid notebook format: %s' % format)
        last_modified, nb = self.read_notebook_object(notebook_id)
        kwargs = {}
        if format == 'json':
            # don't split lines for sending over the wire, because it
            # should match the Python in-memory format.
            kwargs['split_lines'] = False
        data = current.writes(nb, format, **kwargs)
        name = nb.metadata.get('name','notebook')
        return last_modified, name, data 
Example #24
Source File: auth_test.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def get(self, screen_name):
        if screen_name == 'error':
            raise HTTPError(500)
        assert 'oauth_nonce' in self.request.arguments
        assert 'oauth_timestamp' in self.request.arguments
        assert 'oauth_signature' in self.request.arguments
        assert self.get_argument('oauth_consumer_key') == 'test_twitter_consumer_key'
        assert self.get_argument('oauth_signature_method') == 'HMAC-SHA1'
        assert self.get_argument('oauth_version') == '1.0'
        assert self.get_argument('oauth_token') == 'hjkl'
        self.write(dict(screen_name=screen_name, name=screen_name.capitalize())) 
Example #25
Source File: web_test.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def get(self):
            raise HTTPError(682, reason="Foo") 
Example #26
Source File: kernelmanager.py    From Computable with MIT License 5 votes vote down vote up
def _check_kernel_id(self, kernel_id):
        """Check a that a kernel_id exists and raise 404 if not."""
        if kernel_id not in self:
            raise web.HTTPError(404, u'Kernel does not exist: %s' % kernel_id) 
Example #27
Source File: zmqhandlers.py    From Computable with MIT License 5 votes vote down vote up
def on_first_message(self, msg):
        self._inject_cookie_message(msg)
        if self.get_current_user() is None:
            self.log.warn("Couldn't authenticate WebSocket connection")
            raise web.HTTPError(403)
        self.on_message = self.save_on_message 
Example #28
Source File: zmqhandlers.py    From Computable with MIT License 5 votes vote down vote up
def open(self, kernel_id):
        # Check to see that origin matches host directly, including ports
        if not self.same_origin():
            self.log.warn("Cross Origin WebSocket Attempt.")
            raise web.HTTPError(404)

        self.kernel_id = cast_unicode(kernel_id, 'ascii')
        self.session = Session(config=self.config)
        self.save_on_message = self.on_message
        self.on_message = self.on_first_message 
Example #29
Source File: web_test.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def test_httperror_str(self):
        self.assertEqual(str(HTTPError(682, reason="Foo")), "HTTP 682: Foo") 
Example #30
Source File: clustermanager.py    From Computable with MIT License 5 votes vote down vote up
def check_profile(self, profile):
        if profile not in self.profiles:
            raise web.HTTPError(404, u'profile not found')