我有一个Django应用程序。在视图中,我调用另一个函数(在stats.py中)然后进行HTTP POST。
views.py
from stats import Stat
a = Stat(example="12345")
a.use(id='query')
stats.py
self.data = { example : "12345" }
req = urllib2.Request(api_url)
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(self.data))
出现的问题是我收到错误
<django.utils.functional.SimpleLazyObject object at 0x2b4d1fe47650> is not JSON serializable
Django Traceback
从查看Django Traceback,我得到以下内容,
/prod/tools/lx/views.py in update_input
a.use(id='query')
...
/prod/tools/main/stats.py in log_use
response = urllib2.urlopen(req, json.dumps(self.data))
...
/usr/local/lib/python2.7/json/__init__.py in dumps
return _default_encoder.encode(obj)
...
/usr/local/lib/python2.7/json/encoder.py in encode
chunks = self.iterencode(o, _one_shot=True)
...
/usr/local/lib/python2.7/json/encoder.py in iterencode
return _iterencode(o, 0)
...
/usr/local/lib/python2.7/json/encoder.py in default
raise TypeError(repr(o) + " is not JSON serializable")
...
有什么想法吗?
谢谢,
答案 0 :(得分:0)
使用urllib
import urllib
...
self.data = { example : "12345", 'Content-type':'application/json' }
self.data = urllib.urlencode(self.data)
req = urllib2.Request(api_url, self.data)
response = urllib2.urlopen(req)