Python scripting - python

I have been following along in Programming Python 4th Edition. One of the tasks is to write a web page that uses cgi to call a python script. It all seems simple enough, but rather than run the script, the browser echos the script instead. I think it may be related to the shebang but I am not sure.
The HTML:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8" />
<title>Interactive Page</title>
</head>
<body>
<form method=POST action="cgi-bin/cgi101.py">
<p><b>Enter your name</b></p>
<p><input type=text name=user /></p>
<p><input type=submit title=Submit /></p>
</form>
</body>
</html>
The script:
#!python
import cgi
form = cgi.FieldStorage()
print('Content-type: text/html\n')
print('<title>Reply Page</title>')
if not 'user' in form:
print('<h1>Who are you?</h1>')
else:
print('<h1>Hello <i>%s</i></h1>' % cgi.escape(form['user'].value))
Instead of a new page showing "Hello Tim" I'm getting a new page with the script dumped into it.

This is an Apache configuration issue that I have not quite worked through. Now when I run it, I get a file not found error from Apache. Progress I guess...

Related

Is there an easy way to let a html button execute a python function

I have a python function that creates a .txt file with an output / results and saves it in my project directory. Now i have a html js files where i take that data from the .txt file and i use it and display the data.
Now my problem is, i want to have a button that executes the python script and creates fresh data depending on a variable.
Is there an easy way to do it.
I am quite new to programming web applications.
you can use frameworks like flask. with flask you just paste your function with a root that will be executed when you go on that root.
just set Form action to your root and then make your method there like it:
<form method="POST" action={{ url_for('your_function') }}>
<div style="text-align: center;">
<H1>Admin panel login </H1> <br>
Username <input type = "text" name= "username" /> <br>
Password <input type = "password" name = "password" /> <br>
<input type = "submit">
</div>
</form>
then in your python file :
def your_function():
...
Browser has no permission to read local file system. So you must serve the .txt file first.
foo.txt
Foo
Bar
Baz
foo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script>
fetch("foo.txt").then(x => x.text()).then(text => document.getElementsByTagName("body")[0].innerText = text)
</script>
</html>
Start HTTP Server in same directory of foo.txt and foo.html
python3 -mhttp.server 8888
Then open http://localhost:8888/foo.html to see the result.

WSGI app can not receive post method from html form

hello I just started to program for the web with python without use of any web framework.
for testing reasons I created a simple html form with the post method to pass a simple text data to the WSGI app that I wrote.
this is the code for the HTML form:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<form action="/tester" method="post">
<input type="text" name="user">
<input type="submit" value="go">
</form>
</body>
</html>
and this is the code for the simple WSGI app:
def test_app(environ, start_response):
var1 = str(environ["REQUEST_METHOD"])
start_response('200 OK', [('Content-Type', 'text/plain')])
return[var1]
but no matter what I do it keeps showing me GET!(as the purpose of the code is tho return the method).
I don't know what I need to do?

How to invoke python s cript on clicking submit on a web form?

my web form looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
<link rel="stylesheet" href="formstyle.css" type="text/css" />
</head>
<body>
<h1>Form Example</h1>
<form action="checkpoint.py" method="POST">
<input type="text" size="6" maxlength="20" name="text2" />
<input type="submit" value="Go!" />
</form>
</body>
</html>
On clicking submit, the browser prompts for opening the checkpoint.py file instead of executing it. The file is present in the same folder. Can you please help me with what I am doing wrong here?
I am completely new to front end and web development.
First of all you need to have server running (in my case it is runned in cgi-bin\ directory). Here you have source code:
from http.server import HTTPServer, CGIHTTPRequestHandler
webdir = '.' # where your html files and cgi-bin script directory live
port = 8080 # default http://localhost or http://127.0.0.1
srvraddr = ("", port)
srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler)
srvrobj.serve_forever()
Then you need a script for requests processing:
#!/usr/bin/python
import cgi
form = cgi.FieldStorage() # parse form data
print('Content-type: text/html\n')
print('<title>Reply Page</title>')
print(form)
if not 'text2' in form:
print('<h1>Who are you?</h1>')
else:
print('<h1>Hello <i>%s</i>!</h1>' % cgi.excape(form['text2'].value))
And, of course, html file, which you already have (remember about correct value in "action" form attribute).
Run server (leave it running), open your form (http://localhost:8080), and send it - then in your cmd window with running server you should see some info about http request -> that's mean your server is running correctly and getting the requests.
EDIT: this code works on Windows + Python3, but should work also on Linux.

How to use cgi form input as variable in call to system command in Python script?

Say I have a web page like this on an Ubuntu 12.04 web server running apache:
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Name Input</title>
</head>
<body>
<form action="./test.py" method="post">
<p> Name: <input type="text" name="name" id="name" value=""/></p>
<input type="submit" value="Submit" />
</form>
</body>
</html>
I want to use the value of name as input to a shell script which is called by a Python CGI script like this.
test.py:
#!/usr/bin/env python
import commands, cgi, cgitb
form = cgi.FieldStorage()
name = form.getvalue('name')
result = commands.getoutput("/usr/lib/cgi-bin/test.sh name")
contents = pageTemplate.format(**locals())
print "Content-type: text/html\n\n"
print contents
In the example code above, how should name be passed to test.sh?
For completeness, say that pageTemplate looks like this:
pageTemplate = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Name Output</title>
</head>
<body>
{result}
</body>
</html>
'''
Just pass it into the command:
result = commands.getoutput("/usr/lib/cgi-bin/test.sh %s" % name)

Python CGI Script Not Executing

Just doing a basic python project with HTML file, i came across a tutorial which gave an idea about how i can execute the code,
here is the HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Admin Login</title>
</head>
<body>
<big><big>Login
Here<br>
<br>
</big></big>
<form action="/var/www/cgi-bin/Login.py" name="LoginForm"><big>Administration
Login<br>
User Name<br>
<input name="UserName"><br>
<br>
<br>
Password<br>
<input name="PassWord"><br>
</big><br>
<br>
<br>
<input type="submit">
<br>
</form>
__ <br>
</body>
</html>
and the python code..
#!/usr/bin/python
import cgi
import cgitb; cgitb.enable()
# get the info from the html form
form = cgi.FieldStorage()
#set up the html stuff
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 == 'Myusername' and Pass == 'MyPasword':
print '<big><big>Welcome'
print 'Hello</big></big><br>'
print '<br>'
else:
print 'Sorry, incorrect user name or password'
print '</body>'
print '</html>'
The problem is, when i submit the username and password, it just shows the whole code back on the browser and not the required Welcome message :(. I use Fedora13 .. can anyone tell me what is going wrong? I even changed the permissions of the file(s).
Most likely, your webserver is not configured to execute the script. Even if it's marked as 'executable' in the file system, that doesn't necessarily mean the webserver knows that it should be executing .py files (rather than just serving them 'straight up'). Have a look here if you're running Apache: http://httpd.apache.org/docs/2.0/howto/cgi.html
<form action="/var/www/cgi-bin/Login.py" name="LoginForm">
Try
<form action="/cgi-bin/Login.py" name="LoginForm">
/var/www is probably the path from your ftp site. The web server will only look inside /var/www, so it puts that part there automatically.

Categories