python类HTTPError()的实例源码

__init__.py 文件源码 项目:jgscm 作者: src-d 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _read_file(self, blob, format):
        """Reads a non-notebook file.

        blob: instance of :class:`google.cloud.storage.Blob`.
        format:
          If "text", the contents will be decoded as UTF-8.
          If "base64", the raw bytes contents will be encoded as base64.
          If not specified, try to decode as UTF-8, and fall back to base64
        """
        bcontent = blob.download_as_string()

        if format is None or format == "text":
            # Try to interpret as unicode if format is unknown or if unicode
            # was explicitly requested.
            try:
                return bcontent.decode("utf8"), "text"
            except UnicodeError:
                if format == "text":
                    raise web.HTTPError(
                        400, "%s is not UTF-8 encoded" %
                             self._get_blob_path(blob),
                        reason="bad format",
                    )
        return base64.encodebytes(bcontent).decode("ascii"), "base64"
base_handler.py 文件源码 项目:tornado-ssdb-project 作者: ego008 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def authorized(admin_only=False):
    def wrap(user_handler):
        @wraps(user_handler)
        def authorized_handler(self, *args, **kwargs):
            self.set_cache(is_public=False)
            request = self.request
            if request.method == 'GET':
                if not self.current_user_id:
                    next_url = self.get_argument('next', '/')
                    self.redirect(self.get_login_url() + "?next=" + next_url, status=302 if request.version == 'HTTP/1.0' else 303)
                elif admin_only and not self.is_admin:
                    raise HTTPError(403)
                else:
                    user_handler(self, *args, **kwargs)
            elif not self.current_user_id:
                raise HTTPError(403)
            elif admin_only and not self.is_admin:
                raise HTTPError(403)
            else:
                user_handler(self, *args, **kwargs)
        return authorized_handler
    return wrap
tut.py 文件源码 项目:SanicMongo 作者: beepaste 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def put(self, operation):
        """Método responsável por tratar requisições PUT.
        Aqui funciona assim: Pode-se enviar PUT requests para
        ``/``, ``/putpost`` ou ``/putcomment``,
        sendo ``/`` ou ``/putpost`` para cadastrar
        um post e ``/putcomment`` para cadastrar um comentário
        """
        if not operation:
            operation = 'putpost'

        operations = {'putpost': self.put_post,
                      'putcomment': self.put_comment}

        if operation not in operations:
            raise HTTPError(404)

        method = operations.get(operation)
        ret = yield method()
        self.write(ret)
graphql_handler.py 文件源码 项目:react-tornado-graphql-example 作者: yatsu 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def error_response(func):
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        try:
            result = func(self, *args, **kwargs)
        except Exception as ex:
            if not isinstance(ex, (web.HTTPError, ExecutionError, GraphQLError)):
                tb = ''.join(traceback.format_exception(*sys.exc_info()))
                app_log.error('Error: {0} {1}'.format(ex, tb))
            self.set_status(error_status(ex))
            error_json = json_encode({'errors': error_format(ex)})
            app_log.debug('error_json: %s', error_json)
            self.write(error_json)
        else:
            return result

    return wrapper
register.py 文件源码 项目:noc-orchestrator 作者: DirceuSilvaLabs 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def post(self):
        # ???? TODO: ?????
        mobile = self.get_argument('mobile')
        pwd = self.get_argument('pwd')
        users = yield User.objects.filter(mobile=mobile).find_all()
        if len(users) != 0:
            # ?????????
            raise HTTPError(**errors.status_21)

        school_id = self.get_argument('school_id')
        self.vaildate_id(school_id)

        school = yield School.objects.get(self.get_argument('school_id'))
        self.check_none(school)

        # ????
        user = User(mobile=mobile, password=pwd, nickname='test', school_id=ObjectId(school_id))
        yield user.save()

        user = user.to_dict()
        user['token'] = token_manager.create_token(str(user['id']))
        self.write_json(user)
__init__.py 文件源码 项目:jgscm 作者: src-d 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
        }
