Python flask.abort() Examples

The following are 30 code examples of flask.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 , or try the search function .
Example #1
Source Project: beavy   Author: beavyHQ   File: views.py    License: Mozilla Public License 2.0 9 votes vote down vote up
def submit_story():
    if request.method == "POST":
        params = request.get_json()
        title, url = params['title'].strip(), params['url'].strip()
        text = params.get('text', "").strip()
        if not title:
            return abort(400, "You have to provide a 'title'")

        if url:
            link = Link(title=title, url=url, owner_id=current_user.id)
            db.session.add(link)
            db.session.commit()
            return link_schema.dump(link)
        elif text:
            topic = Topic(title=title, text=text, owner_id=current_user.id)
            db.session.add(topic)
            db.session.commit()
            return topic_schema.dump(topic)

        return abort(400, "You have to provide either 'url' or 'text', too")

    # Just render it
    return {} 
Example #2
Source Project: ptnotes   Author: averagesecurityguy   File: webserver.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_attack(pid, aid):
    """
    Get list of all the hosts possibly vulnerable to the attack.
    """
    project = get_project_db(pid)
    db = database.ScanDatabase(project['dbfile'])

    if flask.request.method == 'POST':
        note = flask.request.form['note']
        db.attackdb.update_attack_note(aid, note)

    attack = db.attackdb.get_attack(aid)

    if attack is None:
        flask.abort(404)

    items = [i.split(':') for i in attack['items'].split(',')]

    return flask.render_template('attack.html', pid=pid, attack=attack,
                items=items, name=project['name']) 
