Handle HTML Form Data with Python? - python

I'm trying to use Python and HTML together. What I'm trying to do is create an HTML Form that will submit data to a python file and that python file will then handle the data. But I'm not getting it to work.
Here is my python code:
form = cgi.FieldStorage() # instantiate only once!
name = form['Sample Name'].value
and this is my HTML code:
<form method='POST' action='/functionGen.py'>
Name: <input type='text' name='Sample Name'>
<input type='submit' value='Begin Storing'>
</form>
What ends up happening is I just see my python code in the browser, the file doesn't begin handling the data.
What can I do?

You should know, that you are getting plain python source document via http protocol now. If you want to use CGI mechanism, you should place youre .py in cgi-enabled directory. It means that you need http server.
related questions
How to run Python CGI script
How do I set up a Python CGI server?

Related

Trouble uploading json file with flask

For some reason, this won't accept json files.
#app.route('/get_data', methods=['POST'])
def get_data():
dataFile = request.files['file_path']
dataFileName = dataFile.filename
dataFile.save(os.path.join(uploads_dir, dataFileName))
I keep getting this error:
You seem to have json set as an file ending in your template by <input type="file" accept="json">. (The template is not supplied so I can't pinpoint the line. This is not an error of the backend (flask) but of the your template code (jinja/html). It would be nice if you could supply a MRE for such issues.
For more information about <input type="file"> take a look at the MDN Documentation.
Example of correct accept:
<input type="file" accept=".json">
This will only allow *.json file but keep in mind that users may supply other files manually and create a fallback or validation when parsing/ saving the file.

Textarea event handling with Python3

I wonder if someone can help me. I'm trying to do something like the following to get input events from a HTML text box and send them to a python function.
textarea = cgi.FieldStorage()
chars = textarea.getvalue('1')
def MyPythonFunction():
'Do something with chars'
print(<textarea oninput=MyPythonFunction() </textarea>)
I've tried all kinds of things but can't get it to work.
Thanks in advance
First, the oninput keyword of the textarea HTML tag expects JavaScript code and would interpret mypythonfunction to be a JavaScript function. You need to output an HTML form that contains a SUBMIT tag such that when the form is submitted it invokes your server-side script: the form might look like:
<form name="f" action="my_script.py" method="post">
<textarea name="chars"></textarea>
<br>
<input type="submit" name="submit" value="Submit">
</form>
Your server side script, my_script.py, which must be executable, might look like:
#!/usr/bin/env python
import cgi
import cgitb
cgitb.enable()
form = cgi.FieldStorage()
chars = form.getvalue('chars')
If you really wanted to process input a character at a time, then you would remove the SUBMIT HTML tag, put back the oninput keyword. But then you would have to specify a JavaScript function that would get invoked whenever the contents of the textarea changed. This function would have to use a technique called AJAX to invoke your server-side Python script passing the contents of the TEXTAREA as an argument. This is a rather advanced topic, but you can investigate this.

Display Python output in HTML

What is the simplest way to display the Python ystockquote (http://goldb.org/ystockquote.html) module output in HTML? I am creating an HTML dashboard which will be run locally on my computer and want to insert the stock output results into the designated HTML placeholders. I am hoping that because it is local I can avoid many CGI and server requirements.
I would use a templating system (see the Python wiki article). jinja is a good choice if you don't have any particular preferences. This would allow you to write HTML augmented with expansion of variables, control flow, etc. which greatly simplifies producing HTML automatically.
You can simply write the rendered HTML to a file and open it in a browser, which should prevent you from needing a webserver (though running python -m SimpleHTTPServer in the directory containing the HTML docs will make them available under http://localhost:8000)
Here is a simple server built using web.py (I have been playing with this for a while now, so this was a fun question to answer)
import web
import ystockquote
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def POST(self):
history = ystockquote.get_historical_prices(web.input()['stock'], web.input()['start'], web.input()['end'])
head = history[0]
html = '<html><head><link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"><body><table class="table table-striped table-bordered table-hover"><thead><tr><th>{}<th>{}<th>{}<th>{}<th>{}<th>{}<th>{}<tbody>'.format(*head)
for row in history[1:]:
html += "<tr><td>{}<td>{}<td>{}<td>{}<td>{}<td>{}<td>{}".format(*row)
return html
def GET(self):
return """<html>
<head><link href='//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css' rel='stylesheet'>
<body>
<form method='POST' action='/'><fieldset>
Symbol <input type='input' name='stock' value='GOOG'/><br/>
From <input type='input' name='start' value='20130101'/><br/>
To <input type='input' name='end' value='20130506'/><br/>
<input type='submit' class='btn'/></fieldset></form>"""
if __name__ == "__main__":
app.run()

how do i print outputs to html page using python?

I want user to enter a sentence then I break up that sentence into a list. I got the html page down but i have trouble passing that sentence to python.
How do I properly send the user input to be processed by python and output it to a new page?
There are many Python web frameworks. For example, to break up a sentence using bottle:
break-sentence.py:
#!/usr/bin/env python
from bottle import request, route, run, view
#route('/', method=['GET', 'POST'])
#view('form_template')
def index():
return dict(parts=request.forms.sentence.split(), # split on whitespace
show_form=request.method=='GET') # show form for get requests
run(host='localhost', port=8080)
And the template file form_template.tpl that is used both to show the form and the sentence parts after processing in Python (see index() function above):
<!DOCTYPE html>
<title>Break up sentence</title>
%if show_form:
<form action="/" method="post">
<label for="sentence">Input a sentence to break up</label>
<input type="text" name="sentence" />
</form>
%else:
Sentence parts:<ol>
%for part in parts:
<li> {{ part }}
%end
</ol>
%end
request.forms.sentence is used in Python to access user input from <input name="sentence"/> field.
To try it you could just download bottle.py and run:
$ python break-sentence.py
Bottle server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.
Now you can visit http://localhost:8080/.
Have you tried Google? This page sums up the possibilities, and is one of the first results when googling 'python html'.
As far as I know, the two easiest options for your problem are the following.
1) CGI scripting. You write a python script and configure it as a CGI-script (in case of most HTTP-servers by putting it in the cgi-bin/ folder). Next, you point to this file as the action-attribute of the form-tag in your HTML-file. The python-script will have access to all post-variables (and more), thus being able to process the input and write it as a HTML-file. Have a look at this page for a more extensive description. Googling for tutorials will give you easier step-by-step guides, such as this one.
2) Use Django. This is rather suited for larger projects, but giving it a try on this level may provide you certain insights, and wetting your appetite for future work ;)

