The list of environment variables in WSGI application can be displayed using python code. But before that, you may want to see how to create WSGI aplication. To display the list of environment, firstly I create file named env.py and copy-paste the following code and don’t forget to save.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
###################### #file name: env.py ###################### from wsgiref.simple_server import make_server def application(environ, start_response): body = [ '%s: %s' % (key, value) for key, value \ in sorted(environ.items()) ] body = '\n'.join(body) status = '200 OK' headers = [ ('Content-Type', 'text/plain'), ('Content-Lenght',str(len(body))) ] start_response(status, headers) #return[body] #this line for python2 since wsgi made for python2 return[body.encode()] #this line is for python3 if __name__ == '__main__': server = make_server('localhost', 5000, application) server.serve_forever() |
Then I place the file in my work directory called D:\personal\flaskApp\pythoneveryday
Next step, activate my existed python environment which I already installed before. See how to create virtual environment for Python using Anaconda.
Next, I run the file env.py like following
Next, I open my browser and write http://localhost:5000 on the address bar to see what will happen
Explanation for codes in env.py
The environ.items() command will return a dictionary object containing all environment variables. The variable name will be used as the key and the contents of the variable will be used as the value of the dictionary object. Therefore, we can display the list of elements contained in the dictionary object using the following code
1 2 3 4 5 6 |
... body = [ '%s: %s' % (key, value) for key, value \ in sorted(environ.items()) ] ... |
by the code in sorted(environ.items()) above, the elements in the dictionary will be firsly sorted using the before being displayed.
Congratulation! now I can display the list of environment variables in WSGI application.