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 File: views.py    From beavy with 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 File: profiles.py    From flask-restful-example with 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 #3
Source File: profiles.py    From flask-restful-example with 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 #4
Source File: profiles.py    From flask-restful-example with 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 #5
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 #6
Source File: decorators.py    From pagure with 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 #7
Source File: views.py    From social-relay with 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 #8
Source File: views.py    From social-relay with 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 #9
Source File: repo.py    From pagure with 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 #10
Source File: decorators.py    From pagure with 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 File: __init__.py    From beavy with 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 #12
Source File: app.py    From pagure with 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 File: test.py    From github-stats with 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 #14
Source File: gh.py    From github-stats with 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 #15
Source File: webserver.py    From ptnotes with 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 #16
Source File: feedback.py    From github-stats with 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 File: auth.py    From github-stats with 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 File: profile.py    From github-stats with MIT License 5 votes vote down vote up
def profile_password():
  if not config.CONFIG_DB.has_email_authentication:
    flask.abort(418)
  user_db = auth.current_user_db()
  form = ProfilePasswordForm(obj=user_db)

  if not user_db.password_hash:
    del form.old_password

  if form.validate_on_submit():
    errors = False
    old_password = form.old_password.data if form.old_password else None
    new_password = form.new_password.data
    if new_password or old_password:
      if user_db.password_hash:
        if util.password_hash(user_db, old_password) != user_db.password_hash:
          form.old_password.errors.append('Invalid current password')
          errors = True

      if not (form.errors or errors):
        user_db.password_hash = util.password_hash(user_db, new_password)
        flask.flash('Your password has been changed.', category='success')

    if not (form.errors or errors):
      user_db.put()
      return flask.redirect(flask.url_for('profile'))

  return flask.render_template(
    'profile/profile_password.html',
    title=user_db.name,
    html_class='profile-password',
    form=form,
    user_db=user_db,
  ) 
Example #19
Source File: user.py    From github-stats with MIT License 5 votes vote down vote up
def user_update(user_id=0):
  if user_id:
    user_db = model.User.get_by_id(user_id)
  else:
    user_db = model.User(name='', username='')
  if not user_db:
    flask.abort(404)

  form = UserUpdateForm(obj=user_db)
  for permission in user_db.permissions:
    form.permissions.choices.append((permission, permission))
  form.permissions.choices = sorted(set(form.permissions.choices))
  if form.validate_on_submit():
    if not util.is_valid_username(form.username.data):
      form.username.errors.append('This username is invalid.')
    elif not model.User.is_username_available(form.username.data, user_db.key):
      form.username.errors.append('This username is already taken.')
    else:
      form.populate_obj(user_db)
      if auth.current_user_key() == user_db.key:
        user_db.admin = True
        user_db.active = True
      user_db.put()
      return flask.redirect(flask.url_for(
        'user_list', order='-modified', active=user_db.active,
      ))

  return flask.render_template(
    'user/user_update.html',
    title=user_db.name or 'New User',
    html_class='user-update',
    form=form,
    user_db=user_db,
    api_url=flask.url_for('api.admin.user', user_key=user_db.key.urlsafe()) if user_db.key else ''
  )


###############################################################################
# User Verify
############################################################################### 
Example #20
Source File: user.py    From github-stats with MIT License 5 votes vote down vote up
def user_forgot(token=None):
  if not config.CONFIG_DB.has_email_authentication:
    flask.abort(418)

  form = auth.form_with_recaptcha(UserForgotForm(obj=auth.current_user_db()))
  if form.validate_on_submit():
    cache.bump_auth_attempt()
    email = form.email.data
    user_dbs, cursors = util.get_dbs(
      model.User.query(), email=email, active=True, limit=2,
    )
    count = len(user_dbs)
    if count == 1:
      task.reset_password_notification(user_dbs[0])
      return flask.redirect(flask.url_for('welcome'))
    elif count == 0:
      form.email.errors.append('This email was not found')
    elif count == 2:
      task.email_conflict_notification(email)
      form.email.errors.append(
        '''We are sorry but it looks like there is a conflict with your
        account. Our support team is already informed and we will get back to
        you as soon as possible.'''
      )

  if form.errors:
    cache.bump_auth_attempt()

  return flask.render_template(
    'user/user_forgot.html',
    title='Forgot Password?',
    html_class='user-forgot',
    form=form,
  )