Problem with python cgi in Firefox

I have written an html form and am trying to incorporate a python cgi script with it. I have already configured my apache server to execute cgi scripts from the cgi-bin directory. Here's the html form:
<html>
<body>
<form name="input" action="c:/xampp/cgi-bin/test2.py" method="post">
<input type="text" name="qry" />
<input type="submit" value="GO!" />
</form>
</body>
</html>
And here's the test2.py cgi script:
#!c:/Python27/python.exe -u
import cgi
import cgitb
cgitb.enable()
form = cgi.FieldStorage()
qry = form["qry"].value
print "Content-Type: text/html"
print
print "<html"
print "<body>"
print qry
print "</body>"
print "</html>"
The html page is located in my htdocs folder and the cgi script is in the cgi-bin directory. However, when I enter something into the form and submit, firefox returns an error message saying: "Firefox doesn't know how to open this address, because the protocol (c) isn't associated with any program". Why is this error occurring? Does it have something to do with my path to the cgi script in my html page? Thanks in advance!
You are correct: it has something to do with the path to the CGI script on the HTML page. The form's action attribute should refer to the path where the CGI script is getting interpreted on the server, e.g., /cgi-bin/test2.py.
Since you made this mistake, I'm assuming you are new to web development. Consider using mod_wsgi and a framework like Django instead of CGI, especially if you expect a lot of traffic or you are making a web application and not just handling a single form.

Categories

Resources