0

Hi i have a flask application that Build as a docker image to serve as an api

this image is deployed to multiple environments (DEV/QA/PROD)

i want to use an applicationInsight for each environment

using a single application Insight works fine

here is a code snippet

app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = APPINSIGHTS_INSTRUMENTATIONKEY
appinsights = AppInsights(app)

@app.after_request
def after_request(response):
    appinsights.flush()
    return response

but to have multiple application i need to configure app.config with the key of the app insight

i thought of this solution which thourghs errors

here a snippet :

app = Flask(__name__)
def monitor(key):
    app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = key
    appinsights = AppInsights(app)
    
@app.after_request
def after_request(response):
    appinsights.flush()
    return response

@app.route("/")
def hello():
    hostname = urlparse(request.base_url).hostname
    print(hostname)
    if hostname == "dev url":
       print('Dev')
       monitor('3ed57a90-********')
    if hostname == "prod url":
       print('prod')
       monitor('941caeca-********-******')
    return "hello"

but apparently flask can't proccess traitments after the request is done

error Message :

AssertionError: The setup method 'errorhandler' can no longer be called on the application. It has already handled its first request, any changes will not be applied consistently. Make sure all imports, decorators, functions, etc. needed to set up the application are done before running it.

i hope someone can guide me to a better solution

thanks in advance

0 Answers0