###############################################################################
# User Reset
############################################################################### 
Example #21
Source File: docs_server.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def __get_tree_and_content(repo_obj, commit, path):
    """ Return the tree and the content of the specified file. """

    (blob_or_tree, tree_obj, extended) = __get_tree(
        repo_obj, commit.tree, path
    )

    if blob_or_tree is None:
        return (tree_obj, None, None)

    if not repo_obj[blob_or_tree.oid]:
        # Not tested and no idea how to test it, but better safe than sorry
        flask.abort(404, description="File not found")

    is_file = False
    try:
        is_file = isinstance(blob_or_tree, pygit2.TreeEntry)
    except AttributeError:
        is_file = isinstance(blob_or_tree, pygit2.Blob)

    if is_file:
        filename = blob_or_tree.name
        name, ext = os.path.splitext(filename)
        blob_obj = repo_obj[blob_or_tree.oid]
        if not is_binary_string(blob_obj.data):
            try:
                content, safe = pagure.doc_utils.convert_readme(
                    blob_obj.data, ext
                )
                if safe:
                    filename = name + ".html"
            except pagure.exceptions.PagureEncodingException:
                content = blob_obj.data
        else:
            content = blob_obj.data

    tree = sorted(tree_obj, key=lambda x: x.filemode)
    return (tree, content, filename) 
Example #22
Source File: app.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def markdown_preview():
    """ Return the provided markdown text in html.

    The text has to be provided via the parameter 'content' of a POST query.
    """
    form = pagure.forms.ConfirmationForm()
    if form.validate_on_submit():
        return pagure.ui.filters.markdown_filter(flask.request.form["content"])
    else:
        flask.abort(400, description="Invalid request") 
Example #23
Source File: helpers.py    From github-stats with MIT License 5 votes vote down vote up
def unauthorized(self, response):
    flask.abort(401) 
Example #24
Source File: repo.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def view_project_activity(repo, namespace=None):
    """ Display the activity feed
    """

    if not pagure_config.get("DATAGREPPER_URL"):
        flask.abort(404)

    repo = flask.g.repo

    return flask.render_template("activity.html", repo=repo) 
Example #25
Source File: repo.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def delete_branch(repo, branchname, username=None, namespace=None):
    """ Delete the branch of a project.
    """
    if not flask.g.repo.is_fork and not pagure_config.get(
        "ALLOW_DELETE_BRANCH", True
    ):
        flask.abort(
            404,
            description="This pagure instance does not allow branch deletion",
        )

    repo_obj = flask.g.repo_obj

    if not flask.g.repo_committer:
        flask.abort(
            403,
            description="You are not allowed to delete branch for "
            "this project",
        )

    if six.PY2:
        branchname = branchname.encode("utf-8")

    if branchname == "master":
        flask.abort(
            403, description="You are not allowed to delete the master branch"
        )

    if branchname not in repo_obj.listall_branches():
        flask.abort(404, description="Branch not found")

    task = pagure.lib.tasks.delete_branch.delay(
        repo, namespace, username, branchname
    )
    return pagure.utils.wait_for_task(task) 
Example #26
Source File: repo.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def new_repo_hook_token(repo, username=None, namespace=None):
    """ Re-generate a hook token for the present project.
    """
    if not pagure_config.get("WEBHOOK", False):
        flask.abort(404)

    repo = flask.g.repo

    form = pagure.forms.ConfirmationForm()
    if not form.validate_on_submit():
        flask.abort(400, description="Invalid request")

    try:
        repo.hook_token = pagure.lib.login.id_generator(40)
        flask.g.session.commit()
        flask.flash("New hook token generated")
    except SQLAlchemyError as err:  # pragma: no cover
        flask.g.session.rollback()
        _log.exception(err)
        flask.flash("Could not generate a new token for this project", "error")

    return flask.redirect(
        flask.url_for(
            "ui_ns.view_settings",
            repo=repo.name,
            username=username,
            namespace=namespace,
        )
        + "#privatehookkey-tab"
    ) 
