Python, WSGI and HTTP Learning
#!/usr/bin/env python2
# coding: utf-8
import json
import os
from wsgiref.simple_server import make_server
__KEYS__ = [
'HTTP_X_FORWARDED_FOR',
'REMOTE_ADDR',
'HTTP_ACCEPT_ENCODING',
'REMOTE_HOST',
'CONTENT_TYPE',
'HTTP_DNT',
'SERVER_NAME',
'HTTP_CONNECTION',
'HTTP_USER_AGENT',
'LOGNAME',
'HTTP_COOKIE',
'REQUEST_METHOD',
'HTTP_ACCEPT_LANGUAGE',
'HTTP_ACCEPT',
'HTTP_CACHE_CONTROL',
'HTTP_UPGRADE_INSECURE_REQUESTS',
'HTTP_HOST',
'SERVER_PORT',
'HOME',
'SERVER_SOFTWARE',
'SERVER_PROTOCOL',
'USER'
]
def forever(app, poll_interval=0.5):
app.serve_forever(poll_interval=poll_interval)
def single(app):
app.handle_request()
def home(env, start_response):
HEADERS = dict()
STATUS = '200 OK'
stream = env['wsgi.input']
BODY = {k: env.get(k) for k in __KEYS__}
RESPONSE = json.dumps(BODY, encoding='utf-8')
HEADERS['Content-Type'] = 'application/json'
HEADERS['Content-Length'] = str(len(RESPONSE))
start_response(STATUS, HEADERS.items())
return RESPONSE
def main():
application = make_server(
host='0.0.0.0',
port=int(os.environ.get('PORT', 8000)),
app=home)
# single(application)
forever(application)
if __name__ == '__main__':
main()