flask.after_this_request

Here are the examples of the python api flask.after_this_request taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

16 Examples 7

Example 1

Project: flask-debug-api Source File: extension.py
@module.route('/browse', defaults={'path': '/'}, methods=METHODS)
@module.route('/browse/<path:path>', methods=METHODS)
def browse(path):
    adapter = _request_ctx_stack.top.url_adapter
    g.methods = [method for method in METHODS if adapter.test(path, method)]
    if adapter.test(path, request.method):
        after_this_request(modify_response)
        (endpoint, kwargs) = adapter.match(path)
        view_func = current_app.view_functions[endpoint]
        return view_func(**kwargs)
    return render_template(TEMPLATE, methods=g.methods)

Example 2

Project: WAPT Source File: views.py
Function: log_in
@anonymous_user_required
def login():
    """View function for login view"""

    form_class = _security.login_form

    if request.json:
        form = form_class(MultiDict(request.json))
    else:
        form = form_class()

    if form.validate_on_submit():
        login_user(form.user, remember=form.remember.data)
        after_this_request(_commit)

        if not request.json:
            return redirect(get_post_login_redirect(form.next.data))

    if request.json:
        return _render_json(form, include_auth_token=True)

    return _security.render_template(config_value('LOGIN_USER_TEMPLATE'),
                                     login_user_form=form,
                                     **_ctx('login'))

Example 3

Project: WAPT Source File: views.py
@anonymous_user_required
def register():
    """View function which handles a registration request."""

    if _security.confirmable or request.json:
        form_class = _security.confirm_register_form
    else:
        form_class = _security.register_form

    if request.json:
        form_data = MultiDict(request.json)
    else:
        form_data = request.form

    form = form_class(form_data)

    if form.validate_on_submit():
        user = register_user(**form.to_dict())
        form.user = user

        if not _security.confirmable or _security.login_without_confirmation:
            after_this_request(_commit)
            login_user(user)

        if not request.json:
            if 'next' in form:
                redirect_url = get_post_register_redirect(form.next.data)
            else:
                redirect_url = get_post_register_redirect()

            return redirect(redirect_url)
        return _render_json(form, include_auth_token=True)

    if request.json:
        return _render_json(form)

    return _security.render_template(config_value('REGISTER_USER_TEMPLATE'),
                                     register_user_form=form,
                                     **_ctx('register'))

Example 4

Project: WAPT Source File: views.py
Function: token_login
@anonymous_user_required
def token_login(token):
    """View function that handles passwordless login via a token"""

    expired, invalid, user = login_token_status(token)

    if invalid:
        do_flash(*get_message('INVALID_LOGIN_TOKEN'))
    if expired:
        send_login_instructions(user)
        do_flash(*get_message('LOGIN_EXPIRED', email=user.email,
                              within=_security.login_within))
    if invalid or expired:
        return redirect(url_for('login'))

    login_user(user)
    after_this_request(_commit)
    do_flash(*get_message('PASSWORDLESS_LOGIN_SUCCESSFUL'))

    return redirect(get_post_login_redirect())

Example 5

Project: WAPT Source File: views.py
Function: confirm_email
def confirm_email(token):
    """View function which handles a email confirmation request."""

    expired, invalid, user = confirm_email_token_status(token)

    if not user or invalid:
        invalid = True
        do_flash(*get_message('INVALID_CONFIRMATION_TOKEN'))
    if expired:
        send_confirmation_instructions(user)
        do_flash(*get_message('CONFIRMATION_EXPIRED', email=user.email,
                              within=_security.confirm_email_within))
    if invalid or expired:
        return redirect(get_url(_security.confirm_error_view) or
                        url_for('send_confirmation'))

    if user != current_user:
        logout_user()
        login_user(user)

    if confirm_user(user):
        after_this_request(_commit)
        msg = 'EMAIL_CONFIRMED'
    else:
        msg = 'ALREADY_CONFIRMED'

    do_flash(*get_message(msg))

    return redirect(get_url(_security.post_confirm_view) or
                    get_url(_security.post_login_view))

Example 6

Project: WAPT Source File: views.py
Function: reset_password
@anonymous_user_required
def reset_password(token):
    """View function that handles a reset password request."""

    expired, invalid, user = reset_password_token_status(token)

    if invalid:
        do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN'))
    if expired:
        do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email,
                              within=_security.reset_password_within))
    if invalid or expired:
        return redirect(url_for('forgot_password'))

    form = _security.reset_password_form()

    if form.validate_on_submit():
        after_this_request(_commit)
        update_password(user, form.password.data)
        do_flash(*get_message('PASSWORD_RESET'))
        login_user(user)
        return redirect(get_url(_security.post_reset_view) or
                        get_url(_security.post_login_view))

    return _security.render_template(config_value('RESET_PASSWORD_TEMPLATE'),
                                     reset_password_form=form,
                                     reset_password_token=token,
                                     **_ctx('reset_password'))

