简体   繁体   中英

Why can't I just add Content-Type:text/html to a text file when Python can?

This will seem like a stupid question to most of you but why can't I do this:

Content-Type:text/html

<html>
<head><title>Hello</title></head>
<body>
<h1>Hello, World!</h1>
</body>
</html>

in a file called test.txt and open it in my browser as html when a Python script can do this:

#!/usr/bin/python

print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'

and everything works fine. I can't see any difference, they are both printing Content-Type:text/html at the top of the information the browser has requested.

An HTTP response consists of headers and body, separate by the first \\r\\n\\r\\n received. By the time a web server sends an ordinary file, it has already sent all the headers, and the separator.
When a script is run, however, the headers are not sent automatically.

So in the first case, your webserver guessed the content-type from the extension, and sent appropriate headers, before sending the contents of the file. In the second the script sent an overriding header for the content-type. It's then up to the web-server how it handles this, in terms of inserting the other standard http headers.

EDIT: Apache use mod_mine and /etc/mime.types to map file extensions to Content-Types. It probably defaults to text/plain for anything that doesn't have an extension it understands.

The browser probably works off the extension only if it doesn't have a Content-Type to use.

Plain files are assumed to just contain the data, and the headers are generated by the web server, whereas cgi scripts are expected/allowed to generate their own headers.

When browsers read directly from a file, they aren't looking for http headers. When a python script is answering a browser's http request, that is different, and the browser expects the first lines to be http headers which it then interprets as you would expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM