Python flask.after_this_request() Examples

The following are 14 code examples of flask.after_this_request(). 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: basic.py    From Flask-P2P with MIT License 5 votes vote down vote up
def test_after_request_processing(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.after_this_request
            def foo(response):
                response.headers['X-Foo'] = 'a header'
                return response
            return 'Test'
        c = app.test_client()
        resp = c.get('/')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.headers['X-Foo'], 'a header') 
Example #2
Source File: main.py    From cas-eval with Apache License 2.0 5 votes vote down vote up
def save_page():
    @flask.after_this_request
    def add_headers(response):
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response
    values = flask.request.values
    if values.get('type', '') == 'Serp':
        try:
            user_id = Session.get_user_id(values['url'])
        except Exception as e:
            app.logger.error(e)
            return 'Incorrect user_id used', 400
        try:
            query = Session.get_query(values['url'])
        except Exception as e:
            app.logger.error(e)
            return 'No query set?', 400
        for k in ['data', 'tab_id', 'time']:
            if k not in values:
                return 'Missing param: %s' % k, 400
        data = values['data']
        try:
            ts = Session.convert_time(values['time'])
        except Exception as e:
            app.logger.error(e)
            return 'Incorrect timestamp', 400
        session = Session(id=values['tab_id'], user_id=user_id, q=query,
                serp_html=data, start_ts=ts)
        n = len(data)
        while n > 1:
            session.serp_html = data[:n]
            try:
                session.put()
                break
            except apiproxy_errors.RequestTooLargeError as e:
                app.logger.error(e)
                n /= 2
        return 'Saved', 201
    return 'Only support saving SERPs using POST requests, sorry.', 403 
Example #3
Source File: main.py    From cas-eval with Apache License 2.0 5 votes vote down vote up
def save_settings():
    @flask.after_this_request
    def add_headers(response):
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response
    values = flask.request.values
    try:
        user_id = Session.get_user_id(values['url'])
    except Exception as e:
        app.logger.error(e)
        return 'Incorrect user_id used', 400
    for k in ['data', 'tab_id', 'time']:
        if k not in values:
            return 'Missing param: %s' % k, 400
    try:
        ts = Session.convert_time(values['time'])
    except Exception as e:
        app.logger.error(e)
        return 'Incorrect timestamp', 400
    mute_period_m = 0
    for data in values['data'].split(','):
        try:
            mute_period_m = max(mute_period_m, UserSettings.convert_mute_period_m(data))
        except Exception as e:
            app.logger.error(e)
            return 'Incorrect mute period settings: %s' % data, 400
    mute_deadline = UserSettings.get_mute_deadline(ts, mute_period_m)
    settings = ndb.Key(UserSettings, user_id).get()
    if settings is None:
        # Create settings for the current user
        settings = UserSettings(id=user_id, mute_deadline=mute_deadline, ts=ts)
        settings.put()
    elif settings.mute_deadline is None or settings.mute_deadline < mute_deadline:
        settings.mute_deadline = mute_deadline
        settings.ts = ts
        settings.put()
    return 'Saved', 201 
Example #4
Source File: main.py    From cas-eval with Apache License 2.0 5 votes vote down vote up
def ask_feedback():
    @flask.after_this_request
    def add_headers(response):
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response
    return '10', 200
    values = flask.request.values
    now = datetime.now()
    try:
        user_id = Session.get_user_id(values['url'])
    except:
        return 'Incorrect user_id used', 400
    settings = ndb.Key(UserSettings, user_id).get()
    if settings is None:
        # Create settings for the current user
        settings = UserSettings(id=user_id, ts=now)
    if settings.mute_deadline is not None and settings.mute_deadline > now:
        return '0', 200
    questionnaire_left = 10
    for prev_shown_ts in reversed(settings.questionnaire_shown_ts):
        if prev_shown_ts < now - timedelta(hours=24):
            break
        questionnaire_left -= 1
    if random.random() < 0.5:
        # Suppress the popup for 50% of all SERPs.
        questionnaire_left = 0
    if questionnaire_left > 0:
        settings.questionnaire_shown_ts.append(now)
        settings.put()
    return str(questionnaire_left), 200 
