how to turn a tuple to a string and back in python / how to edit an associative array on a web page
The problem I'm really trying to solve:
I have a square table of true/false values, with rows and columns labelled by strings.
开发者_JS百科I want to display this as an html form with checkboxes, allow the user to tick and untick elements, then submit the form, and then I want to reconstruct the array from the form.
The subproblem I'm trying to solve at the minute:
I have a tuple of two strings, ("foo", "bar")
I want to turn that into the name of a checkbox in a webpage
And then when the form is submitted, turn that string back into the original tuple.
At the moment I'm doing, ("%s$%s" % ("foo", "bar"))-> "foo$bar" and then string.split('$') to get the strings back, which works fine but it's hackish and will break if the strings ever have dollars in them.
Obviously I can't just use repr and eval!
Is there a sane, standard way to do this?
Your second problem is impossible without remembering a state on the server. The client must and shall always be seen as unsafe. There is no sane way of getting the same strings back as you sent. The user can always hack in on some way.
Unless you want to do this cryptographically, which I really doubt :)
However, if you're not worried about script kiddos breaking your app there are thousands of ways, for example what you did, but also saving in a hidden field the length of the first string, which leaves the rest of the string for the second string. Or saving the strings in two different fields, etc.
Why not just nest structures? Given the need for a matrix of values and descriptions, why not nest them like this:
matrix = [
[{'value': False, 'string':'str1'}, {'value': False, 'string':'str2'}],
[{'value': False, 'string':'str1'}, {'value': False, 'string':'str2'}],
]
Now matrix[0][0]
represents a dictionary with keys string
and value
. Without too much of a headache you can convert this to a html table.
Now, you could also (assuming you don't need modification) use nested tuples.
The hard part is reconstruction. You'll need to form the name
tags carefully; I'd suggest from the indices you're using to navigate the matrix like so:
print "<table>"
for i in range(0, 2):
print "<tr>"
for j in range(0, 2):
print "<td>"
item = '<input name="matrix-%d-%d" value=%s>%s<br/>' % (i,j,
str(matrix[i][j]["value"]), matrix[i][j]["string"])
print item
print "</td">
print "</tr>"
print "</table>"
The task then remaining to you is to recreate said list from the post values, which is basically a case of splitting the string, working out if the bounds are sensible (expected?) and populating the dictionary values.
Looks like json is the usual way, and it's a python built-in
import json
json.dumps(("hi","there")) '["hi", "there"]'
json.loads('["hi", "there"]') [u'hi', u'there']
json.loads(json.dumps(("hi","th'ere",'the"e$re'))) [u'hi', u"th'ere", u'the"e$re']
精彩评论