HTML forms not working with python - python

I've created a HTML page with forms, which takes a name and password and passes it to a Python Script which is supposed to print the persons name with a welcome message. However, after i POST the values, i'm just getting the Python code displayed in the browser and not the welcome message. I have stored the html file and python file in the cgi-bin folder under Apache 2.2. If i just run a simple hello world python script in the browser, the "Hello World" message is being displayed. I'm using WinXP, Python 2.5, Apache 2.2. the code that i'm trying to run is the following:
#!c:\python25\python.exe
import cgi
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
reshtml = """Content-Type: text/html\n
<html>
<head><title>Security Precaution</title></head>
<body>
"""
print reshtml
User = form['UserName'].value
Pass = form['PassWord'].value
if User == 'Gold' and Pass == 'finger':
print '<big><big>Welcome'
print 'mr. Goldfinger !</big></big><br>'
print '<br>'
else:
print 'Sorry, incorrect user name or password'
print '</body>'
print '</html>'
The answer to it might be very obvious, but its completely escaping me. I'm very new to Python so any help would be greatly appreciated.
Thanks.

This
i'm just getting the Python code
displayed in the browser
sounds like CGI handling with Apache and Python is not configured correctly.
You can narrow the test case by passing UserName and PassWord as GET parameters:
http://example.com/cgi-bin/my-script.py?UserName=Foo&PassWord=bar
What happens if you do this?

You may have to extract the field values like this
User = form.getfirst('UserName')
Pass = form.getfirst('PassWord')
I know, it's strange.

Related

HTML form return displays python code instead of executing

Coming from only basic front end experience here and running into trouble using method="get" on my python script.
The entire python code is returned to the browser instead of just the print statement. I am using python SimpleHTTPServer and expect that I may be missing some configuration, but I am having quite a bit of trouble determining a solution.
Here is the HTML:
<form name="search" action="\cgi-bin/test.py" method="get">
Search: <input type="text" name="searchbox">
<input type="submit" value="Submit">
</form>
Here is the Python (and also what gets returned to the browser when the form is submitted):
#!/usr/bin/env python3
import cgi
form = cgi.FieldStorage()
searchterm = form.getvalue('searchbox')
print(searchterm)
I know this is probably pretty basic, but I am stumped. I appreciate any guidance to be offered.
If you use Python 2 then you should use CGIHTTPServer instead of SimpleHTTPServer
python2 -m CGIHTTPServer
If you use Python 3 then you should use http.server --cgi
python3 -m http.server --cgi
And code has to be executable.
On Linux you do:
chmod +x cgi-bin/test.py
On Windows you have to assign extension .py to python. I don't use Windows to give more info.
Script has to send information what type of data it sends - text, HTML, image, PDF, Excel, etc. - and empty line which separates header and body.
print("Content-Type: text/html")
print() # empty line beetwin header and body
print(searchterm)
Without this information it may send it as file for downloading.
If you want to display text in console then you may have to use "standard error" because "standard output" and print() is send to browser
import sys
sys.stderr.write(searchterm + '\n')
#!/usr/bin/env python3
import cgi
import sys
form = cgi.FieldStorage()
searchterm = form.getvalue('searchbox')
# send text on console
sys.stderr.write('searchterm: ' + searchterm + '\n')
# send text to browser
#print("Content-Type: text/plain") # send all as text
print("Content-Type: text/html") # send all as HTML
print()
print(searchterm)

How to run a Python script in a web page

