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

Python werkzeug.abort函数代码示例

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

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



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

示例1: abort

def abort(send):
    """
        An enhanced version of Werkzeug's abort.  `send` is handled differently
        based on what it is:

        int: assumed to be a HTTP status code; not all codes supported by
            default, see the Werkzeug documentation for an explanation.
        string/unicode: will put the string as the body of a response and send
            it.
        callable: assume its a Response object or other WSGI application; wrap
            in proxy HTTPException and raise it;
        anything else: pformat, escape, wrap in <pre> tags, and treat like
            string/unicode above.
    """
    # this is a circular import if done at the module level
    from blazeweb.wrappers import Response

    response_body = reindent("""
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    <title>abort() Response</title>
    <h1 style="margin-bottom: 25px">abort() Response</h1>

    %s""".strip(), 0)

    if isinstance(send, int) or hasattr(send, '__call__'):
        response = send
    elif isinstance(send, six.string_types):
        response = Response(response_body % escape(send))
    else:
        response = Response(response_body % ('<pre>%s</pre>' % escape(pformat(send))))
    werkzeug.abort(response)
开发者ID:level12,项目名称:blazeweb,代码行数:31,代码来源:__init__.py


示例2: test_proxy_exception

def test_proxy_exception():
    """Proxy exceptions"""
    orig_resp = Response('Hello World')
    try:
        abort(orig_resp)
    except exceptions.HTTPException, e:
        resp = e.get_response({})
开发者ID:marchon,项目名称:checkinmapper,代码行数:7,代码来源:test_exceptions.py


示例3: new_password

    def new_password(cls):
        """Create a new password

        .. tip::

            Unlike change password this does not demand the old password.
            And hence this method will check in the session for a parameter
            called allow_new_password which has to be True. This acts as a
            security against attempts to POST to this method and changing
            password.

            The allow_new_password flag is popped on successful saving

        This is intended to be used when a user requests for a password reset.
        """
        form = NewPasswordForm(request.form)

        if request.method == 'POST' and form.validate():
            if not session.get('allow_new_password', False):
                current_app.logger.debug('New password not allowed in session')
                abort(403)

            cls.write(
                [request.nereid_user],
                {'password': form.password.data}
            )
            session.pop('allow_new_password')
            flash(_(
                'Your password has been successfully changed! '
                'Please login again'))
            session.pop('user')
            return redirect(url_for('nereid.website.login'))

        return render_template('new-password.jinja', password_form=form)
开发者ID:baijum,项目名称:nereid,代码行数:34,代码来源:party.py


示例4: new_password

    def new_password(self, sign, max_age=24 * 60 * 60):
        """Create a new password

        This is intended to be used when a user requests for a password reset.
        The link sent out to reset the password will be a timestamped sign
        which is validated for max_age before allowing the user to set the
        new password.
        """
        form = NewPasswordForm(request.form)

        if request.method == 'POST' and form.validate():
            try:
                unsigned = self._serializer.loads(
                    self._signer.unsign(sign, max_age=max_age),
                    salt='reset-password'
                )
            except SignatureExpired:
                flash(_("The password reset link has expired"))
            except BadSignature:
                flash(_('Invalid reset password code'))
            else:
                if not self.id == unsigned:
                    current_app.logger.debug('Invalid reset password code')
                    abort(403)

                self.write([self], {'password': form.password.data})
                flash(_(
                    'Your password has been successfully changed! '
                    'Please login again'))
            return redirect(url_for('nereid.website.login'))

        return render_template(
            'new-password.jinja', password_form=form, sign=sign, user=self
        )
开发者ID:sharoonthomas,项目名称:nereid,代码行数:34,代码来源:user.py


示例5: new_password

    def new_password(self):
        """Create a new password

        .. tip::

            Unlike change password this does not demand the old password.
            And hence this method will check in the session for a parameter
            called allow_new_password which has to be True. This acts as a
            security against attempts to POST to this method and changing
            password.

            The allow_new_password flag is popped on successful saving

        This is intended to be used when a user requests for a password reset.
        """
        form = NewPasswordForm(request.form)

        if request.method == "POST" and form.validate():
            if not session.get("allow_new_password", False):
                current_app.logger.debug("New password not allowed in session")
                abort(403)

            self.write(request.nereid_user.id, {"password": form.password.data})
            session.pop("allow_new_password")
            flash(_("Your password has been successfully changed! " "Please login again"))
            session.pop("user")
            return redirect(url_for("nereid.website.login"))

        return render_template("new-password.jinja", password_form=form)
