2
class CreateUserResource(ModelResource):
    class Meta:
        allowed_methods = ['post']
        object_class = User
        authentication = ApiKeyAuthentication()
        authorization = DjangoAuthorization()
        include_resource_uri = False
        fields = ['username']
        models.signals.post_save.connect(create_api_key, sender=User)

    def obj_create(self, bundle, request=None, **kwargs):
        username, password = bundle.data['username'], bundle.data['password']
        #try:
        bundle.obj = User.objects.create_user(username, '', password)
        #except IntegrityError:
            #raise BadRequest('That username already exists')
        #return bundle

我正在使用此资源来创建新用户。但为了做到这一点,我需要一个 api_key。由于我是匿名的,我怎样才能获得 api_key?

4

1 回答 1

2

你为什么不创建一个未经身份验证/授权的用户?

authentication = Authentication()
authorization = Authorization()

ApiKeyAuthentication() 需要一个 appr。数据库表“tastypie_apikey”中的条目...

这是我在未经身份验证时创建用户帐户的方式:

class CreateUserResource(ModelResource):
    class Meta:
        resource_name = 'user'
        allowed_methods = ['post']
        object_class = User
        authentication = Authentication()
        authorization = Authorization()
        include_resource_uri = False
        fields = ['username']

    def obj_create(self, bundle, request=None, **kwargs):
        try:
            bundle = super(CreateUserResource, self).obj_create(bundle, request, **kwargs)
            bundle.obj.set_password(bundle.data.get('password'))
            bundle.obj.save() 
            '''assign user to a group w/ sufficient permissions''' 
            user = User.objects.get(id=bundle.obj.id)
            group = Group.objects.get(id=1)
            user.groups.add(group)
        except IntegrityError:
            raise BadRequest('That username already exists')
        return bundle
于 2012-08-01T17:08:00.537 回答