Example 7

Project: WAPT Source File: views.py
Function: change_password
@login_required
def change_password():
    """View function which handles a change password request."""

    form_class = _security.change_password_form

    if request.json:
        form = form_class(MultiDict(request.json))
    else:
        form = form_class()

    if form.validate_on_submit():
        after_this_request(_commit)
        change_user_password(current_user, form.new_password.data)
        if request.json is None:
            do_flash(*get_message('PASSWORD_CHANGE'))
            return redirect(get_url(_security.post_change_view) or
                            get_url(_security.post_login_view))

    if request.json:
        form.user = current_user
        return _render_json(form)

    return _security.render_template(config_value('CHANGE_PASSWORD_TEMPLATE'),
                                     change_password_form=form,
                                     **_ctx('change_password'))

Example 8

Project: fedocal Source File: api.py
@APP.route('/api/calendars/', methods=['GET', 'POST'])
def api_calendars():
    """
Retrieve calendars
==================

The ``/api/calendars/`` endpoint returns the meetings meeting the
provided criteria.

Response format
---------------

Sample response:

.. code-block:: javascript

    {
        "calendars": [
            {
                "calendar_description": "test",
                "calendar_editor_group": "packager2",
                "calendar_admin_group": "packager",
                "calendar_contact": "test",
                "calendar_name": "test"
            },
            {
                "calendar_description": "asd",
                "calendar_editor_group": "",
                "calendar_admin_group": "",
                "calendar_contact": "asd",
                "calendar_name": "Another test"
            }
        ]
    }
    """
    @flask.after_this_request
    def callback(response):
        """ Handle case the query was an JQuery ajax call. """
        return check_callback(response)

    calendars = fedocallib.get_calendars(SESSION)

    output = {"calendars": [calendar.to_json() for calendar in calendars]}

    return flask.Response(
        response=json.dumps(output),
        status=200,
        mimetype='application/json'
    )

Example 9

Project: fedocal Source File: api.py
@APP.route('/api/locations/', methods=['GET', 'POST'])
def api_locations():
    """
Retrieve locations
==================

The ``/api/locations/`` endpoint returns the locations where meetings are
happening.

Response format
---------------

Sample response:

.. code-block:: javascript

    {
        "locations": [

        ]
    }
    """
    @flask.after_this_request
    def callback(response):
        """ Handle case the query was an JQuery ajax call. """
        return check_callback(response)

    list_locations = fedocallib.get_locations(SESSION)

    output = {"locations": list_locations}

    return flask.Response(
        response=json.dumps(output),
        status=200,
        mimetype='application/json'
    )

Example 10

Project: fedocal Source File: api.py
@APP.route('/api/locations/search/', methods=['GET'])
def api_locations_search():
    """
Retrieve locations
==================

The ``/api/locations/search/`` endpoint can be used to dynamically search
for specified locations.

:arg keyword: Specified using GET parameters this keyword is used to filter
    the list of locations having it in their name.

Response format
---------------

Sample response:

.. code-block:: javascript

    {
        "locations": [
            "EMEA",
            "#[email protected]"
        ]
    }
    """
    @flask.after_this_request
    def callback(response):
        """ Handle case the query was an JQuery ajax call. """
        return check_callback(response)

    keyword = flask.request.args.get('keyword', None)

    if not keyword:
        output = {"error": "no keyword provided"}
        return flask.Response(
            response=json.dumps(output),
            status=400,
            mimetype='application/json'
        )

    if '*' not in keyword:
        keyword = '*%s*' % keyword

    list_locations = fedocallib.search_locations(SESSION, keyword)

    # filter out all locations containing '#'
    # https://fedorahosted.org/fedocal/ticket/118
    list_locations = [_loc for _loc in list_locations if _loc.count('#') == 0]

    output = {"locations": list_locations}

    return flask.Response(
        response=json.dumps(output),
        status=200,
        mimetype='application/json'
    )

Example 11