开发者ID:shalabhaggarwal,项目名称:trytond-nereid,代码行数:29,代码来源:party.py


示例6: get_by_key_name_or_404

def get_by_key_name_or_404(model, key_name, parent=None):
    """Returns a model instance fetched by key name or raises a 404 Not Found
    error. Example::

        from tipfy import RequestHandler
        from tipfy.appengine.db import get_by_key_name_or_404
        from mymodels import Contact

        class EditContactHandler(RequestHandler):
            def get(self, **kwargs):
                contact = get_by_key_name_or_404(Contact,
                    kwargs['contact_key_name'])

                # ... continue processing contact ...

    This function derives from `Kay <http://code.google.com/p/kay-framework/>`_.

    :param model:
        A ``db.Model`` class to load an entity.
    :param key_name:
        A key name from a ``db.Key`` (a string).
    :param parent:
        The parent entity for the requested entities, as a Model
        instance or Key instance, or None (the default) if the requested
        entities do not have a parent.
    :returns:
        A ``db.Model`` instance.
    """
    obj = model.get_by_key_name(key_name, parent=parent)
    if obj:
        return obj

    abort(404)
开发者ID:AmirS2,项目名称:tipfy,代码行数:33,代码来源:__init__.py


示例7: http_redirect

 def http_redirect(self, url, code=302):
     """ Raise a simple redirect exception. """
     # werkzeug >= 0.6 does iri-to-uri transform if it gets unicode, but our
     # url is already url-quoted, so we better give it str to have same behaviour
     # with werkzeug 0.5.x and 0.6.x:
     url = str(url) # if url is unicode, it should contain ascii chars only
     abort(redirect(url, code=code))
开发者ID:graphingwiki,项目名称:gwiki-with-moin,代码行数:7,代码来源:contexts.py


示例8: process_action_method

    def process_action_method(self):
        # now call our "action" methods, only one of these methods will be
        # called depending on the type of request and the attributes
        # available on the view
        http_method = rg.request.method.lower()
        method_name = None

        # handle XHR (Ajax) requests
        if rg.request.is_xhr:
            method_name = self.http_method_map['_xhr_']
            # if the method isn't present, treat it as a non-xhr request
            if method_name and not hasattr(self, method_name):
                method_name = None

        # handle based on HTTP request method type
        if not method_name and http_method in self.http_method_map:
            method_name = self.http_method_map[http_method]

        # if there wasn't a method name found or the method name doesn't exist
        # as a method, then try the default handler
        if method_name is None or not hasattr(self, method_name):
            method_name = self.http_method_map.get('_default_')
            if method_name is None or not hasattr(self, method_name):
                # default fallback failed, we can't handle this request method
                abort(405)

        # call the method that responds to this request method type
        retval = self._call_with_expected_args(getattr(self, method_name))

        # we allow the views to work on self.retval directly, but if the
        # action method returns a non-None value, it takes precedence
        if retval is not None:
            self.retval = retval
开发者ID:level12,项目名称:blazeweb,代码行数:33,代码来源:views.py


示例9: send_file_partial

def send_file_partial(filePath):
    range_header = request.range
    if not range_header: return send_file(filePath)

    if range_header.units != 'bytes' or len(range_header.ranges) != 1:
        abort(400)

    size = os.path.getsize(filePath)
    content_range = range_header.make_content_range(size)

    app.logger.debug("Send file %s: %s" % (content_range, filePath))

    length = content_range.stop - content_range.start

    def data_generator(length=length):
        buffer_size = 8192
        with open(filePath, 'rb') as fp:
            fp.seek(content_range.start)
            while length > 0:
                data = fp.read(min(length, buffer_size))
                length -= len(data)
                yield data

    rv = Response(data_generator(),
        206,
        mimetype=mimetypes.guess_type(filePath)[0],
        direct_passthrough=True)

    rv.headers.add('Content-Range', content_range.to_header())

    return rv
开发者ID:opencv-infrastructure,项目名称:opencv-runbox,代码行数:31,代码来源:helpers.py


