本文整理汇总了Python中flask_restful.abort方法的典型用法代码示例。如果您正苦于以下问题:Python flask_restful.abort方法的具体用法?Python flask_restful.abort怎么用?Python flask_restful.abort使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask_restful
的用法示例。
在下文中一共展示了flask_restful.abort方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_app
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def create_app(config):
"""
创建app
"""
# 添加配置
app.config.from_object(config)
# 解决跨域
app.after_request(_access_control)
# 自定义abort 400 响应数据格式
flask_restful.abort = _custom_abort
# 数据库初始化
db.init_app(app)
# 注册蓝图
from routes import api_v1
app.register_blueprint(api_v1, url_prefix='/api/v1')
# 使用flask原生异常处理程序
app.handle_exception = handle_exception
app.handle_user_exception = handle_user_exception
return app
示例2: authenticate
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def authenticate(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not getattr(func, 'authenticated', True):
return func(*args, **kwargs)
acct = True
allow_list_ip = CONF.etc.allow_ip.split(',')
if getRemoteAddr(request) not in allow_list_ip:
acct = False
# beta env allow any ip in
if CONF.etc.env != 'prod':
acct = True
if acct:
return func(*args, **kwargs)
return abort(401)
return wrapper
示例3: handle_validation_error
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def handle_validation_error(self, error, bundle_errors):
"""
Called when an error is raised while parsing. Aborts the request
with a 400 status and a meta error dictionary.
Can I do this through the exception handling system?
:param error: the error that was raised
"""
help_str = '(%s) ' % self.help if self.help else ''
msg = '[%s]: %s%s' % (self.name, help_str, str(error))
if bundle_errors:
return error, msg
return abort(400, meta={'message':msg, 'code':400, 'status':'FAIL'})
# Custom Exception types for the api. These should just pass.
示例4: monitor_rest_request
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def monitor_rest_request(func):
@wraps(func)
def wrapper(*args, **kwargs):
for index in range(db.retry_commit_number):
try:
result = func(*args, **kwargs)
except Exception as exc:
return rest_abort(500, message=str(exc))
try:
db.session.commit()
return result
except Exception as exc:
db.session.rollback()
app.log("error", f"Rest Call n°{index} failed ({exc}).")
stacktrace = format_exc()
sleep(db.retry_commit_time * (index + 1))
else:
rest_abort(500, message=stacktrace)
return wrapper
示例5: get
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def get(self, job_id):
""" Returns the current status of a given job_id.
Jobs finish by asking its state with a probability of 1/3 """
job_id = int(job_id)
# job doesn't exist
if job_id >= self.queue.nextid:
print("Job_id {} not found".format(job_id))
flask_restful.abort(404,
message="Job_id %d doesn't exist" % job_id)
running = job_id in self.queue.jobs
finished = random.randint(0, 2) != 0
if running and not finished:
print("Job_id %d running" % job_id)
return flask.jsonify({'task': {'status': 'running'}})
if running:
self.queue.delete_job(job_id)
print("Job_id {} reported".format(job_id))
return flask.jsonify({'task': {'status': 'reported'}})
示例6: get
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def get(self, user, key=None):
if key is None:
restful.abort(405)
try:
bid = decode_id(key)
except (ValueError, TypeError):
restful.abort(404)
backup = self.model.query.filter_by(id=bid).first()
if not backup:
if user.is_admin:
return restful.abort(404)
return restful.abort(403)
if not self.model.can(backup, user, 'view'):
return restful.abort(403)
backup.group = [models.User.get_by_id(uid) for uid in backup.owners()]
return backup
示例7: _custom_abort
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def _custom_abort(http_status_code, **kwargs):
"""
自定义abort 400响应数据格式
"""
if http_status_code == 400:
message = kwargs.get('message')
if isinstance(message, dict):
param, info = list(message.items())[0]
data = '{}:{}!'.format(param, info)
return abort(jsonify(pretty_result(code.PARAM_ERROR, data=data)))
else:
return abort(jsonify(pretty_result(code.PARAM_ERROR, data=message)))
return abort(http_status_code)
示例8: admin_required
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def admin_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(current_user)
if not current_user.is_authenticated:
return abort(401)
if not current_user.is_administrator:
return abort(403)
return func(*args, **kwargs)
return wrapper
示例9: resp
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def resp(code=0, data=None, message=None, is_json=True, msg_en=None):
if is_json:
return Response(json.dumps({
'errcode': code,
'data': data,
'message': message if message else msg_en,
'msg_en': msg_en}))
if code == 0:
return data, 200
elif code == 401:
return abort(401)
else:
code = code if code >= 400 else 400
return message, code
示例10: get
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def get(self, id):
"""Get run by id"""
run = self.backend_store.get_run(id)
if not run:
return abort(http_client.NOT_FOUND,
message="Run {} doesn't exist".format(id))
return run_model.format_response(run)
示例11: delete
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def delete(self, id):
"""Delete run by id"""
run = self.backend_store.get_run(id)
if not run:
return abort(http_client.NOT_FOUND,
message="Run {} doesn't exist".format(id))
if not self.manager.delete_run(run):
return abort(http_client.BAD_REQUEST,
message="Failed to find the task queue "
"manager of run {}.".format(id))
return '', http_client.NO_CONTENT
示例12: get
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def get(self):
"""Get a credential by file path"""
args = self.get_parser.parse_args()
cred = self.manager.get_credential(args)
if cred is None:
return abort(http_client.BAD_REQUEST,
message='Unable to decrypt credential value.')
else:
return cred
示例13: get
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def get(self, task_id):
"""
Returns information about task status.
"""
queue = rq.get_queue()
task = queue.fetch_job(task_id)
if task:
return {
"id": task.id,
"status": task.status,
"result_url": task.result
}
else:
return abort(404, message="Unknown task_id")
示例14: authenticate
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def authenticate(func):
""" Provide user object to API methods. Passes USER as a keyword argument
to all protected API Methods.
"""
@wraps(func)
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)
return wrapper
示例15: create_assignment
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import abort [as 别名]
def create_assignment(self, user, offering, name):
args = self.parse_args()
course = models.Course.by_name(offering)
assignment = models.Assignment(
course=course,
creator_id=user.id,
display_name=args["display_name"],
name=name,
due_date=utils.server_time_obj(args["due_date"], course),
lock_date=utils.server_time_obj(args["lock_date"], course),
max_group_size=args["max_group_size"],
url=args["url"],
revisions_allowed=args["revisions_allowed"],
autograding_key=args["autograding_key"],
continuous_autograding=args["continuous_autograding"],
uploads_enabled=args["uploads_enabled"],
upload_info=args["upload_info"],
visible=args["visible"],
)
if not models.Assignment.can(assignment, user, "create"):
models.db.session.remove()
restful.abort(403)
models.db.session.add(assignment)
models.db.session.commit()
return assignment