【问题标题】:Django rest framework social oauth2 api url and response customizationDjango rest框架social oauth2 api url和响应定制
【发布时间】:2019-07-26 14:38:38
【问题描述】:

我正在制作一个 API 系统,它遵循 localhost:8080/api/v1/end_name 之类的 url,并且我正在使用 django-rest-framework-social-oauth2 库进行社交身份验证,也用于我的自定义用户身份验证。问题是他们正在为像localhost:8080/auth/token这样的url提供api响应,格式如下:

{
"access_token": "........",
"expires_in": 36000,
"token_type": "Bearer",
"scope": "read write",
"refresh_token": "......"
}

但我需要以我的方式自定义它,因为我的响应格式不同。我的一个就像跟随..

{
    "error": false,
    "message": "User created successfully",
    "data": {
        "email": "localtestuse2@beliefit.com"
    }
}

我需要data: {} 中的回复。我的一个问题是

  • 我该怎么做?

我的另一个问题是

  • 我可以将api url localhost:8080/auth/token自定义为localhost:8080/api/v1/auth/token吗?

【问题讨论】:

    标签: django django-rest-framework django-socialauth django-oauth


    【解决方案1】:

    我最终想出了解决方案。要进行自定义响应,我必须覆盖他们的方法并根据我的需要自定义响应。这里调用的方法名为TokenView。所以我按照以下方式对其进行了自定义

    class UserLoginView(TokenView):
    @method_decorator(sensitive_post_parameters("password"))
    def post(self, request, *args, **kwargs):
        url, headers, body, status = self.create_token_response(request)
        # body is str here, we need to make it proper json
        data = json.loads(body)
    
        if status != 200:
            response = Response(makeContext(True, "Couldn't generated token", data))
        else:
            response = Response(makeContext(False, "Token generated successfully", data))
    
        response.accepted_renderer = JSONRenderer()
        response.accepted_media_type = "application/json"
        response.renderer_context = {}
        return response
    

    这里makecontext是我自定义的json maker方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-08
      • 2021-11-05
      • 2020-06-17
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      相关资源
      最近更新 更多