Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check request method inside Python class?

Tags:

python

flask

I have a class for Flask:

class Likes(object):
    def __init__(self, model, table_id):
        self.model = model
        self.table_id = table_id

        if request.form["likes"] == 'like':
            query = self.model.query.filter_by(id=table_id).first()
            query.likes += 1
            db.session.commit()
            flash(u'Like =)) ' + query.title, 'info')
        elif request.form["likes"] == 'dislike':
            query = self.model.query.filter_by(id=table_id).first()
            query.likes -= 1
            db.session.commit()
            flash(u"Don't like =(" + query.title, 'info')

and I want to call this class every time user sent POST request, but every time I create an instance of my class I need add check request type:

# ...
if request.method == 'POST':
    Likes(Post, request.form["post_id"])
# ...

How can I improve my class and add inside it this check:

if request.method == 'POST':
    # ...

Solution: Use decorator @app.before_request

@app.before_request
def before_req():
    if request.method == 'POST':
        flash(u'Before request', 'success')
like image 355
Denis Avatar asked Sep 10 '15 08:09

Denis


1 Answers

You can use Flask.request_started signal to run something everytime a request arrive and then execute the code you require.

flask.request_started

This signal is sent before any request processing started but when the request context was set up. Because the request context is already bound, the subscriber can access the request with the standard global proxies such as request.

Have a look at the Flask's Signals chapter to learn more.

Use something like that in your code:

def create_like(sender, **extra):
    if request.method == 'POST':
        Likes(Post, request.form["post_id"])


from flask import request_started
request_started.connect(create_like, app)

This was adapted from the example for the documentation of Core Signals.

like image 185
amirouche Avatar answered Oct 02 '22 15:10

amirouche