What is the best way to pass List via form in python (cgi).
ListStr = ['State1', 'State2', 'State3']
TrVListStr = '##'.join(ListStr)
print """
<form method="post">
<input type=hidden name="state_carry" value="""+TrVListStr+"""><br />
<input type="submit" value="Submit" />
</form>
"""
After submission I should have list as it was before submission.
I can do split (based on ## rule) form['state_carry].value again to fetch that. but I think it is not good way.
Is there any way to pass Python List via form and retrieve them later.
Thanks.
You could use the python cgi module. The documentation specifically covers the case where you have multiple values for a certain field name.
The basic idea is that you can have multiple fields in your html form with the same name, and the value for each field is one of the values from the list. You can then use the getlist() method to retrieve all the values as a list. For example:
print "<form method=\"post\">"
for s in ListStr:
print "<input type=hidden name=\"state_carry\" value=\"" + s + "\"><br />"
print "<input type=\"submit\" value=\"Submit\" />"
print "</form>"
Then in your CGI script you'll have something like:
MyList = form.getlist("state_carry")
In python I would do.
###In the form page.
import cgi
#Convert list of values to string before passing them to action page.
ListStr=','.join(['State1', 'State2', 'State3'])
print "<input type=hidden name=\"state_carry\" value=\""+ListStr+"\"><br />"
###In the action page
import cgi
#Return the string passed in the user interaction page and transform it back to a list.
ListStr=cgi.FieldStorage().getvalue('state_carry').split(',')
Related
I have a form-input like:
<PRE>
<FORM>
<INPUT name="field_RecordingDateID-StartDate" id="field_RecordingDateID-StartDate" placeholder="mm/dd/yyyy" type="date" value="">
<INPUT name="field_RecordingDateID-EndDate" id="field_RecordingDateID-EndDate" placeholder="mm/dd/yyyy" type="date" value="">
<input type="submit" value="search">
</FORM>
</PRE>
I am try to create dictionary as
payload = dict(field_RecordingDateID-StartDate = "10-08-2016",
field_RecordingDateID-EndDate ="12-08-2016")
And I need to send post request so that I can get the result through Python requests.
I am using
r = requests.get(url,data=payload)
Currently I am getting error as 'Can't assigned the value to operator' in console.
The error is at creating dictionary.
Can you help me?
It is a small problem in your code. Actually the correct way to define a dictionary is will be like this.
payload = {"field_RecordingDateID-StartDate" :"10-08-2016",
"field_RecordingDateID-EndDate" :"12-08-2016"}
You should use a valid identifier. Try to create payload dict as:
StartDate = 'field_RecordingDateID-StartDate'
EndDate = 'field_RecordingDateID-EndDate'
payload = dict(StartDate = '10-08-2016', EndDate = '12-08-2016')
and post your data as:
r = requests.post(url,data=payload)
If I send a form like this:
<form method="POST" ...>
<input type="text" name="filters[price_from]">
<input type="text" name="filters[price_to]">
</form>
to PHP script it automatically creates an array and I can access variables like this:
$_POST['filters']['price_to']
and:
$_POST['filters']
is iterable
AND this is my question, how can I get same effect in FLASK?
request.form.getlist('filters')
return [] (empty list)
request.form.get('filters[price_from]')
return right value but this is not the result of which they expect (its not iterable).
Should i rebuild my form or use some other method?
You cannot access a python array/list using a key, if you want to access your data using a key, store your filters as a json object, then you will be able to access the data by using a key.
<form method="POST" enctype="application/JSON">
<input type="text" name="filters[price_from]" value="" >
<input type="text" name="filters[price_to]" value="" >
</form>
filters = request.get_json()
filters['price_from'] #returns price_from value
filters['price_to'] #returns price_to value
In php an array is several things.
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.
While in python an array is only a list accessed by index.
>>> filters = ['price_from', 'price_to']
>>> filters[0]
'price_from'
>>> filters[1]
'price_to'
And a dict is accessed by key.
>>> filters = {'price_from':'value', 'price_to':'another_value'}
>>> filters['price_from']
'value'
>>> filters['price_to']
'another_value'
I have a small .py program, rendering 2 HTML pages. One of those HTML pages has a form in it. A basic form requesting a name, and a comment. I can not figure out how to take the name and the comment from the form and store it into the csv file. I have got the coding so that the very little I already manually input into the csv file is printed/returned on the HTML page, which is one of the goals. But I can't get the data I input into the form into the csv file, then back n the HTML page. I feel like this is a simple fix, but the Flask book makes absolutely no sense to me, I'm dyslexic and I find it impossible to make sense of the examples and the written explanations.
This is the code I have for reading the csv back onto the page;
#app.route('/guestbook')
def guestbook():
with open('nameList.csv','r') as inFile:
reader=csv.reader(inFile)
names=[row for row in reader]
return render_template('guestbook.html',names=names[1:])
And this is my form coding;
<h3 class="tab">Feel free to enter your comments below</h3>
<br />
<br />
<form action="" method="get" enctype="text/plain" name="Comments Form">
<input id="namebox" type="text" maxlength="45" size="32" placeholder="Name"
class="tab"/>
<br />
<textarea id="txt1" class="textbox tab" rows="6" placeholder="Your comment"
class="tab" cols="28"></textarea>
<br />
<button class="menuitem tab" onclick="clearComment()" class="tab">Clear
comment</button>
<button class="menuitem" onclick="saveComment()" class="tab">Save comment</button>
<br>
</div>
By what I understand all you need is to save the data into the file and you don't know how to handle this in Flask, I'll try to explain it with code as clear as possible:
# request is a part of Flask's HTTP requests
from flask import request
import csv
# methods is an array that's used in Flask which requests' methods are
# allowed to be performed in this route.
#app.route('/save-comment', methods=['POST'])
def save_comment():
# This is to make sure the HTTP method is POST and not any other
if request.method == 'POST':
# request.form is a dictionary that contains the form sent through
# the HTTP request. This work by getting the name="xxx" attribute of
# the html form field. So, if you want to get the name, your input
# should be something like this: <input type="text" name="name" />.
name = request.form['name']
comment = request.form['comment']
# This array is the fields your csv file has and in the following code
# you'll see how it will be used. Change it to your actual csv's fields.
fieldnames = ['name', 'comment']
# We repeat the same step as the reading, but with "w" to indicate
# the file is going to be written.
with open('nameList.csv','w') as inFile:
# DictWriter will help you write the file easily by treating the
# csv as a python's class and will allow you to work with
# dictionaries instead of having to add the csv manually.
writer = csv.DictWriter(inFile, fieldnames=fieldnames)
# writerow() will write a row in your csv file
writer.writerow({'name': name, 'comment': comment})
# And you return a text or a template, but if you don't return anything
# this code will never work.
return 'Thanks for your input!'
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.
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.