在Django 1.5.5项目中,我试图让移动客户通过Tastypie的API下注遭遇。读完POST数据后,我可以保存Bet
对象,但我需要User
实例。
我知道bundle.request.user
但是此引用在自定义视图中不可用(与此处prepend_urls
一起使用。
在我的自定义视图中,request.user
引用AnonymousUser
。使用Tastypie的ApiKeyAuthentication
保护API资源(我是否需要使用位于标题中的API密钥获取当前User
。)。
# ──────────────────────────────────────────────────────────────────────────────
class BaseResource(ModelResource):
# ──────────────────────────────────────
def prepend_urls(self):
try:
additional_urls = self._meta.additional_urls
except AttributeError:
additional_urls = []
return [url(r'^'+u[0]+'$', self.wrap_view(u[1]), name=u[2]) for u in additional_urls]
...
# ──────────────────────────────────────
class Meta:
abstract = True
allowed_methods = ['get',]
authentication = ApiKeyAuthentication()
authorization = DjangoAuthorization()
max_limit = 1000
# ──────────────────────────────────────────────────────────────────────────────
class EncounterResource(BaseResource):
...
# ──────────────────────────────────────
def bet(self, request, **kwargs):
self.method_check(request, allowed=['post'])
encounter = int(kwargs.get('encounter', 0))
if not encounter:
return self.create_response(request, {
'success': False,
'message': 'Pretty sure you\'re doing something wrong',
}, HttpApplicationError)
data = self.deserialize(
request,
request.body,
format=request.META.get('CONTENT_TYPE', 'application/json')
)
...
return self.create_response(request, {
'success': True,
}, HttpCreated)
# ──────────────────────────────────────
class Meta(BaseResource.Meta):
allowed_methods = ['get', 'post',]
queryset = Encounter.objects.all()
resource_name = 'encounters'
additional_urls = [
('encounters/(?P<encounter>\d+)/bet/', 'bet', 'api-encounter-bet'),
]
答案 0 :(得分:1)
查看&#34;发送&#34;可以。您想先调用is_authenticated
方法,然后使用request.user
https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py#L443