Score:0

Use Multiple Azure Application Insights in one Flask app

ag flag

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

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.