__init__.py 文件源码 项目:jgscm 作者: src-d 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
        }
__init__.py 文件源码 项目:jgscm 作者: src-d 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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")
handlers_async.py 文件源码 项目:mygene.info 作者: biothings 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def get(self, geneid=None):
        '''/gene/<geneid>
           geneid can be entrezgene, ensemblgene, retired entrezgene ids.
           /gene/1017
           /gene/1017?fields=symbol,name
           /gene/1017?fields=symbol,name,reporter.HG-U133_Plus_2
        '''
        if geneid:
            kwargs = self.get_query_params()
            kwargs.setdefault('scopes', 'entrezgene,ensemblgene,retired')
            kwargs.setdefault('species', 'all')
            gene = yield Task(self.esq.get_gene2, geneid, **kwargs)
            if gene:
                self.return_json(gene)
                self.ga_track(event={'category': 'v2_api',
                                     'action': 'gene_get'})
            else:
                raise HTTPError(404)
        else:
            raise HTTPError(404)
handlers.py 文件源码 项目:toshi-id-service 作者: toshiapp 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def get(self, address, hash, format, include_body=True):

        format = format.upper()
        if format not in ['PNG', 'JPG', 'JPEG']:
            raise HTTPError(404)
        if format == 'JPG':
            format = 'JPEG'

        async with self.db:
            if hash is None:
                row = await self.db.fetchrow("SELECT * FROM avatars WHERE toshi_id = $1 AND format = $2 ORDER BY last_modified DESC",
                                             address, format)
            else:
                row = await self.db.fetchrow(
                    "SELECT * FROM avatars WHERE toshi_id = $1 AND format = $2 AND substring(hash for {}) = $3"
                    .format(AVATAR_URL_HASH_LENGTH),
                    address, format, hash)

        if row is None or row['format'] != format:
            raise HTTPError(404)

        await self.handle_file_response(row['img'], "image/{}".format(format.lower()),
                                        row['hash'], row['last_modified'])
rps.py 文件源码 项目:incubator-milagro-mfa-server 作者: apache 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def get_time_permits(self, hash_mpin_id_hex, signature):
        # Get time permit from the local D-TA
        url = url_concat(
            "{0}/{1}".format(options.DTALocalURL.rstrip("/"), "timePermits"), {
                'hash_mpin_id': hash_mpin_id_hex,
                'signature': signature,
                'count': random.randint(PERMITS_MIN, PERMITS_MAX) if options.cacheTimePermits else 1})
        response = yield self.http_client.fetch(url)

        if response.error:
            log.error("DTA timePermit failed, URL: {0}. Code: {1}, Reason: {2}".format(url, response.code, response.reason))
            raise HTTPError(500)

        if response.body:
            try:
                response_data = json.loads(response.body)
                raise tornado.gen.Return(response_data["timePermits"])
            except (ValueError, KeyError):
                log.error("DTA /timePermit Failed. Invalid JSON response".format(
                    response.body))
                raise HTTPError(500)
rps.py 文件源码 项目:incubator-milagro-mfa-server 作者: apache 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_time_permit(self, hash_mpin_id_hex, date_epoch, signature):
        """Get time permit from cache or request new."""
        if options.cacheTimePermits:
            time_permit_item = self.storage.find(time_permit_id=hash_mpin_id_hex, time_permit_date=date_epoch)
            if time_permit_item:
                # Get time permit from cache
                raise tornado.gen.Return(time_permit_item.time_permit)

        # No cached time permits for this mpin id, request new from D-TA
        time_permits = yield self.get_time_permits(hash_mpin_id_hex, signature)
        if options.cacheTimePermits:
            self.cache_time_permits(time_permits, hash_mpin_id_hex)

        # Return the one for today
        if str(date_epoch) not in time_permits:
            log.error("DTA /timePermit Failed. No time permit for today")
            raise HTTPError(500)
        raise tornado.gen.Return(time_permits[str(date_epoch)])