示例10: request

    def request(self, user_obj, **kw):
        u = None
        # always revalidate auth
        if user_obj and user_obj.auth_method == self.name:
            user_obj = None
        # something else authenticated before us
        if user_obj:
            return user_obj, True

        auth = request.authorization
        if auth and auth.username and auth.password is not None:
            logging.debug("http basic auth, received username: {0!r} password: {1!r}".format(
                auth.username, auth.password))
            u = user.User(name=auth.username.decode(self.coding),
                          password=auth.password.decode(self.coding),
                          auth_method=self.name, auth_attribs=[], trusted=self.trusted)
            logging.debug("user: {0!r}".format(u))

        if not u or not u.valid:
            from werkzeug import Response, abort
            response = Response(_('Please log in first.'), 401,
                                {'WWW-Authenticate': 'Basic realm="{0}"'.format(self.realm)})
            abort(response)

        logging.debug("u: {0!r}".format(u))
        if u and self.autocreate:
            logging.debug("autocreating user")
            u.create_or_update()
        if u and u.valid:
            logging.debug("returning valid user {0!r}".format(u))
            return u, True  # True to get other methods called, too
        else:
            logging.debug("returning {0!r}".format(user_obj))
            return user_obj, True
开发者ID:YelaSeamless,项目名称:moin-2.0,代码行数:34,代码来源:http.py


示例11: edit_address

    def edit_address(cls, address=None):
        """
        Edit an Address

        POST will update an existing address.
        GET will return a existing address edit form.

        .. version_changed:: 3.0.3.0

            For creating new address use the create_address handled instead of
            this one. The functionality would be deprecated in 3.2.X

        :param address: ID of the address
        """
        if address is None:
            warnings.warn(
                "Address creation will be deprecated from edit_address handler."
                " Use party.address.create_address instead",
                DeprecationWarning
            )
            return cls.create_address()

        form = cls.get_address_form()

        if address not in (a.id for a in request.nereid_user.party.addresses):
            # Check if the address is in the list of addresses of the
            # current user's party
            abort(403)

        address = cls(address)

        if request.method == 'POST' and form.validate():
            party = request.nereid_user.party
            cls.write([address], {
                'name': form.name.data,
                'street': form.street.data,
                'streetbis': form.streetbis.data,
                'zip': form.zip.data,
                'city': form.city.data,
                'country': form.country.data,
                'subdivision': form.subdivision.data,
            })
            if form.email.data:
                party.add_contact_mechanism_if_not_exists(
                    'email', form.email.data
                )
            if form.phone.data:
                party.add_contact_mechanism_if_not_exists(
                    'phone', form.phone.data
                )
            return redirect(url_for('party.address.view_address'))

        elif request.method == 'GET' and address:
            # Its an edit of existing address, prefill data
            form = cls.get_address_form(address)

        return render_template('address-edit.jinja', form=form, address=address)
开发者ID:priyankajain18,项目名称:nereid,代码行数:57,代码来源:party.py


示例12: _admin_required

def _admin_required(handler):
    """Implementation for admin_required and AdminRequiredMiddleware."""
    auth = handler.auth

    if not auth.session:
        return handler.redirect(auth.login_url())

    if not auth.user or not auth.user.is_admin:
        abort(403)
开发者ID:peper,项目名称:tipfy,代码行数:9,代码来源:__init__.py


示例13: subdivision_list

    def subdivision_list():
        """
        Return the list of states for given country
        """
        country = int(request.args.get("country", 0))
        if country not in [c.id for c in request.nereid_website.countries]:
            abort(404)

        Subdivision = Pool().get("country.subdivision")
        subdivisions = Subdivision.search([("country", "=", country)])
        return jsonify(result=[{"id": s.id, "name": s.name, "code": s.code} for s in subdivisions])
开发者ID:rahulsukla,项目名称:nereid,代码行数:11,代码来源:routing.py


示例14: remove_address

    def remove_address(self):
        """
        Make address inactive if user removes the address from address book.
        """
        if self.party == current_user.party:
            self.active = False
            self.save()
            flash(_('Address has been deleted successfully!'))
            if request.is_xhr:
                return jsonify(success=True)
            return redirect(request.referrer)

        abort(403)
开发者ID:priyankajain18,项目名称:nereid,代码行数:13,代码来源:party.py


示例15: remove

    def remove(self):
        """
        DELETE: Removes the current contact mechanism
        """
        ContactMechanism = Pool().get("party.contact_mechanism")

        if self.party == request.nereid_user.party:
            ContactMechanism.delete([self])
        else:
            abort(403)
        if request.is_xhr:
            return jsonify({"success": True})
        return redirect(request.referrer)
开发者ID:GauravButola,项目名称:nereid,代码行数:13,代码来源:party.py


