WSGI using os.environment

Many people advised me to start using WSGI to avoid unnecessary wrestling with code to be able to modify my web system code (because of the expired feature CGI) without using complicated WSGI.

So I am trying to use WSGI. After installing WSGI, I successfully tested my first simple function. However, to my surprise, the function ‘os.environment’ contains NO important keys such as SERVER_NAME, REQUEST_METHOD and QUERY_STRING. Why not?

My code at server contains:

#!C:/Program Files/Python/python.exe
from wsgiref.simple_server import make_server

def web_app(environment, start_response):
  status = '200 OK'
  headers = [('Content-type', 'text/html; charset=utf-8')]
  start_response(status, headers)
  import os
  tblose = os.environ
  srvnmx = tblose.get('SERVER_NAME')
  if srvnmx == None:
    srvnmx = '?'
  rqsmth = tblose.get('REQUEST_METHOD')
  if rqsmth == None:
    rqsmth = '?'
  rqsqry = tblose.get('QUERY_STRING')
  if rqsqry == None:
    rqsqry = '?'
  wrk = str.encode(''.join(['Hello, I just created my <strong>first</strong> WSGI',
                            '<br>SESSIONNAME=', tblose['SESSIONNAME'], 
                            '<br>SYSTEMDRIVE=', tblose['SYSTEMDRIVE'], 
                            '<br>SYSTEMROOT', tblose['SYSTEMROOT'], 
                            '<br>SERVER_NAME=', srvnmx,
                            '<br>REQUEST_METHOD=', rqsmth,
                            '<br>QUERY_STRING=', rqsqry]))
  return [wrk]

with make_server('', 8000, web_app) as server:
  print('\nServing on port 8000...')
  print('\nVisit http:')
  print('\nTo kill the server enter \'control + C\'.')

My first browser in put is:

Output on my browser contains:

Hello, I just created my first WSGI

Help, what should I have anything wrong?

The docs say what you can expect in os.environ PEP 3333 – Python Web Server Gateway Interface v1.0.1 |

It says that SERVER_NAME is optional.

When HTTP_HOST is not set, these variables can be combined to determine a default

I really don’t understand your statement about HTTP-HOST.
My request in the browser is: localhost:8000/server/pythonwsgi/
I am wondering why WSGI does not give SERVER_NAME, REQUEST_METHOD and QUERY_STRING in my function web_app.
Where would I have done something wrong?

You’ve been given an environment dictionary. Use of the actual operating system environment is unnecessary and insecure, and WSGI uses a much more efficient strategy instead (while still retaining some of the CGI inspiration). Try looking inside environment for the keys you want, or possibly printing the whole thing out.

I still think you’ll do MUCH better with a framework like Flask though. The wsgiref module is there as a reference implementation and isn’t intended to be easy to build actual applications with.