How do I accept post requests with a python script using cgi? - python

I want to submit text to an HTML form and send it to a Python script. When I press the submit button it takes me to an error page that says:
Error code: 501 Message: Unsupported method ('POST'). Error code explanation: HTTPStatus.NOT_IMPLEMENTED - Server does not support this operation.
I'm not exactly sure what the issue is. I've googled the error message and have looked through different documentation and watched some videos but they are seem to gloss over how to set up the server correctly.
I'm running Python 3.7.
<form action="www/cgi-bin/hello.py" method="post">
First Name:
<input type="text" name="first_name" placeholder="e.g. Barack" required="required"/>
Last Name:
<input type="text" name="last_name" placeholder="e.g. Obama" required="required"/>
<input type="submit" name="submitprompt" value="Submit"/>
</form>
#!/usr/bin/python
import cgi, cgitb
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
print("Content-type:text/html")
print("")
print("")
print("Hello - Second CGI Program")
print("")
print("")
print(" Hello %s %s" % (first_name, last_name))
print("")
print("")
I'm expecting to be taken a page that has the text: Hello first_name last_name. Instead, I receive the aforementioned error.

Using the command "python3 -m http.server --cgi 8000" and configuring from there solved my issue.

Related

Trying to click in the message box using selenium webdriver

Trying to click on the message box for every new message window that pops up. However it seems as if the id changes every time. How do I get this to work for everytime a new message box pops up.
Here is what I tried:
passMessage = browser.find_element_by_css_selector('ember-text-area msg-messaging-form__message ember-view')
For example:
<textarea name="message" spellcheck="true" required="" placeholder="Write a message or attach a file" id="a11y-ember8470" class="ember-text-area msg-messaging-form__message ember-view"></textarea>
<textarea name="message" spellcheck="true" required="" placeholder="Write a message or attach a file" id="a11y-ember8492" class="ember-text-area msg-messaging-form__message ember-view"></textarea>
It is a css class name, so you need a dot:
passMessage = browser.find_element_by_css_selector('.ember-text-area.msg-messaging-form__message.ember-view');
http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains

How to execute external commands with Python using Apache2 and CGI

I have an Apache web server. I have an html file and a Python script located at var/www/myfolder. I am submitting a form through the html file which is handled by my Python script (when the submit button is clicked). But once handling the form, my Python script executes an external command. (see the following code)
webpage.html
<!DOCTYPE html>
<html>
<head>
<title>Webform</title>
</head>
<body>
<h3>Webform</h3>
<form action="myscript.py" method="POST">
<p>Name: <input type="text" name="name"></p>
<input type="submit" value="Submit">
</form>
</body>
</html>
myscript.py
#!/usr/bin/python -W
import cgi, cgitb
import sys
import os
# Get data from fields
form = cgi.FieldStorage()
name = form.getvalue('name')
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></br></br>'
print '<p>Name: %s</p>' % (name)
print '</body>'
print '</html>'
os.system("./other_script.py") # gives me an error with permission
On my server I am user007 but I know that when I click submit on the html file, the Python script is executed as apache2 user. The problem is I don't know the password for this user (can't us sudo). Are the two ideas possible:
1) change from apache2 to user007 when trying to execute other_script.py from myscript.py
2) I know that you can change users using suEXEC but I have no idea how to use it.
Any suggestions?
I should let you know that locally both the python scripts are executing fine.
Edit 1:
I get this message before the error occurs: WARNING: HOME is not set, using root: /

KeyError in Python

This is my code:
print """\
<form method="post">
Please enter Viewer Type:<br />
<table>
"""
#Viewer Type
print "<tr><td>Viewer Type<select name=""ViewerType"">"
print """\
<option value="C">Crowd Funding
<option value="P">Premium
"""
#do it button
print """\
<input type="submit" value="OK" />
"""
print """\
</form>
</body>
<html>
"""
ViewerType=form['ViewerType'].value
And, when I serve it to a browser, this is the error:
Traceback (most recent call last): File "/home/nandres/dbsys/mywork/James/mywork/ViewerForm.py", >line 42, in ViewerType=form['ViewerType'].value File "/usr/lib/python2.7/cgi.py", line 541, in >getitem raise KeyError, key KeyError: 'ViewerType'
And line 42 is the last line of my code.
The error isn't actually affecting functionality, and everything works fine, but I don't really want it popping up. Any advice/insight would be appreciated.
Btw, I have this at the top of my code:
import cgi
form = cgi.FieldStorage()
When your script is first called to render the page, the form dict is empty. The dict will only get filled when the user actually submits the form. So changing your HTML to
<option value="C" selected>Crowd Funding
won't help.
So you need to test the dict before you attempt to access it. Eg,
#! /usr/bin/env python
import cgi
form = cgi.FieldStorage()
print 'Content-type: text/html\n\n'
print "<html><body>"
print """\
<form method="post">
Please enter Viewer Type:<br />
<table>
"""
#Viewer Type
print "<tr><td>Viewer Type<select name=""ViewerType"">"
print """\
<option value="C">Crowd Funding
<option value="P">Premium
"""
#do it button
print """\
<input type="submit" value="OK" />
"""
print "</table></form>"
if len(form) > 0:
ViewerType = form['ViewerType'].value
print '<p>Viewer Type=' + ViewerType + '</p>'
else:
print '<p>No Viewer Type selected yet</p>'
print "</body></html>"
Simple solution if you don't want it popping:
try:
ViewerType=form['ViewerType'].value
except KeyError:
pass
It'll work but I would recommend you to debug your code and find out why you are getting KeyError. From https://wiki.python.org/moin/KeyError,
Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary.