Example #5
Source File: main.py    From cas-eval with Apache License 2.0 5 votes vote down vote up
def log():
    @flask.after_this_request
    def add_headers(response):
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response
    values = flask.request.values
    tab_id = values.get('tab_id', '')
    session = ndb.Key(Session, tab_id).get()
    if session is None:
        return 'No sessions with tab_id = %s' % tab_id, 404
    elif session.shared:
        return 'Cannot update previously shared session with tab_id = %s' % tab_id, 403
    try:
        user_id = Session.get_user_id(values['url'])
    except:
        return 'Incorrect user_id used', 400
    if session.user_id != user_id:
        return 'Session does not belong to %s' % user_id, 403
    try:
        if 'buffer' in values:
            buffer = json.loads(values['buffer'])
        else:
            buffer = [flask.request.url.split('?', 1)[-1]]
        actions = []
        for log_str in buffer:
            log_item = urlparse.parse_qs(log_str)
            ts = Session.convert_time(log_item['time'][0])
            event_type = log_item.get('ev', ['UNKNOWN'])[0]
            fields = {k: v[0] for (k, v) in log_item.iteritems() if k not in ['ev', 'time']}
            actions.append(Action(ts=ts, event_type=event_type, fields=fields))
        session.actions += actions
        session.put()
        return 'Updated', 200

    except Exception as e:
        app.logger.error(e)
        app.logger.error('Buffer: %s' % values.get('buffer', ''))
        return 'Incorrect buffer contents', 400 
Example #6
Source File: app.py    From trace-examples with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def joke():
    res = requests.get('https://icanhazdadjoke.com/', headers=dict(Accept='text/plain'))
    res.raise_for_status()

    @after_this_request
    def after_joke(response):
        print('Hook: after_this_request')
        return response

    return res.content 
Example #7
Source File: basic.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_after_request_processing(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.after_this_request
            def foo(response):
                response.headers['X-Foo'] = 'a header'
                return response
            return 'Test'
        c = app.test_client()
        resp = c.get('/')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.headers['X-Foo'], 'a header') 
Example #8
Source File: basic.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_after_request_processing(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.after_this_request
            def foo(response):
                response.headers['X-Foo'] = 'a header'
                return response
            return 'Test'
        c = app.test_client()
        resp = c.get('/')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.headers['X-Foo'], 'a header') 
Example #9
Source File: basic.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_after_request_processing(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.after_this_request
            def foo(response):
                response.headers['X-Foo'] = 'a header'
                return response
            return 'Test'
        c = app.test_client()
        resp = c.get('/')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.headers['X-Foo'], 'a header') 
Example #10
Source File: basic.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_after_request_processing(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.after_this_request
            def foo(response):
                response.headers['X-Foo'] = 'a header'
                return response
            return 'Test'
        c = app.test_client()
        resp = c.get('/')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.headers['X-Foo'], 'a header') 
Example #11
Source File: basic.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_after_request_processing(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.after_this_request
            def foo(response):
                response.headers['X-Foo'] = 'a header'
                return response
            return 'Test'
        c = app.test_client()
        resp = c.get('/')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.headers['X-Foo'], 'a header') 
Example #12
Source File: basic.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def test_after_request_processing(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.after_this_request
            def foo(response):
                response.headers['X-Foo'] = 'a header'
                return response
            return 'Test'
        c = app.test_client()
        resp = c.get('/')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.headers['X-Foo'], 'a header') 
Example #13
Source File: basic.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_after_request_processing(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.after_this_request
            def foo(response):
                response.headers['X-Foo'] = 'a header'
                return response
            return 'Test'
        c = app.test_client()
        resp = c.get('/')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.headers['X-Foo'], 'a header') 
Example #14
Source File: basic.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_after_request_processing(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            @flask.after_this_request
            def foo(response):
                response.headers['X-Foo'] = 'a header'
                return response
            return 'Test'
        c = app.test_client()
        resp = c.get('/')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.headers['X-Foo'], 'a header')