• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python httpexceptions.exception_response函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyramid.httpexceptions.exception_response函数的典型用法代码示例。如果您正苦于以下问题:Python exception_response函数的具体用法?Python exception_response怎么用?Python exception_response使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: update

 def update(self):
     collection = self.context.__parent__
     try:
         values = self._update_values_from_request()
     except NotImplementedError: # pragma: no cover
         raise exception_response(501)
     except InvalidResource, ex:
         raise exception_response(
             400,
             body=unicode(ex)
         )
开发者ID:yoshrote,项目名称:columns2,代码行数:11,代码来源:base.py


示例2: validation_context

def validation_context(request, response=None):
    try:
        yield
    except (
        exceptions.RequestValidationError,
        exceptions.ResponseValidationError,
        exceptions.PathNotFoundError,
    ):
        raise exception_response(206)
    except Exception:
        raise exception_response(400)
开发者ID:macisamuele,项目名称:pyramid_swagger,代码行数:11,代码来源:request_test.py


示例3: request_params

def request_params(request):
    try:
        params = NestedMultiDict(request.GET, request.POST)
    except UnicodeDecodeError:
        response = exception_response(422)
        response.body = dumps(error_handler(request, response.code, {"location": "body", "name": "data", "description": "could not decode params"}))
        response.content_type = 'application/json'
        raise response
    except Exception, e:
        response = exception_response(422)
        response.body = dumps(error_handler(request, response.code, {"location": "body", "name": str(e.__class__.__name__), "description": str(e)}))
        response.content_type = 'application/json'
        raise response
开发者ID:openprocurement,项目名称:openprocurement.documentservice,代码行数:13,代码来源:utils.py


示例4: login

def login(request):
    user_payload = request.json
    user = User.query.filter_by(username=user_payload["username"]).one_or_none()
    if not user:
        return exception_response(404, detail="Usuario nao encontrado")

    if not user.verify_password(user_payload["password"]):
        return exception_response(404, detail="Password invalido")

    claims = {"username": user.username, "email": user.email}
    policy = request.registry.queryUtility(IAuthenticationPolicy)
    token = policy.encode_jwt(request, claims=claims)
    token = token.decode(encoding='UTF-8')

    return {"token": token}
开发者ID:marioidival,项目名称:giriapedia,代码行数:15,代码来源:auth.py


示例5: _invoke_subrequest

 def _invoke_subrequest(self, subreq):
     request = self.request
     subreq.session = request.session
     result = request.invoke_subrequest(subreq)
     if result.status_int > 400:
         raise exception_response(result.status_int)
     return result
开发者ID:ercchy,项目名称:h,代码行数:7,代码来源:api.py


示例6: error

    def error(self, code, message='', **kwargs):
        from pyramid.httpexceptions import exception_response

        raise exception_response(code, detail=message, headers={
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
        })
开发者ID:camptocamp,项目名称:tilecloud-chain,代码行数:7,代码来源:server.py


示例7: post

 def post(self):
     headers, body, status = self.oauth.create_revocation_response(
         self.request.url, self.request.method, self.request.POST, self.request.headers)
     if status == 200:
         return {}
     else:
         raise exception_response(status, body=body)
开发者ID:chinmaygghag,项目名称:h,代码行数:7,代码来源:auth.py


示例8: restore

def restore(request):
    """Restore a Post_History entry as the current version."""
    session = DBSession()
    context = get_context(request)
    uid = context['user'].uid

    id = request.matchdict['id']
    page = request.matchdict['page']
    version = request.matchdickt['version']

    try:
        entry = session.query(Post_History)\
                       .filter(Post_History.id == id)\
                       .filter(Post_History.page == page)\
                       .order_by(expression.desc(Post_History.changed_on))\
                       .limit(1)\
                       .offset(version)\
                       .one()
    except sqlalchemy.orm.exc.NoResultFound:
        return exception_response(404)

    current = session.query(Post).get(id)
    additions = entry.restore(context['user'], current)
    session.addall(additions)

    context['msg'].append('Post restored succesfully.')
    msgs = [('msg', m) for m in context['msg']]
    return HTTPFound(location=request.route_url('post', id=entry.id, page=page,
                                                _query=msgs))
