本文整理汇总了Python中werkzeug.abort函数的典型用法代码示例。如果您正苦于以下问题:Python abort函数的具体用法?Python abort怎么用?Python abort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了abort函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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({})
示例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)
示例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
)
示例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)
示例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)
示例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))
示例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
示例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
示例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
示例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)
示例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)
示例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])
示例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)
示例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)