rps.py 文件源码 项目:incubator-milagro-mfa-server 作者: apache 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def get(self, mpin_id):
        # Check revocation status of mpin id.
        if options.RPAPermitUserURL:
            response = yield self.http_client.fetch(
                url_concat(options.RPAPermitUserURL, {"mpin_id": mpin_id}),
                raise_error=False)

            if response.code != 200:
                # RPA rejects this mpin id
                raise HTTPError(response.code)

        hash_mpin_id_hex = hashlib.sha256(mpin_id.decode("hex")).hexdigest()
        today_epoch = secrets.today()
        signature = signMessage(hash_mpin_id_hex, Keys.app_key)
        time_permit = yield self.get_time_permit(hash_mpin_id_hex, today_epoch, signature)

        self.set_header("Cache-Control", "no-cache")
        self.finish({
            "date": today_epoch,
            "signature": signature,
            "storageId": hash_mpin_id_hex,
            'message': "M-Pin Time Permit Generated",
            'timePermit': time_permit,
            'version': VERSION,
        })
abc.py 文件源码 项目:xiaodi 作者: shenaishiren 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def write_error(self, status_code, **kwargs):
        try:
            exc_info = kwargs.pop('exc_info')
            e = exc_info[1]
            if isinstance(e, HTTPAPIError):
                pass
            elif isinstance(e, HTTPError):
                e = HTTPAPIError(BAD_REQUEST_ERROR, e.log_message, e.status_code)
            else:
                e = HTTPAPIError(INTERNAL_SERVER_ERROR, str(e), 500)
            self.set_status(status_code)
            self._async_write(str(e))
        except Exception as e:
            LOG.exception(str(e))
            return super(BaseApiHandler, self).write_error(status_code, **kwargs)

    # private method
handlers.py 文件源码 项目:nbrsessionproxy 作者: jupyterhub 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def proxy(self, port, path):
        if not path.startswith('/'):
            path = '/' + path

        # if we're in 'starting' let's wait a while
        for i in range(5):
            if not self.state.get('starting', False):
                break
            # Simple exponential backoff
            wait_time = max(1.4 ** i, 5)
            self.log.debug('Waiting {} before checking if rstudio is up'.format(wait_time))
            yield gen.sleep(wait_time)
        else:
            raise web.HTTPError('could not start rsession in time', status_code=500)

        # FIXME: try to not start multiple processes at a time with some locking here
        if 'proc' not in self.state:
            self.log.info('No existing process rsession process found')
            yield self.start_process()

        return (yield super().proxy(self.port, path))
handlers.py 文件源码 项目:jupyter_tensorboard 作者: lspvic 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get(self, name, path):

        if path == "":
                uri = self.request.path + "/"
                if self.request.query:
                    uri += "?" + self.request.query
                self.redirect(uri, permanent=True)
                return

        self.request.path = (
            path if self.request.query
            else "%s?%s" % (path, self.request.query))

        manager = self.settings["tensorboard_manager"]
        if name in manager:
            tb_app = manager[name].tb_app
            WSGIContainer(tb_app)(self.request)
        else:
            raise web.HTTPError(404)
public_server.py 文件源码 项目:JupyterHubDocker 作者: jbkrause 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def download(self, fspath, mime_type=None):

        if os.path.exists(fspath):
            if mime_type is None:
                mime_type, encoding = mimetypes.guess_type(fspath)
            if mime_type is None:
                mime_type = "text/plain"
            base_filename = os.path.basename(fspath)
            self.set_header('Content-Type', mime_type)
            self.set_header('Content-Disposition', 'attachment; filename="%s"' % base_filename)
            fp = open(fspath, "rb")
            try:
                self.write(fp.read())
            except:
                print("IO error reading: " + fspath)
            finally:
                fp.close()
        else:
            raise web.HTTPError(404)
