全面披露:跨發佈到谷歌Tastypie集團轉換POST與Tastypie PUT
我有一個情況我有限的過被髮送到我的API是什麼控制。基本上有兩個Web服務,我需要能夠接受POST數據。兩者都使用帶有urlencoded數據的簡單POST操作(基本上是基本表單提交)。
關於它的「捲曲」的角度思考它像:
curl --data "id=1&foo=2" http://path/to/api
我的問題是,我不能用POST更新記錄。所以我需要調整模型資源(我相信),使得如果指定的ID,在POST充當PUT而不是POST。
api.pyclass urlencodeSerializer(Serializer):
formats = ['json', 'jsonp', 'xml', 'yaml', 'html', 'plist', 'urlencoded']
content_types = {
'json': 'application/json',
'jsonp': 'text/javascript',
'xml': 'application/xml',
'yaml': 'text/yaml',
'html': 'text/html',
'plist': 'application/x-plist',
'urlencoded': 'application/x-www-form-urlencoded',
}
# cheating
def to_urlencoded(self,content):
pass
# this comes from an old patch on github, it was never implemented
def from_urlencoded(self, data,options=None):
""" handles basic formencoded url posts """
qs = dict((k, v if len(v)>1 else v[0])
for k, v in urlparse.parse_qs(data).iteritems())
return qs
class FooResource(ModelResource):
class Meta:
queryset = Foo.objects.all() # "id" = models.AutoField(primary_key=True)
resource_name = 'foo'
authorization = Authorization() # only temporary, I know.
serializer = urlencodeSerializer()
urls.py
foo_resource = FooResource
...
url(r'^api/',include(foo_resource.urls)),
)
在Freenode上#tastypie,鬼[],建議我覆蓋由在像模型資源創建函數post_list()所以,但是,我還沒有成功地使用它。
def post_list(self, request, **kwargs):
if request.POST.get('id'):
return self.put_detail(request,**kwargs)
else:
return super(YourResource, self).post_list(request,**kwargs)
不幸的是,這種方法不適合我。我希望更大的社區能夠爲這個問題提供一些指導或解決方案。
注:我不能覆蓋該來自客戶端(按:http://django-tastypie.readthedocs.org/en/latest/resources.html#using-put-delete-patch-in-unsupported-places)頭
我使用的方法obj_create這樣的鏈接 http://stackoverflow.com/questions/10070173/tastypie-obj-create-how-to-use-newly-created-object 和工精細 – 2014-04-22 15:14:02