开发者ID:pflarr,项目名称:basic_site,代码行数:29,代码来源:views.py


示例9: download_pgn

def download_pgn(request):
  pgn = request.rundb.get_pgn(request.matchdict['id'])
  if pgn == None:
    raise exc.exception_response(404)
  if '.pgn' in request.matchdict['id']:
    request.response.content_type = 'application/x-chess-pgn'
  return pgn
开发者ID:glinscott,项目名称:fishtest,代码行数:7,代码来源:api.py


示例10: forgot_password

def forgot_password(request):
    settings = request.registry.settings
    if not is_pwreminder_enabled(settings):
        raise exc.exception_response(503)
    handle_history(request)
    _ = request.translate
    config = Config(load(get_path_to_form_config('auth.xml')))
    form_config = config.get_form('forgot_password')
    form = Form(form_config, csrf_token=request.session.get_csrf_token(),
                translate=_)
    complete = False
    if request.POST:
        if form.validate(request.params):
            username = form.data.get('login')
            user = request_password_reset(username, request.db)
            if user:
                mailer = Mailer(request)
                recipient = user.profile[0].email
                token = user.reset_tokens[-1]
                subject = _('Password reset request')
                values = {'url': request.route_url('reset_password',
                                                   token=token),
                          'app_name': get_app_title(),
                          'email': settings['mail.default_sender'],
                          '_': _}
                mail = Mail([recipient],
                            subject,
                            template="password_reset_request",
                            values=values)
                mailer.send(mail)
            msg = _("Password reset token has been sent to the users "
                    "email address. Please check your email.")
            request.session.flash(msg, 'success')
            complete = True
    return {'form': form.render(), 'complete': complete}
开发者ID:ringo-framework,项目名称:ringo,代码行数:35,代码来源:auth.py


示例11: reset_password

def reset_password(request):
    settings = request.registry.settings
    if not is_pwreminder_enabled(settings):
        raise exc.exception_response(503)
    handle_history(request)
    _ = request.translate
    success = False
    token = request.matchdict.get('token')
    user, password = password_reset(token, request.db)
    if password:
        mailer = Mailer(request)
        recipient = user.profile[0].email
        subject = _('Password has been reseted')
        values = {'password': password,
                  'app_name': get_app_title(),
                  'email': settings['mail.default_sender'],
                  '_': _}
        mail = Mail([recipient],
                    subject,
                    template="password_reminder",
                    values=values)
        mailer.send(mail)
        msg = _("Password was resetted and sent to the users email address."
                " Please check your email.")
        success = True
    else:
        msg = _("Password was not resetted. Maybe the request"
                " token was not valid?")
    return {'msg': msg, 'success': success}
开发者ID:toirl,项目名称:ringo,代码行数:29,代码来源:auth.py


示例12: first_or_404

    def first_or_404(self):

        obj = self.first()
        if obj is None:
            raise exception_response(404)

        return obj
开发者ID:chuckbutler,项目名称:pyramid_mongoengine,代码行数:7,代码来源:__init__.py


示例13: get_giria

    def get_giria(self):
        """Return `giria` instance specific, by `state` and `giria` argument"""
        state = State.objects(code=self.state).first()
        giria = Giria.objects(state=state, giria=self.giria).first()

        if giria:
            return giria
        return exception_response(404)
开发者ID:fredericksilva,项目名称:giriapedia,代码行数:8,代码来源:views.py


示例14: create

 def create(self):
     try:
         values = self._create_values_from_request()
     except InvalidResource, ex:
         raise exception_response(
             400,
             body=unicode(ex),
         )
开发者ID:yoshrote,项目名称:columns2,代码行数:8,代码来源:base.py


示例15: get_one

    def get_one(cls, id_=None, query=None):
        if id_ is not None:
            query = cls.query.get(int(id_))

        if query == None:
            raise exception_response(404)
        else:
            return query
开发者ID:redguy-p2pu,项目名称:almir,代码行数:8,代码来源:meta.py