products.py 文件源码 项目:fg21sim 作者: liweitianux 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def validate_absolute_path(self, root, absolute_path):
        """
        Validate and return the absolute path.

        Credit:
        https://github.com/tornadoweb/tornado/blob/master/tornado/web.py
        """
        root = os.path.abspath(root)
        if not root.endswith(os.path.sep):
            root += os.path.sep
        if not (absolute_path + os.path.sep).startswith(root):
            # Only files under the specified root can be accessed
            raise HTTPError(403, "%s is not in the root directory", self.path)
        if not os.path.exists(absolute_path):
            raise HTTPError(404)
        if not os.path.isfile(absolute_path):
            raise HTTPError(403, "%s is not a file", self.path)
        return absolute_path
permission.py 文件源码 项目:2016-NCTU_find_roommate-API-server 作者: Microsheep 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def refresh_token(method):
    # Decorate method to refresh token time after request
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        try:
            now = JwtToken().validate(self.get_argument('token'))
            if len(now.keys()) != 0:
                TIME_UNUSED = 5*60*60
                t = int(time.time()) + TIME_UNUSED
                j = JwtToken().generate({"uid": now['uid'], "type": now['type'], "time": t})
                self.res['token'] = j.decode("utf-8")
        except:
            self.set_status(401)
            self.res['error'] = "Token Refresh Error"
            self.write_json()
            self.finish()
            raise HTTPError(401)
        return method(self, *args, **kwargs)
    return wrapper
handler.py 文件源码 项目:pyfdfs 作者: w4n9H 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def get(self, domain, file_name):
        try:
            if file_name:
                query_status, query_result = self.mysql_client.raw_sql_fdfs_download(file_name.strip(), domain.strip())
                if query_status:
                    self.redirect(url=query_result, permanent=False, status=None)
                else:
                    # logging.error("file: %s, domain: %s , error: %s" % (file_name, domain, query_result))
                    raise HTTPError(404)
            else:
                raise HTTPError(404)
        except:
            raise HTTPError(404)
        finally:
            self.mysql_client.close_connetc()
            # pass
handler.py 文件源码 项目:Young 作者: shiyanhui 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def post(self):
        '''??????'''

        form = StatusMoreForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        page = form.page.data

        skip = HOME_SETTINGS['status_number_per_page'] * page
        limit = HOME_SETTINGS['status_number_per_page']

        status_list = yield StatusDocument.get_friends_status_list(
            self.current_user['_id'], skip=skip, limit=limit
        )

        html = ''.join(
            self.render_string(
                'home/template/status/status-list-item.html',
                status=status
            ) for status in status_list
        )

        self.write_json({'html': html, 'page': page + 1})
handler.py 文件源码 项目:Young 作者: shiyanhui 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def post(self):
        form = StatusCommentsForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        status_id = form.status_id.data

        status = yield StatusDocument.find_one({
            '_id': ObjectId(status_id)
        })
        if not status:
            raise HTTPError(404)

        status_comment_list = yield StatusCommentDocument.get_comment_list(
            status_id, self.current_user['_id']
        )

        html = self.render_string(
            'home/template/status/status-comment-list.html',
            status=status,
            status_comment_list=status_comment_list
        )

        self.write_json({'html': html})
handler.py 文件源码 项目:Young 作者: shiyanhui 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get(self):
        topic_id = self.get_argument('topic_id', None)
        if not topic_id:
            raise HTTPError(404)

        topic = yield TopicDocument.get_topic(
            topic_id, self.current_user['_id']
        )
        if not topic or topic['author']['_id'] != self.current_user['_id']:
            raise HTTPError(404)

        self.render(
            'community/template/topic-new.html',
            action="edit",
            topic=topic
        )
handler.py 文件源码 项目:Young 作者: shiyanhui 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def post(self):
        form = TopicCommentMoreForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        page = form.page.data
        topic_id = form.topic_id.data

        skip = COMMUNITY_SETTINGS['topic_comment_number_per_page'] * page
        limit = COMMUNITY_SETTINGS['topic_comment_number_per_page']

        comment_list = yield TopicCommentDocument.get_comment_list(
            topic_id, skip, limit
        )

        html = ''.join(
            self.render_string(
                'community/template/topic-comment-list-item.html',
                comment=comment
            ) for comment in comment_list
        )

        self.write_json({'html': html, 'page': page + 1})
