Python flask_restful.abort() Examples

The following are 30 code examples of flask_restful.abort(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_restful , or try the search function .
Example #1
Source File: app.py    From flask-restful-example with MIT License 6 votes vote down vote up
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 
Example #2
Source File: decorators.py    From open_dnsdb with Apache License 2.0 6 votes vote down vote up
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 
Example #3
Source File: api.py    From ok with Apache License 2.0 6 votes vote down vote up
def get(self, user, email=None):
        target = self.model.lookup(email)

        if not email or email.lower() == user.email.lower():
            # Get the current user
            return user

        if not target and user.is_admin:
            restful.abort(404)
        elif not target:
            restful.abort(403)

        if user.is_admin:
            return target

        restful.abort(403) 
Example #4
Source File: api.py    From ok with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: dummy_cuckoo_api.py    From PeekabooAV with GNU General Public License v3.0 6 votes vote down vote up
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'}}) 
Example #6
Source File: server.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: api_util.py    From NEXT with Apache License 2.0 6 votes vote down vote up
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. 
Example #8
Source File: api.py    From ok with Apache License 2.0 5 votes vote down vote up
def add_score(self, user):
        args = self.parse_args()
        try:
            bid = decode_id(args['bid'])
        except (ValueError, TypeError):
            restful.abort(404)
        backup = models.Backup.query.get(bid)
        kind = args['kind'].lower().strip()
        score, message = args['score'], args['message']
        score = make_score(user, backup, score, message, kind)
        if score:
            return {'success': True, 'message': 'OK'}
        return {'success': False, 'message': "Permission error"} 
Example #9
Source File: api.py    From ok with Apache License 2.0 5 votes vote down vote up
def get(self, user, backup_id):
        backup = models.Backup.query.get(backup_id)
        if not backup:
            if user.is_admin:
                restful.abort(404)
            else:
                restful.abort(403)
        if not models.Backup.can(backup, user, "view"):
            restful.abort(403)
        return {"comments": backup.comments} 
Example #10
Source File: api.py    From ok with Apache License 2.0 5 votes vote down vote up
def get(self, user, name, email):
        assign = models.Assignment.by_name(name)
        target = models.User.lookup(email)

        limit = request.args.get('limit', 150, type=int)
        offset = request.args.get('offset', 0, type=int)

        if not assign or not target:
            if user.is_admin:
                return restful.abort(404)
            return restful.abort(403)

        if user.email != email and not self.model.can(assign, user, 'export'):
            return restful.abort(403)

        base_query = (models.Backup.query.filter(
            models.Backup.submitter_id == target.id,
            models.Backup.assignment_id == assign.id,
        ).order_by(models.Backup.created.desc()))

        backups = base_query.limit(limit).offset(offset)

        num_backups = base_query.count()
        has_more = ((num_backups - offset) - limit) > 0

        data = {'backups': backups.all(),
                'count': num_backups,
                'limit': limit,
                'offset': offset,
                'has_more':  has_more}
        return data 
Example #11
Source File: api.py    From ok with Apache License 2.0 5 votes vote down vote up
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': []} 
Example #12
Source File: api.py    From ok with Apache License 2.0 5 votes vote down vote up
def get(self, offering, user):
        course = self.model.by_name(offering)
        if course is None:
            restful.abort(404)
        if not self.model.can(course, user, 'staff'):
            restful.abort(403)
        data = {}
        for role in VALID_ROLES:
            data[role] = []
        for p in course.participations:
            data[p.role].append(p.user)
        return data 
Example #13
Source File: api.py    From ok with Apache License 2.0 5 votes vote down vote up
def post(self, user):
        score = self.schema.add_score(user)
        if not score or not score['success']:
            restful.abort(401)
        return {
            'email': current_user.email,
            'success': True
        } 
Example #14
Source File: api.py    From ok with Apache License 2.0 5 votes vote down vote up
def post(self, name=None):
        if not name:
            restful.abort(404)
        self.schema.edit_version(name)
        return {} 
Example #15
Source File: api.py    From ok with Apache License 2.0 5 votes vote down vote up
def get(self, user, name):
        assign = self.model.by_name(name)
        if not assign:
            restful.abort(404)
        elif not self.model.can(assign, user, 'view'):
            restful.abort(403)
        return assign 
Example #16
Source File: api.py    From ok with Apache License 2.0 5 votes vote down vote up
def get(self, user, name, email):
        assign = models.Assignment.by_name(name)
        target = models.User.lookup(email)
        default_value = {'members': []}

        if not assign:
            restful.abort(404)
        elif not target and user.is_admin:
            restful.abort(404)
        elif not target:
            restful.abort(403)

        group = self.model.lookup(target, assign)

        member_emails = [email.lower()]
        if group:
            member_emails = [m.user.email.lower() for m in group.members]

        is_member = user.email.lower() in member_emails
        is_staff = user.is_enrolled(assign.course.id, STAFF_ROLES)

        if is_member or is_staff or user.is_admin:
            if group:
                return group
            else:
                return default_value
        restful.abort(403) 
Example #17
Source File: app.py    From flask-restful-example with MIT License 5 votes vote down vote up
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) 
Example #18
Source File: api.py    From ok with Apache License 2.0 5 votes vote down vote up
def edit_version(self, name):
        args = self.parse_args()
        if not current_user.is_admin:
            restful.abort(403)
        if not utils.check_url(args['download_link']):
            restful.abort(400, message='URL is not valid')
        version = models.Version.query.filter_by(name=name).first_or_404()
        version.current_version = args['current_version']
        version.download_link = args['download_link']
        version.save() 
