CGI - HTML to python

那年仲夏 提交于 2021-01-29 19:00:31

问题


I am following the tutorial CGI, when I try to execute the program

#!C:/Python27/python.exe
# Import modules for CGI handling 
import cgi, cgitb 

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
first_name = form.getvalue('first_name')
last_name  = form.getvalue('last_name')

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"

The HTML file

<form action = "/cgi-bin/hello_get.py" method = "get">
First Name: <input type = "text" name = "first_name">  <br />

Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>

In my browser on submitting the values, my python file is displaying as it is. Blankly my code was shown by the browser. Even it didn't get the first name and last name. What is the problem?

I am unable to find where I am doing the mistake.


回答1:


If I understand correctly, you are saying that the web server is displaying the source of your Python program instead of executing the source. Based on your shebang specification, it appears you are running under Windows. Depending on what web server you are using, IIS or Apache for example, you need to configure the web server so that it knows that files with .py extensions are to be executed by the Python interpreter for it is clearly ignoring the shebang specification. For example, if using Apache your httpd configuration file might contain the following lines:

AddHandler cgi-script .py
ScriptInterpreterSource Registry-Strict

With the second line, the web server will ignore the shebang and use whatever program is associated with the filetype .py, which should be your Python interpreter. This is probably what you want as you may be upgrading your interpreter and its location changing. In this case you should probably code the shebang as:

#!/usr/bin/env python


来源:https://stackoverflow.com/questions/53912765/cgi-html-to-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!