I'm trying to add a before_first_request
functionality to a specific Blueprint
of my Flask
application. Below you can see that I have two Blueprints
, public and admin.
I have tried this but had no success: https://stackoverflow.com/a/27401269/7077556
This only works for the the first request that is made to the application, any other request from other device and ip after that first one is not handled by this "custom" before_first_request
.
I want to run a function just for the first request that a client makes to the public Blueprint
.
How can I do this? Thanks in advance
This is the code that I'm using:
from flask import Flask, Blueprint
application = Flask(__name__)
# PUBLIC Blueprint
public = Blueprint('public', __name__, static_url_path='/public', static_folder='static', template_folder='templates')
# ADMIN Blueprint
admin = Blueprint('admin', __name__, static_url_path='/admin', static_folder='static', template_folder='templates')
# Before First Request To Public BP
from threading import Lock
public._before_request_lock = Lock()
public._got_first_request = False
@public.before_request
def init_public_bp():
if public._got_first_request:
return
else:
with public._before_request_lock:
public._got_first_request = True
print('THIS IS THE FIRST REQUEST!')
# Do more stuff here...
# PUBLIC ROUTE
@public.route("/")
def public_index():
return 'Hello World!'
# ADMIN ROUTE
@admin.route('/')
def admin_index():
return 'Admin Area!'
# Register PUBLIC Blueprint
application.register_blueprint(public)
# Register ADMIN Blueprint
application.register_blueprint(admin, url_prefix='/admin')
if __name__ == "__main__":
application.run(host='0.0.0.0')