Access Apache SetEnv variable from Django wsgi.py file

前端 未结 5 1769
盖世英雄少女心
盖世英雄少女心 2020-12-14 09:53

I\'m trying to separate out Django\'s secret key and DB pass into environmental variables, as widely suggested, so I can use identical code bases between local/production se

5条回答
  •  失恋的感觉
    2020-12-14 10:42

    Here's an alternative solution that's as future-proof as get_wsgi_application. It even lets you set environment variables to use in your Django initialization.

    # in wsgi.py
    
    KEYS_TO_LOAD = [
        # A list of the keys you'd like to load from the WSGI environ
        # into os.environ
    ]
    
    def loading_app(wsgi_environ, start_response):
        global real_app
        import os
        for key in KEYS_TO_LOAD:
            try:
                os.environ[key] = wsgi_environ[key]
            except KeyError:
                # The WSGI environment doesn't have the key
                pass
        from django.core.wsgi import get_wsgi_application
        real_app = get_wsgi_application()
        return real_app(wsgi_environ, start_response)
    
    real_app = loading_app
    
    application = lambda env, start: real_app(env, start)
    

    I'm not 100% clear how mod_wsgi manages its processes, but I assume it doesn't re-load the WSGI app very often. If so, the performance penalty from initializing Django will only happen once, inside the first request.

    Alternatively, if you don't need to set the environment variables before initializing Django, you can use the following :

    # in wsgi.py
    
    KEYS_TO_LOAD = [
        # A list of the keys you'd like to load from the WSGI environ
        # into os.environ
    ]
    
    from django.core.wsgi import get_wsgi_application
    django_app = get_wsgi_application()
    
    def loading_app(wsgi_environ, start_response):
        global real_app
        import os
        for key in KEYS_TO_LOAD:
            try:
                os.environ[key] = wsgi_environ[key]
            except KeyError:
                # The WSGI environment doesn't have the key
                pass
        real_app = django_app
        return real_app(wsgi_environ, start_response)
    
    real_app = loading_app
    
    application = lambda env, start: real_app(env, start)
    

提交回复
热议问题