Django休息框架社交oauth2 api url和响应定制

问题描述 投票:0回答:1

我正在制作一个API系统,它遵循localhost:8080/api/v1/end_name这样的网址,我正在使用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": "[email protected]"
    }
}

我需要在我的data: {}回应。我的一个问题是

  • 我该怎么做?

我的另一个问题是

  • 我可以自定义api url localhost:8080/auth/tokenlocalhost:8080/api/v1/auth/token吗?
django django-rest-framework django-socialauth django-oauth
1个回答
0
投票

我最终提出了解决方案。要进行自定义响应,我必须覆盖他们的方法并根据我的需要自定义响应。这里调用的方法名为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制造方法。

© www.soinside.com 2019 - 2024. All rights reserved.