Project: fedocal Source File: api.py
@APP.route('/api/meetings/', methods=['GET', 'POST'])
@APP.route('/api/meetings', methods=['GET', 'POST'])
def api_meetings():
    """
Retrieve meetings
=================

The ``/api/meetings/`` endpoint returns the meetings meeting the
provided criteria.

Response format
----------------

Sample response:

.. code-block:: javascript

    {
        "meetings": [
            {
                "meeting_time_start": "23:00:00",
                "meeting_information": "",
                "meeting_time_stop": "23:00:00",
                "calendar_name": "test",
                "meeting_date_end": "2013-05-27",
                "meeting_manager": "pingou2,",
                "meeting_date": "2013-05-27",
                "meeting_name": "test1.5",
                "meeting_location": "None"
            },
            {
                "meeting_time_start": "06:00:00",
                "meeting_information": "",
                "meeting_time_stop": "07:00:00",
                "calendar_name": "test",
                "meeting_date_end": "2013-05-28",
                "meeting_manager": "pingou,",
                "meeting_date": "2013-05-28",
                "meeting_name": "test3",
                "meeting_location": null
            }
        ],
        "arguments": {
            "start": "2013-05-04",
            "calendar": "test",
            "end": "2013-11-30",
            "region": null
        }
    }


The ``arguments`` item in the root dictionary contains all possible
arguments, and displays the value used (the default if the argument
was not provided).

Time arguments
--------------

Below is a table describing what timeframe messages are received from
depending on what combination of time options you provide.

========= ======= =================
``start`` ``end`` Message timeframe
========= ======= =================
no        no      the last 30 days and the coming 180 days
**yes**   no      from ``start`` until the coming 180 days
no        **yes** the last 30 days until ``end``
**yes**   **yes** between ``start`` and ``end``
========= ======= =================

``start``
  Return results starting at date ``start`` (prefered format is
  "+%Y-%m-%d" see ``date "+%Y-%m-%d"``).

  Default: 30 days ago ``date "+%Y-%m-%d" -d "30 days ago"``

``end``
  Return results ending at date ``end`` (prefered format is
  "+%Y-%m-%d" see ``date "+%Y-%m-%d"``).

  Default: coming 180 days ``date "+%Y-%m-%d" -d "180 days"``

Filter arguments
----------------

``calendar``
  Restrict the meetings to a specific calendar.

  Default: all calendars

``region``
  Restrict the meeting to a specific region.

  If the calendar does not have support for regions enabled, no
  meetings will be found matching this criteria and no meetings will
  be returned.

  Default: all regions

    """
    @flask.after_this_request
    def callback(response):
        """ Handle case the query was an JQuery ajax call. """
        return check_callback(response)

    startd = flask.request.args.get('start', None)
    if startd is None:
        startd = datetime.date.today() - datetime.timedelta(days=30)
    else:
        try:
            startd = parser.parse(startd).date()
        except (ValueError, TypeError):
            output = {"meetings": [],
                      "error": "Invalid start date format: %s" % startd}
            return flask.Response(
                response=json.dumps(output),
                status=400,
                mimetype='application/json')

    endd = flask.request.args.get('end', None)
    if endd is None:
        endd = datetime.date.today() + datetime.timedelta(days=180)
    else:
        try:
            endd = parser.parse(endd).date()
        except (ValueError, TypeError):
            output = {"meetings": [],
                      "error": "Invalid end date format: %s" % endd}
            return flask.Response(
                response=json.dumps(output),
                status=400,
                mimetype='application/json')

    calendar_name = flask.request.args.get('calendar', None)
    location = flask.request.args.get('location', None)
    region = flask.request.args.get('region', None)
    location = location or region

    if calendar_name:
        calendarobj = Calendar.by_id(SESSION, calendar_name)

        if not calendarobj:
            output = {
                "meetings": [],
                "error": "Invalid calendar provided: %s" % calendar_name}
            return flask.Response(
                response=json.dumps(output),
                status=400,
                mimetype='application/json')

    status = 200
    meetings = []
    try:
        if calendar_name:
            if location:
                # print "calendar and region"
                meetings = fedocallib.get_meetings_by_date_and_location(
                    SESSION, calendar_name, startd, endd, location)
            else:
                # print "calendar and no region"
                meetings = fedocallib.get_by_date(
                    SESSION, calendarobj, startd, endd)
        else:
            meetings = []
            if location:
                # print "no calendar and region"
                meetings.extend(
                    fedocallib.get_by_date_at_location(
                        SESSION, location, startd, endd)
                )
            else:
                # print "no calendar and no region"
                for calendar in fedocallib.get_calendars(SESSION):
                    meetings.extend(fedocallib.get_by_date(
                        SESSION, calendar, startd, endd))
    except SQLAlchemyError, err:  # pragma: no cover
        status = 500
        LOG.debug('Error in api_meetings')
        LOG.exception(err)

    output = {}
    output['arguments'] = {
        'start': startd.strftime('%Y-%m-%d'),
        'end': endd.strftime('%Y-%m-%d'),
        'calendar': calendar_name,
        'location': location,
    }

    meetings_json = []
    for meeting in meetings:
        meetings_json.append(meeting.to_json())
    output['meetings'] = meetings_json

    return flask.Response(
        response=json.dumps(output),
        status=status,
        mimetype='application/json'
    )

Example 12