Example #19
Source File: api.py    From ok with Apache License 2.0 5 votes vote down vote up
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 
Example #20
Source File: api.py    From ok with Apache License 2.0 5 votes vote down vote up
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 
Example #21
Source File: views.py    From docsbox with MIT License 5 votes vote down vote up
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") 
Example #22
Source File: credential_controller.py    From column with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #23
Source File: run_controller.py    From column with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #24
Source File: run_controller.py    From column with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #25
Source File: decorators.py    From open_dnsdb with Apache License 2.0 5 votes vote down vote up
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 
Example #26
Source File: decorators.py    From open_dnsdb with Apache License 2.0 5 votes vote down vote up
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 
Example #27
Source File: api.py    From ok with Apache License 2.0 4 votes vote down vote up
def post(self, user, key=None):
        if key is not None:
            restful.abort(405)
        try:
            backup = self.schema.store_backup(user)
        except ValueError as e:
            data = {'backup': True}
            if 'late' in str(e).lower():
                data['late'] = True
            return restful.abort(403, message=str(e), data=data)

        assignment = backup.assignment

        # Only accept revision if the assignment has revisions enabled
        if not assignment.revisions_allowed:
            return restful.abort(403,
                                 message=("Revisions are not enabled for {}"
                                          .format(assignment.name)),
                                 data={'backup': True, 'late': True})

        # Only accept revision if the user has a FS
        group = assignment.active_user_ids(user.id)
        fs = assignment.final_submission(group)

        if not fs:
            return restful.abort(403, message="No Submission to Revise", data={})

        # Get previous revision, (There should only be one)
        previous_revision = assignment.revision(group)
        if previous_revision:
            for score in previous_revision.scores:
                if score.kind == "revision":
                    score.archive()
        models.db.session.commit()
        fs_url = url_for('student.code', name=assignment.name, submit=fs.submit,
                         bid=fs.id, _external=True)

        assignment_creator = models.User.get_by_id(assignment.creator_id)

        make_score(assignment_creator, backup, 2.0, "Revision for {}".format(fs_url),
                   "revision")
        backup_url = url_for('student.code', name=assignment.name, submit=backup.submit,
                             bid=backup.id, _external=True)

        return {
            'email': current_user.email,
            'key': encode_id(backup.id),
            'url': backup_url,
            'course': assignment.course,
            'assignment': assignment.name,
        } 
Example #28
Source File: api.py    From ok with Apache License 2.0 4 votes vote down vote up
def get(self, user, name):
        assign = models.Assignment.by_name(name)

        if not assign:
            if user.is_admin:
                return restful.abort(404)
            return restful.abort(403)

        limit = request.args.get('limit', 150, type=int)
        offset = request.args.get('offset', 0, type=int)

        if not self.model.can(assign, user, 'export'):
            return restful.abort(403)

        subms = assign.course_submissions(include_empty=False)

        output = []
        subm_keys = set(s['backup']['id'] for s in subms)
        joined = models.db.joinedload
        base_query = (models.Backup.query.options(joined('assignment'),
                                                  joined('submitter'),
                                                  joined('messages'))
                            .filter(models.Backup.id.in_(subm_keys))
                            .order_by(models.Backup.created.desc()))

        num_subms = len(subm_keys)
        output = base_query.limit(limit).offset(offset)
        has_more = ((num_subms - offset) - limit) > 0

        results = []
        for backup in output:
            data = backup.as_dict()
            data.update({
                'group': [models.User.get_by_id(uid) for uid in backup.owners()],
                'assignment': assign,
                'is_late': backup.is_late,
                'external_files': backup.external_files,
                'submission_time': backup.submission_time,
                'submitter': backup.submitter,
                'messages': backup.messages
            })
            results.append(data)

        return {'backups': results,
                'limit': limit,
                'offset': offset,
                'count': num_subms,
                'has_more': has_more} 
