从tastypie uri获取模型对象? [英] Get model object from tastypie uri?
问题描述
例如:
如果您在python中将uri作为字符串,您如何获取该字符串的模型对象?
您可以使用 get_via_uri
,但是@Zakum提到,这将适用您可能不想要的授权。所以挖掘这个方法的源码,我们看到我们可以像这样解析URI:
from django.core.urlresolvers import解析,get_script_prefix
def get_pk_from_uri(uri):
prefix = get_script_prefix()
chomped_uri = uri
如果前缀和chomped_uri.startswith(前缀) :
chomped_uri = chomped_uri [len(prefix)-1:]
try:
view,args,kwargs = resolve(chomped_uri)
除了Resolver404:
raise NotFound(提供的URL'%s'不是有效资源的链接。%uri)
return kwargs ['pk']
如果您的Django应用程序位于Web服务器的根目录(即 get_script_prefix()=='/'
),那么你可以简化为:
view,args,kwargs = resolve(uri)
pk = kwargs ['pk']
How do you get the model object of a tastypie modelresource from it's uri?
for example:
if you were given the uri as a string in python, how do you get the model object of that string?
You can use get_via_uri
, but as @Zakum mentions, that will apply authorization, which you probably don't want. So digging into the source for that method we see that we can resolve the URI like this:
from django.core.urlresolvers import resolve, get_script_prefix
def get_pk_from_uri(uri):
prefix = get_script_prefix()
chomped_uri = uri
if prefix and chomped_uri.startswith(prefix):
chomped_uri = chomped_uri[len(prefix)-1:]
try:
view, args, kwargs = resolve(chomped_uri)
except Resolver404:
raise NotFound("The URL provided '%s' was not a link to a valid resource." % uri)
return kwargs['pk']
If your Django application is located at the root of the webserver (i.e. get_script_prefix() == '/'
) then you can simplify this down to:
view, args, kwargs = resolve(uri)
pk = kwargs['pk']
这篇关于从tastypie uri获取模型对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!