使用 urllib 发布 pickle 转储字符串
我需要将数据发布到 Django 服务器。我想用泡菜。 (没有安全要求 -> 小型 Intranet 应用程序。)
首先,我在客户端上 pickle 数据并使用 urllib2 发送它
def dispatch(self, func_name, *args, **kwargs):
dispatch_url = urljoin(self.base_url, "api/dispatch")
pickled_args = cPickle.dumps(args, 2)
pickled_kwargs = cPickle.dumps(kwargs, 2)
data = urllib.urlencode({'func_name' : func_name,
'args' : pickled_args,
'kwargs': pickled_kwargs})
resp = self.opener.open(dispatch_url, data)
在服务器上接收数据也可以:
def dispatch(request):
func_name = request.POST["func_name"]
pickled_args = request.POST["args"]
pickled_kwargs = request.POST["kwargs"]
但是 unpickling 会引发错误:
cPickle.loads(pickled_args)
Traceback (most recent call last):
File "<string>", line 1, in <fragment>
TypeError: must be string, not unicode
显然 urllib.urlencode
创建了一个 unicode 字符串。但是我怎样才能将它转换回能够再次解酸(老兄)呢?
顺便说一下,使用 pickle 格式 0 (ascii) 是可行的。我可以在 unpickle 之前转换为字符串,但我宁愿使用格式 2。
此外,非常感谢有关如何将二进制数据获取到 Django 视图的建议。
I need to post data to a Django server. I'd like to use pickle. (There're no security requirements -> small intranet app.)
First, I pickle the data on the client and sending it with urllib2
def dispatch(self, func_name, *args, **kwargs):
dispatch_url = urljoin(self.base_url, "api/dispatch")
pickled_args = cPickle.dumps(args, 2)
pickled_kwargs = cPickle.dumps(kwargs, 2)
data = urllib.urlencode({'func_name' : func_name,
'args' : pickled_args,
'kwargs': pickled_kwargs})
resp = self.opener.open(dispatch_url, data)
Recieving the data at the server works, too:
def dispatch(request):
func_name = request.POST["func_name"]
pickled_args = request.POST["args"]
pickled_kwargs = request.POST["kwargs"]
But unpickling raises an error:
cPickle.loads(pickled_args)
Traceback (most recent call last):
File "<string>", line 1, in <fragment>
TypeError: must be string, not unicode
Obviously the urllib.urlencode
has created a unicode string. But how can I convert it back to be able to unpickling (laods) again?
By the way, using pickle format 0 (ascii) works. I can convert to string before unpickling, but I'd rather use format 2.
Also, recommendations about how to get binary data to a Django view are highly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
urllib.urlencode
不返回 Unicode 字符串。request.POST
包含 Unicode 字符串可能是您使用的 Web 框架的一个功能。不要使用
pickle
在服务之间进行通信,它不安全、脆弱、不可移植、难以调试,并且会使您的组件过于耦合。urllib.urlencode
doesn't return Unicode string.It might be a feature of the web framework you use that
request.POST
contains Unicode strings.Don't use
pickle
to communicate between services it is not secure, brittle, not portable, hard to debug and it makes your components too coupled.