示例16: subdivision_list

    def subdivision_list(cls):
        """
        Return the list of states for given country
        """
        Subdivision = Pool().get('country.subdivision')

        country = int(request.args.get('country', 0))
        if country not in [c.id for c in request.nereid_website.countries]:
            abort(404)
        subdivisions = Subdivision.search([('country', '=', country)])
        return jsonify(
            result=[s.serialize() for s in subdivisions]
        )
开发者ID:priyankajain18,项目名称:nereid,代码行数:13,代码来源:website.py


示例17: nereid_user

    def nereid_user(self):
        """Fetch the browse record of current user or None."""
        NereidUser = current_app.pool.get('nereid.user')
        if 'user' not in session:
            return NereidUser(self.nereid_website.guest_user.id)

        try:
            nereid_user, = NereidUser.search([('id', '=', session['user'])])
        except ValueError:
            session.pop('user')
            abort(redirect(url_for('nereid.website.login')))
        else:
            return nereid_user
开发者ID:raimonesteve,项目名称:nereid,代码行数:13,代码来源:wrappers.py


示例18: edit_address

    def edit_address(cls, address=None):
        """
        Edit an Address

        POST will update an existing address.
        GET will return a existing address edit form.

        .. version_changed:: 3.0.3.0

            For creating new address use the create_address handled instead of
            this one. The functionality would be deprecated in 3.2.X

        :param address: ID of the address
        """
        if address is None:
            warnings.warn(
                "Address creation will be deprecated from edit_address handler."
                " Use party.address.create_address instead",
                DeprecationWarning
            )
            return cls.create_address()

        address = cls(address)
        if address.party != current_user.party:
            # Check if the address belong to party
            abort(403)

        form = cls.get_address_form(address)

        if request.method == 'POST' and form.validate_on_submit():
            party = current_user.party
            cls.write([address], {
                'name': form.name.data,
                'street': form.street.data,
                'streetbis': form.streetbis.data,
                'zip': form.zip.data,
                'city': form.city.data,
                'country': form.country.data,
                'subdivision': form.subdivision.data,
            })
            if form.phone.data:
                phone = party.add_contact_mechanism_if_not_exists(
                    'phone', form.phone.data
                )
                cls.write([address], {
                    'phone_number': phone.id
                })
            return redirect(url_for('party.address.view_address'))

        return render_template('address-edit.jinja', form=form, address=address)
开发者ID:2cadz,项目名称:nereid-checkout,代码行数:50,代码来源:checkout.py


示例19: get

    def get(self, filename):
        try:
            resource = Resource(RetrieveResource(request))
            try:
                current_app.storages.retrieveResource(resource)
                response = x_accel_redirect(resource.location, resource.size)
                return response
            except StorageUnavailableError as e:
                abort(503)

        except HTTPException as e:
            # print(e)
            raise
        except Exception as e:
            abort(500)
开发者ID:xmm,项目名称:fstore,代码行数:15,代码来源:image.py


示例20: _dispatch_request

    def _dispatch_request(self, req):
        """
        Implement the nereid specific _dispatch
        """

        language = 'en_US'
        if req.nereid_website:
            # If this is a request specific to a website
            # then take the locale from the website
            language = req.nereid_locale.language.code

        with Transaction().set_context(language=language):

            # pop locale if specified in the view_args
            req.view_args.pop('locale', None)

            # otherwise dispatch to the handler for that endpoint
            if req.url_rule.endpoint in self.view_functions:
                meth = self.view_functions[req.url_rule.endpoint]
            else:
                model, method = req.url_rule.endpoint.rsplit('.', 1)
                meth = getattr(Pool().get(model), method)

            if not hasattr(meth, 'im_self') or meth.im_self:
                # static or class method
                result = meth(**req.view_args)
            else:
                # instance method, extract active_id from the url
                # arguments and pass the model instance as first argument
                model = Pool().get(req.url_rule.endpoint.rsplit('.', 1)[0])
                i = model(req.view_args.pop('active_id'))
                try:
                    i.rec_name
                except UserError:
                    # The record may not exist anymore which results in
                    # a read error
                    current_app.logger.debug(
                        "Record %s doesn't exist anymore." % i
                    )
                    abort(404)
                result = meth(i, **req.view_args)

            if isinstance(result, LazyRenderer):
                result = (
                    unicode(result), result.status, result.headers
                )

            return result
开发者ID:priyankajain18,项目名称:nereid,代码行数:48,代码来源:application.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python werkzeug.check_password_hash函数代码示例发布时间:2022-05-26
下一篇:
Python wepay.WePay类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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