handler.py 文件源码 项目:Young 作者: shiyanhui 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def post(self):
        form = ProfileCoverSetForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        profile_cover_id = form.profile_cover_id.data
        profile_cover = yield OfficialProfileCoverDocument.find_one({
            '_id': ObjectId(profile_cover_id)
        })

        if not profile_cover:
            raise HTTPError(404)

        cover = DBRef(
            OfficialProfileCoverDocument.meta['collection'],
            ObjectId(profile_cover['_id'])
        )
        yield UserSettingDocument.set_profile_cover(
            self.current_user['_id'], cover
        )

        raise gen.Return()
handler.py 文件源码 项目:Young 作者: shiyanhui 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def post(self):
        form = PrivateSetForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        require_verify_when_add_friend = form.require_verify_when_add_friend.data
        allow_stranger_visiting_profile = form.allow_stranger_visiting_profile.data
        allow_stranger_chat_with_me = form.allow_stranger_chat_with_me.data
        enable_leaving_message = form.enable_leaving_message.data

        yield UserSettingDocument.update(
            {'user': DBRef(
                UserDocument.meta['collection'],
                ObjectId(self.current_user['_id'])
            )},
            {'$set': {
                'require_verify_when_add_friend': require_verify_when_add_friend,
                'allow_stranger_visiting_profile': allow_stranger_visiting_profile,
                'allow_stranger_chat_with_me': allow_stranger_chat_with_me,
                'enable_leaving_message': enable_leaving_message
            }}
        )

        self.finish()
handler.py 文件源码 项目:Young 作者: shiyanhui 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def post(self):
        form = NotificationSetForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        email_notify_when_offline = form.email_notify_when_offline.data

        yield UserSettingDocument.update(
            {'user': DBRef(
                UserDocument.meta['collection'],
                ObjectId(self.current_user['_id'])
            )},
            {'$set': {'email_notify_when_offline': email_notify_when_offline}}
        )

        self.finish()
status.py 文件源码 项目:Young 作者: shiyanhui 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def post(self):
        form = StatusMoreForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        page = form.page.data

        skip = PROFILE_SETTINGS['status_number_per_page'] * page
        limit = PROFILE_SETTINGS['status_number_per_page']
        status_list = yield StatusDocument.get_status_list(
            self.current_user['_id'],
            self.current_user['_id'],
            skip=skip, limit=limit
        )

        html = ''.join(
            self.render_string(
                'profile/template/status/status-list-item.html',
                status=status
            ) for status in status_list
        )
        self.write_json({'html': html, 'page': page + 1})
profile.py 文件源码 项目:Young 作者: shiyanhui 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def post(self):
        form = LeaveMessageMoreForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        page = form.page.data
        user_id = form.user_id.data

        skip = PROFILE_SETTINGS['leave_message_number_per_page'] * page
        limit = PROFILE_SETTINGS['leave_message_number_per_page']

        leave_message_list = yield LeaveMessageDocument.get_leave_message_list(
            user_id, self.current_user['_id'], skip=skip, limit=limit
        )

        html = ''.join(
            self.render_string(
                'profile/template/leavemessage/leavemessage-list-item.html',
                leave_message=leave_message
            )
            for leave_message in leave_message_list
        )
        self.write_json({'html': html, 'page': page + 1})
profile.py 文件源码 项目:Young 作者: shiyanhui 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def post(self):
        form = FriendRequestForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        user_id = form.user_id.data

        yield MessageDocument.remove({
            'sender': DBRef(
                UserDocument.meta['collection'],
                ObjectId(user_id)
            ),
            'recipient': DBRef(
                UserDocument.meta['collection'],
                ObjectId(self.current_user['_id'])
            ),
            'message_type': MessageTopic.FRIEND_REQUEST_NEW})


问题


面经


文章

微信
公众号

扫码关注公众号