存储字符串值时异常的 Django 管理行为
使用 django trunk r13359 和 djangopiston,我创建了一个存储字符串值的小型 Restful 服务。
这是我用来存储字符串的模型:
class DataStore(models.Model):
data = models.CharField(max_length=200)
url = models.URLField(default = '', verify_exists=False, blank = True)
我使用curl来发布以下数据:
curl -d "data=somedata" http://localhost:8000/api/datastorage/
这是作为django-piston处理程序的一部分处理存储的代码
store = DataStore()
store.url = request.POST.get('url',""),
store.data = request.POST['data'],
store.save()
return {'data':store}
当我使用curl发布数据时,我得到以下响应正文,即预期:
{
"result": {
"url": [
""
],
"data": [
"somedata"
],
"id": 1
}
}
然而,当我从 django admin 查看存储的实例时,数据字段中存储的值看起来像这样:
(u'somedata',)
并且以下内容存储在 url 中:
('',)
更有趣的是当我使用以下命令查询服务时卷曲来查看存储的内容,我得到以下信息:
{
"result": {
"url": [
"('',)"
],
"data": [
"(u'somedata',)"
],
"id": 1
}
}
我很困惑..有什么想法可能会发生什么吗?
Using django trunk r13359 and django piston, I created a small restful service that stores string values.
This is the model I am using to store strings:
class DataStore(models.Model):
data = models.CharField(max_length=200)
url = models.URLField(default = '', verify_exists=False, blank = True)
I used curl to post following data:
curl -d "data=somedata" http://localhost:8000/api/datastorage/
This is the code that handles storage as part of the django-piston handler
store = DataStore()
store.url = request.POST.get('url',""),
store.data = request.POST['data'],
store.save()
return {'data':store}
When I post the data with curl I get the following response body, which is expected:
{
"result": {
"url": [
""
],
"data": [
"somedata"
],
"id": 1
}
}
Whats not expected however is when I look at the stored instance from django admin, the value stored in the data field looks something like this:
(u'somedata',)
and the following is stored in the url:
('',)
Whats even more interesting is when I query the service with curl to see what is stored, I get the following:
{
"result": {
"url": [
"('',)"
],
"data": [
"(u'somedata',)"
],
"id": 1
}
}
I'm stumped .. any ideas what could be going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上你的响应也不应该是预期的,注意你的字符串周围的 [] ,那些不应该在那里。
您的错误是在这两行后面添加逗号:
Python 将解释您想要在 url 和 data 中存储元组,并且 django 会将这些元组隐式转换为字符串,从而导致您看到的行为。只要删除两个逗号就可以了。
Actually your response is also not what should be expected, note the [] around your strings, those shouldn't be there.
Your error is adding the comma after these two lines:
Python will interprete you want to store a tuple in url and data, and django will convert those tuples to strings implicitly, resulting in the behaviour you see. Just remove the two commas and you'll be fine.