我正在使用tastypie为我的Django项目创建一个api . 我的项目要求用户登录以便对模型视图等进行编辑 . 因此,我的第一步是使用tastypie通过在UserResource中创建登录和注销功能来登录用户,如here所述 . 响应包含我用于注销的sessionid cookie . 我的资源使用SessionAuthentication和DjangoAuthorization . 但是当我尝试使用tastypie资源URL在模型上发布或放置或删除时,我收到错误401错误 . 有些人建议我必须使用有效的csrf_token . 但是当tastypie登录视图不会返回时,我怎么能这样做呢 . 示例代码:
class EntryResource(ModelResource):
customer = fields.ForeignKey(CustomerResourse, 'customer', full=True)
creator = fields.ForeignKey(UserResource,'creator',null=True,full=True,blank=True)
class Meta:
queryset = Entry.objects.all()
resource_name = 'entry'
authorization = DjangoAuthorization()
authentication = SessionAuthentication()
我的client.py
headers={"Content-Type":"application/json"}
#login. I don't get a csrftoken here, but works fine which is odd because i post data r
resp = requests.post(login_url, data=json.dumps(credentials), headers=headers)
cookies ={'sessionid':resp.cookies['sessionid']}
entry = {
'title':'New Entry',
'snippet':'New Snippet',
'created': datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
}
entry_json = json.dumps(entry)
entry_add_response = requests.post(entry_api_url,data=entry_json,
headers=headers,cookies=cookies)
#entry_add_response.status_code is 401
#logout works as it should
logout_resp = requests.get(logout_url, cookies=cookies)
我究竟做错了什么?我没有做正确的步骤吗?我的所有网址都附有?format = json . 试过没有没工作 . 我还尝试从django和会话身份验证和授权更改为基本(Authentication(),Authorization()) . 然后我得到500错误 . 我开始觉得有点绝望....