我正在使用python调试此PHP代码(该代码位于许多其他代码中,这会使问题变得混乱)
$sql = rtrim("INSERT INTO someTable (foo, bar, id) VALUES " . str_repeat("(?, ?, $id)," , count($contents)), ',');
$stmt = $dbh->prepare($sql);
foreach ($contents as $i => $line) {
$stmt->bindParam(2*$i+1, $line['foo'], PDO::PARAM_STR);
$stmt->bindParam(2*$i+2, $line['bar'], PDO::PARAM_STR);
echo $line['dutch'] . '->' . $line['english'] . '\n';
if (!$stmt->execute()) {
$dbh->rollBack();
return false;
}
}
$dbh->commit();
return true;
为此调试,我编写了这段代码
import requests
s = requests.Session()
content = [
{'foo': 'f', 'bar': 'b'},
{'foo': 'o', 'bar': 'a'},
{'foo': 'o', 'bar': 'r'}
]
s.post("http://localhost:8000", data={'content': content})
无法将数据添加到我的数据库中
所以,我尝试了一些调试
print_r($_POST)
返回了
Array
(
[someOtherVariables] => otherValues
[content] => foo
)
我曾希望内容包含一个对象数组,但是它某种程度上仅包含第一个索引的名称。 有谁知道为什么这个python代码没有发送完整列表,以及如何修改我的代码以使其起作用?
我还尝试使用json而不是数据变量s.post("http://localhost:8000", json={'content': content})
发送数据,但这似乎无法解决我的问题。
答案 0 :(得分:1)
我认为可能是您需要先将python dict转换为json字符串,然后再通过请求将其发送。
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
您的情况:
contentAsjsonString = json.dumps(content)
s.post("http://localhost:8000", data={'content': contentAsjsonString })