开发者

How to out put HTML in Browser with Python

I've got a forms processing python script that just emails the input to me, then I just want to display a web page that say Message Sent with in Heading 1. The email and forms processing part is working, but all I get is text displayed in the browser instead on the browser rendering the HTML.

print 'Content-type: text/html\n\n'

I suspect its due to this line, any pls help?

开发者_开发知识库

this is what im trying to print

print "<html><head><title></title></head></html>"

I just tried running this test script

print
print 'Content-type: text/html\n\n'

print '<HTML><HEAD><TITLE>Python Sample CGI</TITLE></HEAD>'
print '<BODY>'
print '<H1>This is a header</H1>'

print '<p>' #this is a comment
print 'See this is just like most other HTML'
print '<br>'
print '</BODY>'
print '</html>

this is what I see in the browser after running it

Content-type: text/html


<HTML><HEAD><TITLE>Python Sample CGI</TITLE></HEAD>
<BODY>
<H1>This is a header</H1>
<p>
See this is just like most other HTML
<br>
</BODY>
</html>


This is your problem:

print
print 'Content-type: text/html\n\n'

Your HTTP header needs to be the first thing printed. You've got a blank line before it, which marks the end of the HTTP header. So the browser takes what you intended to be the HTTP header as the beginning of the response body. It doesn't see any HTTP header (except any provided by the Web server), certainly no Content-type: header.

Either the server or your browser is defaulting to a content type of text/plain in this case, so the browser does not try to interpret the HTML tags. Et voila.

TL;DR: Take out the first blank print.


You can simply redirect the user to the page you'd like them to see:

print 'Location: /thanksforemail.html'
print


Couple of things, firstly make sure that you have the correct she-bang notation at the top:

#!/usr/bin/env python

also, make sure that you import cgi, cgitb, and you have cgitb.enable(). (The cgitb stuff is not as important though)

Finally, make sure that your file is chmoded correctly. I usually make mine with permission 755. Hope that helps!


Keep your yourfile.py file inside cgi-bin folder. keep the CGIHTTPServer.py file outside cgi-bin folder. Run CGIHTTPServer.py file after running your yourfile.py file. You will get a port number may be 8000. Then open your browser and type : localhost:8000/cgi-bin/yourfile.py

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