示例16: handle_error

 def handle_error(self, error):
     """Handles errors during parsing. Aborts the current HTTP request and
     responds with a 400 error.
     """
     logger.error(error)
     status_code = getattr(error, 'status_code', 400)
     data = getattr(error, 'data', {})
     raise exception_response(status_code, detail=text_type(error), **data)
开发者ID:venuatu,项目名称:webargs,代码行数:8,代码来源:pyramidparser.py


示例17: abort

def abort(request, code, body):
    # if no Accept header is set, then force */*, otherwise the exception
    # will be returned as text/plain, which causes easy_install/setuptools
    # to fail improperly
    request.headers.setdefault("Accept", "*/*")
    if "application/json" in request.headers.get("Accept", ""):
        apireturn(code, body)
    threadlog.error(body)
    raise exception_response(code, explanation=body, headers=meta_headers)
开发者ID:uceo,项目名称:uceo-2015,代码行数:9,代码来源:views.py


示例18: view_calculation

def view_calculation(request):
    """

    View for looking up calculations.

    """

    # Get the key
    matches = request.matchdict
    hashkey = matches['one']

    # Look up the key
    calculation = request.dbsession.query(models.Calculation) \
        .filter_by(hashkey=hashkey).first()

    if calculation is None:
        raise httpexceptions.exception_response(404)

    # Get from database
    # workpath = 'molcalc/data/'+hashkey + '/'

    # Check if calculation exists
    # if not os.path.exists(workpath):
    #     raise httpexceptions.exception_response(404)

    data = {}

    # with open(workpath + "start.sdf", 'r') as sdffile:
    #     sdfstr = sdffile.read()
    #     data['sdf'] = sdfstr
    #
    # molobj, status = cheminfo.sdfstr_to_molobj(sdfstr)
    # smiles = cheminfo.molobj_to_smiles(molobj)

    data["hashkey"] = calculation.hashkey
    data["smiles"] = calculation.smiles
    data["sdf"] = calculation.sdf
    data["svg"] = calculation.svg
    data["name"] = ""

    if hashkey == "404":
        raise httpexceptions.exception_response(404)

    return data
开发者ID:jensengroup,项目名称:molcalc,代码行数:44,代码来源:views.py


示例19: publish

def publish(context, request):
    topic_mode = request.POST.get('hub.mode', '')
    topic_urls = request.POST.getall('hub.url')

    bad_data = False
    error_msg = None

    if not topic_mode or topic_mode != 'publish':
        bad_data = True
        error_msg = "Invalid or unspecified mode."

    if not topic_urls:
        bad_data = True
        error_msg = "No topic URLs provided"

    hub = request.root

    for topic_url in topic_urls:
        try:
            hub.publish(topic_url)
        except ValueError:
            bad_data = True
            error_msg = "Malformed URL: %s" % topic_url

    if not bad_data:
        topics = [
            topic
            for (url, topic) in hub.topics.items()
            if url in topic_urls
        ]
        # XXX: Currently this is needed to ensure the listener gets
        #      the latest data.
        hub.fetch_content(topic_urls, request.application_url)
        hub.notify_listeners(topics)
        hub.fetch_all_content(request.application_url)

    if bad_data and error_msg:
        return exception_response(400,
                                  body=error_msg,
                                  headers=[('Content-Type', 'text/plain')])

    hub.notify_subscribers()

    return exception_response(204)
开发者ID:kofic,项目名称:PushHubCore,代码行数:44,代码来源:views.py


示例20: _invoke_subrequest

    def _invoke_subrequest(self, subreq):
        request = self.request
        token = api.token.TokenController(request)()
        subreq.headers['X-Annotator-Auth-Token'] = token
        result = request.invoke_subrequest(subreq)

        if result.status_int > 400:
            raise exception_response(result.status_int)

        return result
开发者ID:abigailricarte,项目名称:h,代码行数:10,代码来源:store.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python httpexceptions.HTTPFound类代码示例发布时间:2022-05-27
下一篇:
Python encode.urlencode函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap