Why does wsgiref.simple_server report content-type

2019-09-03 19:23发布

问题:

Output from client.py is text/plain although no content-type header was sent to the server.
Why?

# ---------------------------------------------- server.py
from wsgiref.simple_server import make_server

def simple_app(environ, start_response):
    print environ.get('CONTENT_TYPE')
    start_response('200 OK', [])
    return []

make_server('localhost', 88, simple_app).serve_forever()

# ---------------------------------------------- client.py
import subprocess
import urllib2

p = subprocess.Popen(['python', '-u', 'server.py'])
req = urllib2.Request('http://localhost:88', headers={})
assert not req.has_header('content-type')
urllib2.urlopen(req).read()
p.terminate()

回答1:

The type text/plain is the default for MIME, in section 5.2 Content Type Defaults.

The WSGI simple_server uses BaseHTTPRequestHandler which in turn uses a mimetools.Message class to parse the headers sent by the client -- here is where it sets the default:

# mimetools.py

class Message(rfc822.Message):

    def parsetype(self):
        str = self.typeheader
        if str is None:
            str = 'text/plain'