Example #3
Source Project: beavy   Author: beavyHQ   File: __init__.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def api_only(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        accepted = set(request.accept_mimetypes.values())
        explicit = not(not request.args.get("json", False))
        if not (accepted & API_MIMETYPES) and not explicit:
            return abort(415, "Unsupported Media Type")

        resp = fn(*args, **kwargs)
        if not isinstance(resp, ResponseBase):
            data, code, headers = unpack(resp)
            # we've found one, return json
            if isinstance(data, MarshalResult):
                data = data.data
            resp = make_response(json.dumps(data,
                                            indent=explicit and 4 or 0),
                                 code)

            if headers:
                resp.headers.update(headers)
            resp.headers["Content-Type"] = 'application/json'
        return resp
    return wrapped 
Example #4
Source Project: social-relay   Author: jaywink   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def hcard(guid):
    if guid != app.config.get("RELAY_GUID"):
        return abort(404)
    hcard = generate_hcard(
        "diaspora",
        hostname=app.config.get("SERVER_HOST"),
        fullname=app.config.get("RELAY_NAME"),
        firstname=app.config.get("RELAY_NAME"),
        lastname="",
        photo300="",
        photo100="",
        photo50="",
        searchable="false",
        guid=app.config.get("RELAY_GUID"),
        public_key=app.config.get("RELAY_PUBLIC_KEY"),
        username=app.config.get("RELAY_USERNAME"),
    )
    return Response(hcard, status=200) 
Example #5
Source Project: social-relay   Author: jaywink   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def receive_public():
    if not request.data:
        return abort(404)

    # Queue to rq for processing
    public_queue.enqueue("workers.receive.process", request.data, timeout=app.config.get("RELAY_WORKER_TIMEOUT"))

    # Log statistics
    log_receive_statistics(request.remote_addr)

    # return 200 whatever
    data = {
        'result': 'ok',
    }
    js = json.dumps(data)
    return Response(js, status=200, mimetype='application/json') 
Example #6
Source Project: flask-restful-example   Author: lalala223   File: app.py    License: 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 #7
Source Project: flask-restful-example   Author: lalala223   File: profiles.py    License: MIT License 6 votes vote down vote up
def get(id):
        id = hash_ids.decode(id)
        if not id: abort(404)

        try:
            profile = ProfilesModel.query.get(id[0])
            if not profile: abort(404)
        except SQLAlchemyError as e:
            current_app.logger.error(e)
            db.session.rollback()
            return pretty_result(code.DB_ERROR, '数据库错误!')
        else:
            item = {
                'id': hash_ids.encode(profile.id),
                'nickname': profile.nickname,
                'signature': profile.signature
            }
            return pretty_result(code.OK, data=item) 
Example #8
Source Project: flask-restful-example   Author: lalala223   File: profiles.py    License: MIT License 6 votes vote down vote up
def put(self, id):
        self.parser.add_argument("nickname", type=str, location="json", required=True)
        self.parser.add_argument("signature", type=str, location="json", required=True)
        args = self.parser.parse_args()

        id = hash_ids.decode(id)
        if not id: abort(404)

        try:
            profile = ProfilesModel.query.get(id[0])
            if not profile: abort(404)

            profile.nickname = args.nickname
            profile.signature = args.signature

            db.session.add(profile)
            db.session.commit()
        except SQLAlchemyError as e:
            current_app.logger.error(e)
            db.session.rollback()
            return pretty_result(code.DB_ERROR, '数据库错误!')
        else:
            return pretty_result(code.OK) 
Example #9
Source Project: flask-restful-example   Author: lalala223   File: profiles.py    License: MIT License 6 votes vote down vote up
def delete(id):
        id = hash_ids.decode(id)
        if not id: abort(404)

        try:
            profile = ProfilesModel.query.get(id[0])
            if not profile: abort(404)

            db.session.delete(profile)
            db.session.commit()
        except SQLAlchemyError as e:
            current_app.logger.error(e)
            db.session.rollback()
            return pretty_result(code.DB_ERROR, '数据库错误!')
        else:
            return pretty_result(code.OK) 
Example #10
Source Project: pagure   Author: Pagure   File: decorators.py    License: GNU General Public License v2.0 6 votes vote down vote up
def has_pr_enabled(function):
    """
    Decorator that checks if the current pagure project has the
    issue tracker active or has PRs function active
    If not active returns a 404 page
    """

    @wraps(function)
    def check_trackers(*args, **kwargs):
        repo = flask.g.repo
        if not repo.settings.get("pull_requests", True):
            flask.abort(
                404,
                description="Pull Requests are not enabled on this project",
            )

        return function(*args, **kwargs)

    return check_trackers 
Example #11
Source Project: pagure   Author: Pagure   File: decorators.py    License: GNU General Public License v2.0 6 votes vote down vote up
def is_repo_admin(function):
    """
    Decorator that checks if the current user is the admin of
    the project.
    If not active returns a 403 page
    """

    @wraps(function)
    def check_repo_admin(*args, **kwargs):
        if not flask.g.repo_admin:
            flask.abort(
                403,
                description="You are not allowed to change the "
                "settings for this project",
            )
        return function(*args, **kwargs)

    return check_repo_admin 
Example #12
Source Project: pagure   Author: Pagure   File: app.py    License: GNU General Public License v2.0 6 votes vote down vote up
def view_user_issues(username):
    """
    Shows the issues created or assigned to the specified user.

    :param username: The username to retrieve the issues for
    :type  username: str
    """

    if not pagure_config.get("ENABLE_TICKETS", True):
        flask.abort(
            404,
            description="Tickets have been disabled on this pagure instance",
        )

    user = _get_user(username=username)
    userprofile_common = get_userprofile_common(user)

    return flask.render_template(
        "userprofile_issues.html",
        username=username,
        user=user,
        repos_length=userprofile_common["repos_length"],
        forks_length=userprofile_common["forks_length"],
        select="issues",
    ) 
Example #13
Source Project: pagure   Author: Pagure   File: repo.py    License: GNU General Public License v2.0 6 votes vote down vote up
def view_docs(repo, username=None, filename=None, namespace=None):
    """ Display the documentation
    """
    repo = flask.g.repo

    if not pagure_config.get("DOC_APP_URL"):
        flask.abort(404, description="This pagure instance has no doc server")

    return flask.render_template(
        "docs.html",
        select="docs",
        repo=repo,
        username=username,
        filename=filename,
        endpoint="view_docs",
    ) 
Example #14
Source Project: github-stats   Author: lipis   File: test.py    License: MIT License 6 votes vote down vote up
def admin_test(test=None):
  if test and test not in TESTS:
    flask.abort(404)
  form = TestForm()
  if form.validate_on_submit():
    pass

  return flask.render_template(
    'admin/test/test_one.html' if test else 'admin/test/test.html',
    title='Test: %s' % test.title() if test else 'Test',
    html_class='test',
    form=form,
    test=test,
    tests=TESTS,
    versions=versions.get_versions(),
    back_url_for='admin_test' if test else None,
  ) 
Example #15
Source Project: github-stats   Author: lipis   File: gh.py    License: MIT License 6 votes vote down vote up
def gh_admin_top():
  stars = util.param('stars', int) or 10000
  page = util.param('page', int) or 1
  per_page = util.param('per_page', int) or 100
  # TODO: fix formatting
  result = urlfetch.fetch('https://api.github.com/search/repositories?q=stars:>=%s&sort=stars&order=asc&page=%d&per_page=%d' % (stars, page, per_page))
  if result.status_code == 200:
    repos = json.loads(result.content)
  else:
    flask.abort(result.status_code)

  for repo in repos['items']:
    account = repo['owner']
    account_db = model.Account.get_or_insert(
      account['login'],
      avatar_url=account['avatar_url'].split('?')[0],
      email=account['email'] if 'email' in account else '',
      name=account['login'],
      followers=account['followers'] if 'followers' in account else 0,
      organization=account['type'] == 'Organization',
      username=account['login'],
    )

  return 'OK %d of %d' % (len(repos['items']), repos['total_count']) 
Example #16
Source Project: github-stats   Author: lipis   File: feedback.py    License: MIT License 6 votes vote down vote up
def feedback():
  if not config.CONFIG_DB.feedback_email:
    return flask.abort(418)

  form = FeedbackForm(obj=auth.current_user_db())
  if not config.CONFIG_DB.has_anonymous_recaptcha or auth.is_logged_in():
    del form.recaptcha
  if form.validate_on_submit():
    body = '%s\n\n%s' % (form.message.data, form.email.data)
    kwargs = {'reply_to': form.email.data} if form.email.data else {}
    task.send_mail_notification('%s...' % body[:48].strip(), body, **kwargs)
    flask.flash('Thank you for your feedback!', category='success')
    return flask.redirect(flask.url_for('welcome'))

  return flask.render_template(
    'feedback.html',
    title='Feedback',
    html_class='feedback',
    form=form,
  ) 
Example #17
Source Project: github-stats   Author: lipis   File: auth.py    License: MIT License 6 votes vote down vote up
def post(self):
    args = parser.parse({
      'username': wf.Str(missing=None),
      'email': wf.Str(missing=None),
      'password': wf.Str(missing=None),
    })
    handler = args['username'] or args['email']
    password = args['password']
    if not handler or not password:
      return flask.abort(400)

    user_db = model.User.get_by(
      'email' if '@' in handler else 'username', handler.lower()
    )

    if user_db and user_db.password_hash == util.password_hash(user_db, password):
      auth.signin_user_db(user_db)
      return helpers.make_response(user_db, model.User.FIELDS)
    return flask.abort(401) 
Example #18
Source Project: comport   Author: codeforamerica   File: decorators.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def authorized_access_only(dataset=None):
    ''' Decorates views that require authentication if the department is not public
    '''
    def check_authorized(view_function):
        @wraps(view_function)
        def decorated_function(*args, **kwargs):
            try:
                department = Department.query.filter_by(short_name=kwargs["short_name"].upper()).first()
            except KeyError:
                department = Department.query.filter_by(id=kwargs["department_id"]).first()

            # check whether the current dataset is public
            dataset_is_public = True
            if dataset:
                try:
                    dataset_is_public = getattr(department, "is_public_{}".format(dataset))
                except ValueError:
                    dataset_is_public = True

            # check whether the user has access to this department
            if current_user.is_authenticated():
                user_has_dept_access = current_user.has_department(department.id) or current_user.is_admin()
            else:
                user_has_dept_access = False

            # abort with a 403 Forbidden if the department or dataset's not public and the user's not authorized to access it
            if (not department.is_public or not dataset_is_public) and (not current_user.is_authenticated() or not user_has_dept_access):
                abort(403)

            return view_function(*args, **kwargs)
        return decorated_function
    return check_authorized 
Example #19
Source Project: ptnotes   Author: averagesecurityguy   File: webserver.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_project_db(pid):
    """
    Get our project database.
    """
    pdb = database.ProjectDatabase()
    project = pdb.get_project(pid)

    if project is None:
        flask.abort(404)

    return project 
Example #20
Source Project: ptnotes   Author: averagesecurityguy   File: webserver.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def host(pid, ip):
    """
    Get all the information about a host.
    """
    project = get_project_db(pid)
    db = database.ScanDatabase(project['dbfile'])

    if flask.request.method == 'POST':
        note = flask.request.form['note']
        db.hostdb.update_host_note(ip, note)

    data = db.get_host_details(ip)

    if data is None:
        flask.abort(404)

    details = {}
    for item in data['items']:
        key = "{0}/{1}".format(item['port'], item['protocol'])
        if details.get(key) is None:
            details[key] = []
            details[key].append(item['note'])
        else:
            details[key].append(item['note'])

    keys = sorted(details.keys(), key=lambda x: int(x.split('/')[0]))
    note = data['note']

    return flask.render_template('host.html', pid=pid, host=ip,
            details=details, keys=keys, note=note,
            name=project['name']) 
Example #21
Source Project: ptnotes   Author: averagesecurityguy   File: webserver.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def item(pid, item_id):
    """
    Get all the information about an item.
    """
    project = get_project_db(pid)
    db = database.ScanDatabase(project['dbfile'])
    item = db.itemdb.get_item(item_id)

    if item is None:
        flask.abort(404)

    return flask.render_template('item.html', pid=pid, item=item,
                name=project['name']) 
Example #22
Source Project: hackernewsbot   Author: phil-r   File: main.py    License: MIT License 5 votes vote down vote up
def story_redirect(short_id):
  """Redirect to story url"""
  try:
    story_id = str(shortener.decode(short_id))
  except:
    return abort(400)
  redirect_url = memcache.get(story_id)
  if not redirect_url:
    story = ndb.Key(StoryPost, story_id).get()
    if not story:
      return make_response('<h1>Service Unavailable</h1><p>Try again later</p>', 503, {'Retry-After': 5})
    story.add_memcache()
    redirect_url = story.url
  return redirect(redirect_url) 
Example #23
Source Project: hackernewsbot   Author: phil-r   File: main.py    License: MIT License 5 votes vote down vote up
def comments_redirect(short_id):
  """Redirect to comments url"""
  try:
    story_id = str(shortener.decode(short_id))
  except:
    return abort(400)
  hn_url = "https://news.ycombinator.com/item?id={}".format(story_id)
  return redirect(hn_url) 
Example #24
Source Project: object-detection   Author: cristianpb   File: app.py    License: MIT License 5 votes vote down vote up
def delete_image():
    filename = request.form.get('filename', None)
    try:
        os.remove(filename)
        return json.dumps({'status': filename})
    except Exception as e:
        print(e)
        return abort(404) 
Example #25
Source Project: Jtyoui   Author: jtyoui   File: flaskerror.py    License: MIT License 5 votes vote down vote up
def hello():
        try:
            value = 1 / 0
            return jsonify(msg='请求成功!', data=value, code=200)  # 正常信息
        except ValueError:
            return flask_abort(600, jsonify, message='被除数不能为0')  # 有自定义的处理器来处理
        except KeyError:
            code = 400
        except Exception:  # 其他错误
            code = 500
        return abort(code)  # 由错误异常处理器来处理 
Example #26
Source Project: watchdog   Author: flipkart-incubator   File: index.py    License: Apache License 2.0 5 votes vote down vote up
def openPlugin(self, plugin):
    if self.plugManager.requiresAuth(plugin) and not current_user.is_authenticated():
      return render_template("requiresAuth.html")
    else:
      page, args = self.plugManager.openPage(plugin, **self.pluginArgs)
      if page:
        try:
          return render_template(page, **args)
        except jinja2.exceptions.TemplateSyntaxError: return render_template("error.html", status={'except': 'plugin-page-corrupt'})
        except jinja2.exceptions.TemplateNotFound:    return render_template("error.html", status={'except': 'plugin-page-not-found', 'page': page})
      else: abort(404)


  # /plugin/<plugin>/subpage/<page> 
Example #27
Source Project: watchdog   Author: flipkart-incubator   File: index.py    License: Apache License 2.0 5 votes vote down vote up
def openPluginSubpage(self, plugin, page):
    if self.plugManager.requiresAuth(plugin) and not current_user.is_authenticated():
      return render_template("requiresAuth.html")
    else:
      page, args = self.plugManager.openSubpage(plugin, page, **self.pluginArgs)
      if page:
        try:
          return render_template(page, **args)
        except jinja2.exceptions.TemplateSyntaxError: return render_template("error.html", status={'except': 'plugin-page-corrupt'})
        except jinja2.exceptions.TemplateNotFound:    return render_template("error.html", status={'except': 'plugin-page-not-found', 'page': page})
      else: abort(404)


  # /plugin/<plugin>/_cve_action/<action> 
Example #28
Source Project: beavy   Author: beavyHQ   File: object.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def by_capability(self, aborting=True, abort_code=404, *caps):
        caps = set(chain.from_iterable(map(lambda c:
                                           getattr(Object.TypesForCapability,
                                                   getattr(c, 'value', c), []),
                                           caps)))
        if not caps:
            # No types found, break right here.
            if aborting:
                raise abort(abort_code)
            return self.filter("1=0")

        return self.filter(Object.discriminator.in_(caps)) 
Example #29
Source Project: beavy   Author: beavyHQ   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def private_message(message):
    if current_user not in message.participants:
        return abort(403)
    return pm.dump(message).data 
Example #30
Source Project: social-relay   Author: jaywink   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def webfinger():
    account = request.args.get("q", "")
    if account.startswith("acct:"):
        account = account.replace("acct:", "", 1)
    if account != app.config.get("RELAY_ACCOUNT"):
        return abort(404)
    webfinger = generate_legacy_webfinger(
        "diaspora",
        handle=app.config.get("RELAY_ACCOUNT"),
        host=app.config.get("SERVER_HOST"),
        guid=app.config.get("RELAY_GUID"),
        public_key=app.config.get("RELAY_PUBLIC_KEY")
    )
    return Response(webfinger, status=200, mimetype="application/xrd+xml")