Example #27
Source File: repo.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def delete_repo(repo, username=None, namespace=None):
    """ Delete the present project.
    """
    repo = flask.g.repo

    del_project = pagure_config.get("ENABLE_DEL_PROJECTS", True)
    del_fork = pagure_config.get("ENABLE_DEL_FORKS", del_project)
    if (not repo.is_fork and not del_project) or (
        repo.is_fork and not del_fork
    ):
        flask.abort(404)

    if repo.read_only:
        flask.flash(
            "The ACLs of this project are being refreshed in the backend "
            "this prevents the project from being deleted. Please wait "
            "for this task to finish before trying again. Thanks!"
        )
        return flask.redirect(
            flask.url_for(
                "ui_ns.view_settings",
                repo=repo.name,
                username=username,
                namespace=namespace,
            )
            + "#deleteproject-tab"
        )

    task = pagure.lib.tasks.delete_project.delay(
        namespace=repo.namespace,
        name=repo.name,
        user=repo.user.user if repo.is_fork else None,
        action_user=flask.g.fas_user.username,
    )
    return pagure.utils.wait_for_task(task) 
Example #28
Source File: app.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def renew_api_user_token(token_id):
    """ Renew a user token (ie: not project specific).
    """
    if admin_session_timedout():
        flask.flash("Action canceled, try it again", "error")
        url = flask.url_for(".user_settings")
        return flask.redirect(flask.url_for("auth_login", next=url))

    token = pagure.lib.query.get_api_token(flask.g.session, token_id)

    if not token or token.user.username != flask.g.fas_user.username:
        flask.abort(404, description="Token not found")

    form = pagure.forms.ConfirmationForm()

    if form.validate_on_submit():
        acls = [acl.name for acl in token.acls]
        try:
            pagure.lib.query.add_token_to_user(
                flask.g.session,
                project=None,
                description=token.description or None,
                acls=acls,
                username=flask.g.fas_user.username,
                expiration_date=datetime.date.today()
                + datetime.timedelta(days=(30 * 6)),
            )
            flask.g.session.commit()
            flask.flash("Token created")
            return flask.redirect(
                flask.url_for("ui_ns.user_settings") + "#nav-api-tab"
            )
        except SQLAlchemyError as err:  # pragma: no cover
            flask.g.session.rollback()
            _log.exception(err)
            flask.flash("API token could not be renewed", "error")

    return flask.redirect(
        flask.url_for("ui_ns.user_settings") + "#nav-api-tab"
    ) 
Example #29
Source File: app.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def revoke_api_user_token(token_id):
    """ Revoke a user token (ie: not project specific).
    """
    if admin_session_timedout():
        flask.flash("Action canceled, try it again", "error")
        url = flask.url_for(".user_settings")
        return flask.redirect(flask.url_for("auth_login", next=url))

    token = pagure.lib.query.get_api_token(flask.g.session, token_id)

    if not token or token.user.username != flask.g.fas_user.username:
        flask.abort(404, description="Token not found")

    form = pagure.forms.ConfirmationForm()

    if form.validate_on_submit():
        try:
            if token.expiration >= datetime.datetime.utcnow():
                token.expiration = datetime.datetime.utcnow()
                flask.g.session.add(token)
            flask.g.session.commit()
            flask.flash("Token revoked")
        except SQLAlchemyError as err:  # pragma: no cover
            flask.g.session.rollback()
            _log.exception(err)
            flask.flash(
                "Token could not be revoked, please contact an admin", "error"
            )

    return flask.redirect(
        flask.url_for("ui_ns.user_settings") + "#nav-api-token"
    ) 
Example #30
Source File: webserver.py    From ptnotes with 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