不,你不需要这样做。而且,是的,你可以这样做!你可以像你那样把它作为一个字符串传递,然后在Python中得到它并评估它。
你可以使用。
evaldict = {}
array = eval("[[1, 2, 3], [4, 5, 6]]", evaldict)
虽然我强制将评估的范围封装在一个dict中,但这并不安全!"。
因为有人可以传递一些其他的 Python 表达式来进行评估。因此最好使用 ast 模块中的 literal_eval() ,它不评估表达式。
我建议你使用jquery和它的post()方法来做这个,使用POST HTTP方法而不是GET。
另外,这可以很好地、安全地使用json完成(发送json,而不是仅仅手动串联JS数组。
并使用它来避免直接评估一个列表(在Python中)。
Here is the client side using jquery:
<html><head><title>TEST</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
pyurl = "http://example.com/cgi-bin/so.py";
function callpy (argdict) {
$.post(pyurl, argdict, function (data) {
// Here comes whatever you'll do with the Python's output.
// For example:
document.getElementById("blah").innerHTML = data;
}, "text");
var myArray = [["one", "two"], ["foo", "bar"]];
// This is array shape dependent:
function stringify (a) {
return "['" + a.join("', '") + "']";
myArrayStr = "[";
for (x = 0; x<myArray.length; x++) {
myArrayStr += stringify(myArray[x]) +", ";
myArrayStr += "]";
// This would be better, but it is library dependent:
//myArrayStr = JSON.stringify(myArray);
</script>
</head><body>
<a href="#" onclick="javascript:callpy({'array': myArrayStr});">Click me!</a>
<p id="blah">
Something will appear here!
</body></html>
而这是服务器端的CGI。
#! /usr/bin/env python
# This version of eval() ensures only datatypes are evaluated
# and no expressions. Safe version of eval() although slower. It is available in Python 2.6 and later
from ast import literal_eval as eval
except ImportError:
import sys
print "Content-Type: text/html\n"
print "<h1>literal_eval() not available!</h1>"
sys.exit()
import cgi, cgitb
import sys
cgitb.enable()
print "Content-Type: text/html\n"
i = cgi.FieldStorage()
q = i["array"].value.strip()
print "I received:<br>"
print q
# Put here something to eliminate eventual malicious code from q
# Check whether we received a list:
if not q.startswith("[") and not q.endswith("]"):
print "Wrong query!"
sys.exit()
try: myArray = eval(q)
except: print "Wrong query!"; sys.exit()
if not isinstance(myArray, list):
print "Wrong query!"
sys.exit()