Project: flask-security Source File: views.py
Function: reset_password
@anonymous_user_required
def reset_password(token):
    """View function that handles a reset password request."""

    expired, invalid, user = reset_password_token_status(token)

    if invalid:
        do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN'))
    if expired:
        send_reset_password_instructions(user)
        do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email,
                              within=_security.reset_password_within))
    if invalid or expired:
        return redirect(url_for('forgot_password'))

    form = _security.reset_password_form()

    if form.validate_on_submit():
        after_this_request(_commit)
        update_password(user, form.password.data)
        do_flash(*get_message('PASSWORD_RESET'))
        login_user(user)
        return redirect(get_url(_security.post_reset_view) or
                        get_url(_security.post_login_view))

    return _security.render_template(config_value('RESET_PASSWORD_TEMPLATE'),
                                     reset_password_form=form,
                                     reset_password_token=token,
                                     **_ctx('reset_password'))

Example 13

Project: flask-social Source File: views.py
@login_required
def remove_all_connections(provider_id):
    """Remove all connections for the authenticated user to the
    specified provider
    """
    provider = get_provider_or_404(provider_id)

    ctx = dict(provider=provider.name, user=current_user)

    deleted = _datastore.delete_connections(user_id=current_user.get_id(),
                                            provider_id=provider_id)
    if deleted:
        after_this_request(_commit)
        msg = ('All connections to %s removed' % provider.name, 'info')
        connection_removed.send(current_app._get_current_object(),
                                user=current_user._get_current_object(),
                                provider_id=provider_id)
    else:
        msg = ('Unable to remove connection to %(provider)s' % ctx, 'error')

    do_flash(*msg)
    return redirect(request.referrer)

Example 14

Project: flask-social Source File: views.py
@login_required
def remove_connection(provider_id, provider_user_id):
    """Remove a specific connection for the authenticated user to the
    specified provider
    """
    provider = get_provider_or_404(provider_id)

    ctx = dict(provider=provider.name, user=current_user,
               provider_user_id=provider_user_id)

    deleted = _datastore.delete_connection(user_id=current_user.get_id(),
                                           provider_id=provider_id,
                                           provider_user_id=provider_user_id)

    if deleted:
        after_this_request(_commit)
        msg = ('Connection to %(provider)s removed' % ctx, 'info')
        connection_removed.send(current_app._get_current_object(),
                                user=current_user._get_current_object(),
                                provider_id=provider_id)
    else:
        msg = ('Unabled to remove connection to %(provider)s' % ctx, 'error')

    do_flash(*msg)
    return redirect(request.referrer or get_post_login_redirect())

Example 15

Project: flask-social Source File: views.py
def connect_handler(cv, provider):
    """Shared method to handle the connection process

    :param connection_values: A dictionary containing the connection values
    :param provider_id: The provider ID the connection shoudl be made to
    """
    cv.setdefault('user_id', current_user.get_id())
    connection = _datastore.find_connection(
        provider_id=cv['provider_id'], provider_user_id=cv['provider_user_id'])

    if connection is None:
        after_this_request(_commit)
        connection = _datastore.create_connection(**cv)
        msg = ('Connection established to %s' % provider.name, 'success')
        connection_created.send(current_app._get_current_object(),
                                user=current_user._get_current_object(),
                                connection=connection)
    else:
        msg = ('A connection is already established with %s '
               'to your account' % provider.name, 'notice')
        connection_failed.send(current_app._get_current_object(),
                               user=current_user._get_current_object())

    redirect_url = session.pop(config_value('POST_OAUTH_CONNECT_SESSION_KEY'),
                               get_url(config_value('CONNECT_ALLOW_VIEW')))

    do_flash(*msg)
    return redirect(redirect_url)

Example 16

Project: flask-social Source File: views.py
@anonymous_user_required
def login_handler(response, provider, query):
    """Shared method to handle the signin process"""

    connection = _datastore.find_connection(**query)

    if connection:
        after_this_request(_commit)
        token_pair = get_token_pair_from_oauth_response(provider, response)
        if (token_pair['access_token'] != connection.access_token or
            token_pair['secret'] != connection.secret):
            connection.access_token = token_pair['access_token']
            connection.secret = token_pair['secret']
            _datastore.put(connection)
        user = connection.user
        login_user(user)
        key = _social.post_oauth_login_session_key
        redirect_url = session.pop(key, get_post_login_redirect())

        login_completed.send(current_app._get_current_object(),
                             provider=provider, user=user)

        return redirect(redirect_url)

    login_failed.send(current_app._get_current_object(),
                      provider=provider,
                      oauth_response=response)

    next = get_url(_security.login_manager.login_view)
    msg = '%s account not associated with an existing user' % provider.name
    do_flash(msg, 'error')
    return redirect(next)