本文整理汇总了Python中flask_restful.abort函数的典型用法代码示例。如果您正苦于以下问题:Python abort函数的具体用法?Python abort怎么用?Python abort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了abort函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: authenticate
def authenticate(self):
"""
Verifies user's token and his/her accessibility to requested resources.
Once token is validated, the role of user (flask.g.is_admin) and his/her scope
(flask.g.org_uuid_list) is set up for current request.
Raises Unauthorized when token is missing, invalid, expired or not signed by UAA
Raises Forbidden: when org guid is missing, invalid or user can't access this org
"""
if not self._uaa_public_key:
self._get_token_verification_key()
if any(exc in str(flask.request.path) for exc in self.auth_exceptions):
return
try:
token = self._get_token_from_request()
token_payload = self._parse_auth_token(token)
except (_MissingAuthToken, jwt.InvalidTokenError) as ex:
self._log.warn(str(ex))
abort(401)
flask.g.is_admin = self._is_admin(token_payload)
try:
flask.g.org_uuid_list = self._authorization.get_user_scope(
token,
flask.request,
flask.g.is_admin)
except (_InvalidOrgId, _CloudControllerConnectionError, _UserCantAccessOrg):
self._log.exception('Failed to authenticate the user.')
abort(403)
示例2: patch
def patch(self, record_id, tag_name):
"""A PATCH request.
:param record_id: the identifier of the record
:param tag_name: the name of the tag
"""
abort(405)
示例3: head
def head(self, record_id, tag_name):
"""A HEAD request.
:param record_id: the identifier of the record
:param tag_name: the name of the tag
"""
abort(405)
示例4: put
def put(self, name=None):
if not name:
abort(404, message="A group name is required.")
args = parser.parse_args()
group = Group.objects(name__iexact=name).first()
if not group:
abort(404, message="A group with that name does not exist.")
group.full_name=args['full_name']
if args['image'] and validate_file(args['image'].filename):
if group.image:
group.image.replace(args['image'], content_type=args['image'].content_type)
else:
group.image.put(args['image'], content_type=args['image'].content_type)
response = {
'name': group.name,
'full_name': group.full_name,
'image': str(group.image.grid_id) if group.image.grid_id else None
}
group.save()
return response
示例5: get
def get(self, item_id):
item = Item.query.get(item_id)
if item is None:
abort(404)
return item
示例6: get
def get(self, user, email):
target = models.User.lookup(email)
if not self.can('view', target, user):
restful.abort(403)
if target:
return {'courses': user.participations}
return {'courses': []}
示例7: wrapper
def wrapper(*args, **kwargs):
# Public methods do not need authentication
if not getattr(func, 'public', False) and not current_user.is_authenticated:
restful.abort(401)
# The login manager takes care of converting a token to a user.
kwargs['user'] = current_user
return func(*args, **kwargs)
示例8: func_wrapper
def func_wrapper(*args, **kwargs):
publication_id = kwargs['publication_id']
publication = Publication.query.get(publication_id)
if publication is None:
abort(404, message="Could not find the selected publication")
g.publication = publication
return f(*args, **kwargs)
示例9: parse_args
def parse_args(self, req=None, strict=False):
"""Parse all arguments from the provided request and return the results
as a Namespace
:param strict: if req includes args not in parser, throw 400 BadRequest exception
"""
if req is None:
req = request
namespace = self.namespace_class()
# A record of arguments not yet parsed; as each is found
# among self.args, it will be popped out
req.unparsed_arguments = dict(self.argument_class('').source(req)) if strict else {}
errors = {}
for arg in self.args:
value, found = arg.parse(req, self.bundle_errors)
if isinstance(value, ValueError):
errors.update(found)
found = None
if found or arg.store_missing:
namespace[arg.dest or arg.name] = value
if errors:
flask_restful.abort(400, message=errors)
if strict and req.unparsed_arguments:
raise exceptions.BadRequest('Unknown arguments: %s'
% ', '.join(req.unparsed_arguments.keys()))
return namespace
示例10: put
def put(self, resource_id, file_id):
"""Update a deposition file - i.e. rename it."""
v = APIValidator()
if not v.validate(request.json, file_schema):
abort(
400,
message="Bad request",
status=400,
errors=map(lambda x: dict(message=x, code=error_codes["validation_error"]), v.errors),
)
d = Deposition.get(resource_id, user=current_user)
df = d.get_file(file_id)
if not d.type.authorize_file(d, df, "update_metadata"):
raise ForbiddenAction("update_metadata", df)
new_name = secure_filename(request.json["filename"])
if new_name != request.json["filename"]:
abort(
400,
message="Bad request",
status=400,
errors=[dict(message="Not a valid filename", code=error_codes["validation_error"])],
)
df.name = new_name
d.save()
return d.type.marshal_file(df)
示例11: embed
def embed(query_id, visualization_id, org_slug=None):
# TODO: add event for embed access
query = models.Query.get_by_id_and_org(query_id, current_org)
require_access(query.groups, current_user, view_only)
vis = query.visualizations.where(models.Visualization.id == visualization_id).first()
qr = {}
if vis is not None:
vis = vis.to_dict()
qr = query.latest_query_data
if qr is None:
abort(400, message="No Results for this query")
else:
qr = qr.to_dict()
else:
abort(404, message="Visualization not found.")
client_config = {}
client_config.update(settings.COMMON_CLIENT_CONFIG)
qr = project(qr, ('data', 'id', 'retrieved_at'))
vis = project(vis, ('description', 'name', 'id', 'options', 'query', 'type', 'updated_at'))
vis['query'] = project(vis, ('created_at', 'description', 'name', 'id', 'latest_query_data_id', 'name', 'updated_at'))
return render_template("embed.html",
name=settings.NAME,
base_href=base_href(),
client_config=json_dumps(client_config),
visualization=json_dumps(vis),
query_result=json_dumps(qr),
analytics=settings.ANALYTICS)
示例12: post
def post(self): # pylint:disable=no-self-use
admin_required()
name = name_parser.parse_args()["name"]
if not TOPIC_NAME_RE.match(name):
abort(400, error_message="Invalid topic name. Topic name can only contain A-Z, a-z, 0-9, - and _")
topic_id = run_sns_command(sns.create_topic, Name=name)
return {"topic_id": topic_id["TopicArn"]}
示例13: run_query
def run_query(query, parameters, data_source, query_id, max_age=0):
if data_source.paused:
if data_source.pause_reason:
message = '{} is paused ({}). Please try later.'.format(data_source.name, data_source.pause_reason)
else:
message = '{} is paused. Please try later.'.format(data_source.name)
return error_response(message)
try:
query.apply(parameters)
except InvalidParameterError as e:
abort(400, message=e.message)
if query.missing_params:
return error_response(u'Missing parameter value for: {}'.format(u", ".join(query.missing_params)))
if max_age == 0:
query_result = None
else:
query_result = models.QueryResult.get_latest(data_source, query.text, max_age)
if query_result:
return {'query_result': query_result.to_dict()}
else:
job = enqueue_query(query.text, data_source, current_user.id, current_user.is_api_user(), metadata={
"Username": repr(current_user) if current_user.is_api_user() else current_user.email,
"Query ID": query_id
})
return {'job': job.to_dict()}
示例14: post
def post(self):
args = parse.parse_args()
try:
c_id = args['contact_id']
dcontact = Contact.query.get(c_id).first()
except:
abort(404, message="Contact id: %s doesn't exist" % (c_id))
inv = Invoice()
inv.email = args['email']
inv.invoice_date = args['invoice_date']
inv.recipient_note = args['recipient_note']
inv.subtotal = args['subtotal']
inv.total = args['total']
inv.paid = False
inv.contact_id = c_id
import paypalrestsdk
paypalrestsdk.configure({
"mode": "sandbox", # PAYPAL_MODE
"client_id": app.config['PAYPAL_CLIENT_ID'], # PAYPAL_CLIENT_ID
"client_secret": app.config['PAYPAL_CLIENT_SECRET'] }) # PAYPAL_CLIENT_SECRET
paypal_invoice = paypalrestsdk.Invoice({
"merchant_info": {
"email":"[email protected]",
"first_name":"Francisco",
"last_name": "Barcena",
"business_name":"fdev.tk",
"phone":{"country_code": "001","national_number":"5555555555"},
"address":{
"line1":"123 Fake St. Apt.A",
"city":"Fake City",
"country_code":"US",
"state":"California"
},
},
"billing_info":[{"email":request.form["email"]}],
"note":"MAKE MONEY F*CK B*TCHES"
})
# inv_lines (from list in args)
the_items = []
for the_item in inv_lines:
# append to the_items (for paypal)
the_items.append(dict({"name":the_item.d_description.data,"quantity":str(the_item.qty.data),"unit_price":{"currency":"USD","value":str(the_item.unit_price.data)}}))
# Create and append to Invoice model
new_invoice_line = InvoiceLine()
new_invoice_line.description
new_invoice_line.quantity
new_invoice_line.unit_price
new_invoice_line.amount
inv.invoice_lines.append(new_invoice_line)
paypal_invoice.items = the_items
error = None
if paypal_invoice.create():
print('paypal invoice created')
# Add invoice lines here (from list as argument)
db.session.add(inv)
db.session.commit()
else:
error = paypal_invoice.error
abort(404, message="Invoice creation error: %s" % (error))
return inv, 201
示例15: put
def put(self, id):
args = request.get_json(force=True)
examination = ExaminationModel.query.filter_by(id=id).first_or_404()
# Make sure required fields are there
if args['nome'] and args['ano'] and args['semestre'] is not None:
# Make sure the fields are unique
if ExaminationModel.query.filter(
ExaminationModel.id != args['id']).\
filter((ExaminationModel.nome == args['nome']) &
(ExaminationModel.ano == args['ano']) &
(ExaminationModel.semestre == args['semestre'])
).first():
abort(409,
message="An examination with this name already exists")
else:
examination.id_instituicao_ensino = \
args['id_instituicao_ensino']
examination.nome = args['nome']
examination.ano = args['ano']
examination.semestre = args['semestre']
examination.data_inicio = args['data_inicio']
examination.duracao = args['duracao']
else:
abort(409, message="Missing fields")
# Commit and return
db.session.commit()
examination.id
return examination