Example #29
Source File: views.py    From docsbox with MIT License 4 votes vote down vote up
def post(self):
        """
        Recieves file and options, checks file mimetype,
        validates options and creates converting task
        """
        if "file" not in request.files:
            return abort(400, message="file field is required")
        else:
            with NamedTemporaryFile(delete=False, prefix=app.config["MEDIA_PATH"]) as tmp_file:
                request.files["file"].save(tmp_file)
                tmp_file.flush()
                tmp_file.close()
                remove_file.schedule(
                    datetime.timedelta(seconds=app.config["ORIGINAL_FILE_TTL"])
                , tmp_file.name)
                with Magic() as magic: # detect mimetype
                    mimetype = magic.from_file(tmp_file.name)
                    if mimetype not in app.config["SUPPORTED_MIMETYPES"]:
                        return abort(400, message="Not supported mimetype: '{0}'".format(mimetype))
                options = request.form.get("options", None)
                if options: # options validation
                    options = ujson.loads(options)
                    formats = options.get("formats", None)
                    if not isinstance(formats, list) or not formats:
                        return abort(400, message="Invalid 'formats' value")
                    else:
                        for fmt in formats:
                            supported = (fmt in app.config["SUPPORTED_MIMETYPES"][mimetype]["formats"])
                            if not supported:
                                message = "'{0}' mimetype can't be converted to '{1}'"
                                return abort(400, message=message.format(mimetype, fmt))
                    thumbnails = options.get("thumbnails", None)
                    if thumbnails:
                        if not isinstance(thumbnails, dict):
                            return abort(400, message="Invalid 'thumbnails' value")
                        else:
                            thumbnails_size = thumbnails.get("size", None)
                            if not isinstance(thumbnails_size, str) or not thumbnails_size:
                                return abort(400, message="Invalid 'size' value")
                            else:
                                try:
                                    (width, height) = map(int, thumbnails_size.split("x"))
                                except ValueError:
                                    return abort(400, message="Invalid 'size' value")
                                else:
                                    options["thumbnails"]["size"] = (width, height)
                else:
                    if mimetype == "application/pdf":
                        options = {
                            "formats": ["html"]
                        }
                    else:
                        options = app.config["DEFAULT_OPTIONS"]
                task = process_document.queue(tmp_file.name, options, {
                    "mimetype": mimetype,
                })
        return {
            "id": task.id,
            "status": task.status,
        } 
Example #30
Source File: __init__.py    From open_dnsdb with Apache License 2.0 4 votes vote down vote up
def createApp(app_env, app_kind, conf_dir):
    app = Flask(__name__)
    config_obj = Config(app_env, app_kind, conf_dir)
    CONF.flask_conf = config_obj
    app.config.from_object(config_obj)

    CONF.tmp_dir = make_tmp_dir('./tmp')

    db.init_app(app)
    login_manager = init_login_manager()
    login_manager.init_app(app)

    @login_manager.unauthorized_handler
    def unauthorized():
        return abort(401)

    LOG.info("dnsdb.started")

    @app.context_processor
    def default_context_processor():
        result = {'config': {'BASE_URL': CONF.web.base_url}}
        return result

    from dnsdb.view.web import root
    app.register_blueprint(root.bp, url_prefix='/')

    from dnsdb.view.web import auth
    app.register_blueprint(auth.bp, url_prefix='/web/auth')

    from dnsdb.view.web import user
    app.register_blueprint(user.bp, url_prefix='/web/user')

    from dnsdb.view.web import preview
    app.register_blueprint(preview.bp, url_prefix='/web/preview')

    from dnsdb.view.web import config
    app.register_blueprint(config.bp, url_prefix='/web/config')

    from dnsdb.view.web import subnet
    app.register_blueprint(subnet.bp, url_prefix='/web/subnet')

    from dnsdb.view.web import record
    app.register_blueprint(record.bp, url_prefix='/web/record')

    from dnsdb.view.web import view_isp
    app.register_blueprint(view_isp.bp, url_prefix='/web/view')

    from dnsdb.view.web import view_record
    app.register_blueprint(view_record.bp, url_prefix='/web/view')

    from dnsdb.view import api
    app.register_blueprint(api.bp, url_prefix='/api')

    return app