[英]Django deserialization error: string indices must be integers
我是json,Python和Django的新手。 我在網上做了一些研究,但沒有一個能解決我的問題。 預先感謝您的任何見解!
我正在建立一個允許移動設備更新服務器數據庫的系統,該系統由Django管理。 我目前僅在本地計算機上測試,在該計算機上我向Django識別的URL發送請求。
第一步,我有一段python代碼試圖與服務器通信。
# in test.py:
data = '''{"pk": 4, "model": "arts"}'''
data = json.loads(data)
data = json.dumps(data)
URL = "my local host's URL"
h = httplib2.Http(".cache")
resp, content = h.request(URL, "POST", body = data)
然后在服務器上調用view函數。
# in views.py:
def Updates(request, category):
if request.method=='POST':
print 'Data: %s' % request.body
## this prints successfully:
## > Data: {"pk": "4", "model": "arts"}
resultJson = serializers.deserialize('json', request.body)
for obj in resultJson:
print "OK"
return HttpResponse(request.body)
else:
return HttpResponse("Wrong Method")
我得到的錯誤信息是:
Django Version: 1.6.2
Exception Type: DeserializationError
Exception Value: string indices must be integers
...
Traceback Switch to copy-and-paste view
C:\Python27\lib\site-packages\django\core\handlers\base.py in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
C:\Python27\lib\site-packages\django\views\decorators\csrf.py in wrapped_view
return view_func(*args, **kwargs)
C:\pathToViewsFile\views.py in Updates
for obj in resultJson:
C:\Python27\lib\site-packages\django\core\serializers\json.py in Deserializer
six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
C:\Python27\lib\site-packages\django\core\serializers\json.py in Deserializer
for obj in PythonDeserializer(objects, **options):
C:\Python27\lib\site-packages\django\core\serializers\python.py in Deserializer
Model = _get_model(d["model"])
如Django的文檔提供的示例JSON文件示例所示(實際上,這是我檢查的最后一個位置), deserialize
將使用字典列表(順便說一句,該字典應具有fields
鍵):
[
{
"pk": "4b678b301dfd8a4e0dad910de3ae245b",
"model": "sessions.session",
"fields": {
"expire_date": "2013-01-16T08:16:59.844Z",
...
}
}
]
您還可以在deserialize
的doc中看到此函數返回一個迭代器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.