在视图(APIView)中的类中从URL读取字符串

时间:2019-01-08 04:53:55

标签: python django-rest-framework

我的模式中有一个类似于以下内容的网址

urlpatterns = [
...
    path('rest-auth/registration/account-confirm-email/<str:key>', VerifyEmailView.as_view(), name='account_confirm_email'),
...
]

我需要能够通过以下示例网址传递密钥(“ MjU:1ggiiI:923vm1cLboPQk9TX1f0aywDWBs8”)

http://127.0.0.1:8000/rest-auth/registration/account-confirm-email/MjU:1ggiiI:923vm1cLboPQk9TX1f0aywDWBs8/

到以下视图,

class VerifyEmailView(APIView):
    permission_classes = (AllowAny,)
    allowed_methods = ('POST','GET', 'OPTIONS', 'HEAD')
....
    def get(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        '''key is used here'''
        self.kwargs['key'] = serializer.validated_data['key']
        confirmation = self.get_object()
        confirmation.confirm(self.request)
....

有人可以告诉我如何在此视图中访问我的密钥吗?

3 个答案:

答案 0 :(得分:2)

在使用url参数时,您可以直接在get()中将其作为函数参数获取,请参见以下示例:

class VerifyEmailView(APIView):
    permission_classes = (AllowAny,)
    allowed_methods = ('POST','GET', 'OPTIONS', 'HEAD')
....
    def get(self, request, key):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        '''key is used here'''
        self.key = key
        confirmation = self.get_object()
        confirmation.confirm(self.request)
....

您在key变量中直接获得“ MjU:1ggiiI:923vm1cLboPQk9TX1f0aywDWBs8”。

有关更多信息,请查看this

答案 1 :(得分:0)

您可以使用

path = request.path
path_vals = path.split('/')
key = path_vals[-2]

答案 2 :(得分:0)

在#nishant和#Amit解决方案起作用的同时,这也应该起作用

def get(self, request, *args, **kwargs):
      kwargs=self.kwargs
      key=kwargs.get('key')

在这种情况下,Allauth实际上抱怨形式为以下网址:

path('rest-auth/registration/account-confirm-email/<str:key>', VerifyEmailView.as_view(), name='account_confirm_email'),

出现这样的错误: 异常值:

TemplateResponseMixin需要定义“ template_name”或实现“ get_template_names()”

,并期望以下形式的网址:

path('rest-auth/registration/account-confirm-email/', VerifyEmailView.as_view(), name='account_confirm_email'),

使用此#nishant解决方案在这里起作用