form["x"] throws a KeyError

I'm working on an assignment and we are to create a HTML order form then execute the info by python to create a second customer receipt.
Here is the error msg:
Traceback (most recent call last):
File "F:\Assignment 3\page.py", line 17, in <module>
print "<p>Customer Name:", form["custName"].value, "</p>"
File "C:\Python27\lib\cgi.py", line 540, in __getitem__
raise KeyError, key
KeyError: 'custName'
THE HTML:
<form action="page.py">
<div class="personalinfohead">
<p>Personal Information:</p>
</div>
<div class="personalinfo">
<div>Full name:
<input type="text" name="custName" size="20" />
</div>
<div>Email address:
<input type="text" name="custEmail" size="50" />
</div>
<div>Street address:
<input type="text" name="custAdd" size="50" />
</div>
<div>City:
<input type="text" name="custCity" size="15" />
</div>
<div>Province:
<input type="text" name="custProv" size="2" maxlength="2" />
</div>
<div>Postal code:
<input type="text" name="custPostal" size="6" maxlength="6" />
</div>
</div>
PYTHON:
import cgi
form = cgi.FieldStorage()
# print HTTP/HTML header stuff
print """Content-type: text/html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html><head>
<title>Order Form</title>
</head><body>
"""
# print HTML body using form data
print "<h1>Kintoro Japanese Bar & Restaurant</h1>"
print "<h2>Customer Reciept</h2>"
print "<p>Customer Name:", form["custName"].value, "</p>"
print "<p>Customer Email Address:", form["custEmail"].value, "</p>"
print "<h2>Customer Address:</h2>"
print "<p>Street:", form["custAdd"].value, "</p>"
print "<p>City:", form["custCity"].value, "</p>"
print "<p>Province:", form["custProv"].value, "</p>"
print "<p>Postal Code:", form["custPostal"].value, "</p>"
Jack is correct, but there is a backstory and quick/dirty testing method for the future students.
Explanation first:
Originally, your KeyError said there was no Key with that name. After you've implicitly stated a key (the first part of a dict), it was then missing the Value for said key.
Dictionaries are a key-value pair, so both would need to be implicitly stated at the start of the script (in the scope the previous and following debugging-with-ease methods).
Slowing down the actions helps obtain clearer understanding;
Since this script is a fully loaded CGI that is told to start and finish by declaring variables for each key-value pair, you are seeing the end result of which - where python feeds text data to CGI, CGI then accepts and interprets said text, and gives some sort of response back to python (valid or not!), python can only give you the results of the results. Thusly, this error looks different than your standard (and excellent I may add) non-cgi / console error with followable tracebacks.
A quick/dirty test method:
Implicitly state an exact key-value pair before telling CGI to pass it back to python to use:
custName = { 'Name': 'John Smith' }
One would need to declare a default setting for each dict mentioned as values to have a fully operational loaded script ready to use, but the hint here is that custName would no longer present the error, but it would then complain about your next missing key-value pair.
Yeah, long answer and past classtime - I know. Hopefully, however, this will assist to understand the several parts of a 'single' issue than to solve it once for only a select few people.

Display python script output to HTML page

I have this hello_world.py script which takes username and password and prints user information. Separately the python executes without any error. But, when I submit from HTML the html page gives internal server 500 error. I have added executable permission to script in file system, in httpd.conf. But, I am not sure why this is not executing when I provide submit.
Thanks for suggestions and help.
<form action="/cgi-bin/hello_world.py" method="post">
IP Address: <input type="text" name="user_name"><br />
Password: <input type="text" name="pass_word" />
<input type="submit" value="Submit" />
</form>
My python script is
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
import getpass
import sys
import telnetlib
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
user_name = form.getvalue('user_name')
//username will get IP of machine
pass_word = form.getvalue('pass_word')
loginid = 'admin'
tc = telnetlib.Telnet(user_name)
tc.read_until("login: ")
tc.write(loginid + "\n")
tc.read_until("Password: ")
tc.write(pass_word + "\r\n")
tc.write("ls -l\n")
tc.write("exit\n")
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello </title>"
print "</head>"
print "<body>"
print "<h2> %s is IP and %s is passowrd</h2>" % (user_name, pass_word)
print tc.read_all()
print "</body>"
print "</html>"

Categories

Resources