I'm very new to Python. I just know what Python is.
I have created the below code (in Python IDLE):
print "Hi Welcome to Python test page\n";
print "Now it will show a calculation";
print "30+2=";
print 30+2;
Then I saved this page in my localhost as index.py
I run the script using
http://localhost/index.py
But it does not show the executed Python script. Instead, it showed the above code as HTML. Where is the problem? How can I run a Python file in a web page?
In order for your code to show, you need several things:
Firstly, there needs to be a server that handles HTTP requests. At the moment you are just opening a file with Firefox on your local hard drive. A server like Apache or something similar is required.
Secondly, presuming that you now have a server that serves the files, you will also need something that interprets the code as Python code for the server. For Python users the go to solution is nowadays mod_wsgi. But for simpler cases you could stick with CGI (more info here), but if you want to produce web pages easily, you should go with a existing Python web framework like Django.
Setting this up can be quite the hassle, so be prepared.
As others have pointed out, there are many web frameworks for Python.
But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:
Rename your script to index.cgi. You also need to execute chmod +x index.cgi to give it execution privileges.
Add these 2 lines in the beginning of the file:
#!/usr/bin/python
print('Content-type: text/html\r\n\r')
After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.
Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python might work instead.
Using the Flask library in Python, you can achieve that.
Remember to store your HTML page to a folder named "templates" inside where you are running your Python script.
So your folder would look like
templates (folder which would contain your HTML file)
your Python script
This is a small example of your Python script. This simply checks for plagiarism.
from flask import Flask
from flask import request
from flask import render_template
import stringComparison
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template("my-form.html") # This should be the name of your HTML file
#app.route('/', methods=['POST'])
def my_form_post():
text1 = request.form['text1']
text2 = request.form['text2']
plagiarismPercent = stringComparison.extremelySimplePlagiarismChecker(text1,text2)
if plagiarismPercent > 50 :
return "<h1>Plagiarism Detected !</h1>"
else :
return "<h1>No Plagiarism Detected !</h1>"
if __name__ == '__main__':
app.run()
This a small template of HTML file that is used:
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Enter the texts to be compared</h1>
<form action="." method="POST">
<input type="text" name="text1">
<input type="text" name="text2">
<input type="submit" name="my-form" value="Check !">
</form>
</body>
</html>
This is a small little way through which you can achieve a simple task of comparing two strings and which can be easily changed to suit your requirements.
If you are using your own computer, install a software called XAMPP (or WAMP either works). This is basically a website server that only runs on your computer. Then, once it is installed, go to the xampp folder and double click the htdocs folder. Now you
need to create an HTML file (I'm going to call it runpython.html). (Remember to move the Python file to htdocs as well.)
Add in this to your HTML body (and inputs as necessary).
<form action = "file_name.py" method = "POST">
<input type = "submit" value = "Run the Program!!!">
</form>
Now, in the Python file, we are basically going to be printing out HTML code.
# We will need a comment here depending on your server. It is basically telling the server where your python.exe is in order to interpret the language. The server is too lazy to do it itself.
import cgitb
import cgi
cgitb.enable() # This will show any errors on your webpage
inputs = cgi.FieldStorage() # REMEMBER: We do not have inputs, simply a button to run the program. In order to get inputs, give each one a name and call it by inputs['insert_name']
print "Content-type: text/html" # We are using HTML, so we need to tell the server
print # Just do it because it is in the tutorial :P
print "<title> MyPythonWebpage </title>"
print "Whatever you would like to print goes here, preferably in between tags to make it look nice"
Well, the OP didn't say server or client side, so I will just leave this here in case someone like me is looking for client side:
Skulpt is a implementation of Python to run at client side. Very interesting, no plugin required, just simple JavaScript code.
With your current requirement, this would work:
def start_html():
return '<html>'
def end_html():
return '</html>'
def print_html(text):
text = str(text)
text = text.replace('\n', '<br>')
return '<p>' + str(text) + '</p>'
if __name__ == '__main__':
webpage_data = start_html()
webpage_data += print_html("Hi Welcome to Python test page\n")
webpage_data += fd.write(print_html("Now it will show a calculation"))
webpage_data += print_html("30+2=")
webpage_data += print_html(30+2)
webpage_data += end_html()
with open('index.html', 'w') as fd: fd.write(webpage_data)
Open the index.html file, and you will see what you want.

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

Webpage redirect to the main page with CGI Python

As my first web app I developed a very simple survey. Random questions are being asked from the user anytime the page refreshes. The answer is sent to a cgi script using post to save the answers to the database.
However, when the user presses the submit button it automatically goes to the page which is responsible for processing the data and since it doesn't have any output it is a blank page. Now if the user wants to answer another question they have to press the "back" in the browser and refresh the page so a new question pops up. I don't want this.
I want it in a way that when the users pressed submit, the answers go automatically to the processing script and the page refreshes itself with a new question or at least after processing it redirects to the main survey page with a new question.
You want to implement this: https://en.wikipedia.org/wiki/Post/Redirect/Get
It's much simpler than it sounds. The CGI script that receives the POST must simply produce the following output:
Status: 303 See other
Location: http://lalala.com/themainpage
You can also send a HTTP header from your processing script:
Location: /
After you have processed your answer, you would send the above header. I would recommend you append a random number query string. e.g. python example (assuming you're using the python CGI module):
#!/usr/bin/env python
import cgitb
import random
import YourFormProcessor
cgitb.enable() # Will catch tracebacks and errors for you. Comment it out if you no-longer need it.
if __name__ == '__main__':
YourFormProcessor.Process_Form() # This is your logic to process the form.
redirectURL = "/?r=%s" % random.randint(0,100000000)
print 'Content-Type: text/html'
print 'Location: %s' % redirectURL
print # HTTP says you have to have a blank line between headers and content
print '<html>'
print ' <head>'
print ' <meta http-equiv="refresh" content="0;url=%s" />' % redirectURL
print ' <title>You are going to be redirected</title>'
print ' </head>'
print ' <body>'
print ' Redirecting... Click here if you are not redirected' % redirectURL
print ' </body>'
print '</html>'
<html>
<head>
<meta http-equiv="refresh" content="0;url=http://www.example.com" />
<title>You are going to be redirected</title>
</head>
<body>
Redirecting...
</body>
</html>
See meta-refresh drawbacks and alternatives here.

Error in creating HTML form using Python-CGI

I have to create a HTML form and get the data using python-cgi. HTML form requires user to submit firstname and lastname and then the python script is supposed to get the data generated in the form. I have read up tutorials and tried playing with it to make it work, but it does not seem to happen.
HTML code:
<form method = "POST" action ="http://localhost/cgi-bin/pyfile_test.py">
<p>First Name: <input type="text" name="firstname">
<p>Last Name: <input type="text" name="lastname">
<p>Click here to submit the form:<input type="submit" value="Submit">
<input type="hidden" name="session" value="1898fd">
</form>
python script to extract data
#!c:/Python26/python.exe -u
import cgi, cgitb
cgitb.enable()
def main()
print "Content-type: text/html\n"
print
form = cgi.FieldStorage()
if form.has_key("firstname") amd form["firstname"].value !="":
print "<h1>Hello", form["firstname"].value, "</h1>"
else:
print "<h1> Error!Wrong!</h1>
main()
when i direct html form to above script it does NOT work but when i direct it to the following script it works.
#!c:/Python26/python.exe -u
import cgi, cgitb
cgitb.enable()
print "Content-type: text/html"
print
print "The First Python Script On Server Side"
print "The sum of two numbers evaluation"
print "3+5 = ",3+5
I dont know what is going wrong. Any help will be highly appreciated!
At least in what you just showed, there are syntax errors:
if form.has_key("firstname") amd form["firstname"].value !="":
print "<h1>Hello", form["firstname"].value, "</h1>"
else:
print "<h1> Error!Wrong!</h1>
amd should be and, and both print statements should be indented deeper than the if and else keywords that control them.
If you fix your syntax and try again, what exactly do you see in the browser (and what do you see if you use your browser's "show source" functionality)?
Edit:
One more syntax error: you're missing a closing " on the second print. It's really tiresome to spot all your syntax errors one by one, and Apache (or whatever your web server is) doesn't seem to be helping -- cgitb can't take control until the whole script is successfully parsed, so syntax errors are the one reason it can't show!
And one more: missing colon at the end of the def main line.
Why don't you just run it with python yourscript.py at the command line until you've made syntax-error-free, and only then try again to run it as a CGI?
E.g. after fixing the two errors I spotted earlier but not the two I've just spotted, you'd be seeing (if python is on the PATH and the shell prompt is $):
$ python acgi.py
File "acgi.py", line 6
def main()
^
SyntaxError: invalid syntax
because of the missing " at the end of the previous line and missing colon at line 6.
Fixing the last two errors (total of four in the code you originally posted) you finally see:
$ python acgi.py
Content-type: text/html
<h1> Error!Wrong!</h1>
of course it says "wrong" because the field storage is empty, but this shows you can NOW (with all four errors fixed) sensibly try to run it as a CGI script at last;-)

Categories

Resources