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')