(DJANGO)如何从视图重定向到另一个URL?

时间:2020-02-10 15:14:25

标签: python django spotify

我是Django的新手,现在在从当前视图重定向到另一个URL时遇到一些问题。在这种情况下,我想重定向到Spotify登录页面。

这是我的观点:

#############################################################################
client_id = 'somestring'; # Your client id
client_secret = 'anotherstring'; # Your secret
redirect_uri = 'http://127.0.0.1:8000/callback/'; # Your redirect uri
stateKey = 'spotify_auth_state'
#############################################################################

def generateRandomString(length):
    text = ''
    possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'

    for i in range(0,length):
         text += possible[math.floor(random.random() * len(possible))] 
    return text

##############################################################################


def login_process(request):

    if request.method == 'GET':

        state = generateRandomString(16)
        print(str(state))
        HttpResponse.set_cookie(stateKey, state)

        #your application requests authorization
        scope = 'user-top-read user-read-email'
        return HttpResponseRedirect(request, 'https://accounts.spotify.com/authorize?' + urllib.parse.urlencode({
          response_type: 'code',
          client_id: client_id,
          scope: scope,
          redirect_uri: redirect_uri,
          state: state
        }), {})

def login_view(request, *args, **kwargs):
    print(args, kwargs)
    print(request.user)
    #return HttpResponse("<h1>Hello world</h1>")
    return render(request, "login.html", {})




def callback_view(request, *args, **kwargs):
    return render(request, "callback.html", {})


这是我应该点击以重定向的链接:

    <a href="login/">Login with spotify</a>

这是我的urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', login_view, name='login_view'),
    path('login/', login_process, name = 'login'),
    path('callback/', callback_view, name = 'callback_view'),
]

我得到的错误是“ / login /'str'对象的AttributeError没有属性'cookies'”,我什至不知道方法“ return HttpResponseRedirect”是否是完成所有这些事情的正确方法。你能帮我吗?

1 个答案:

答案 0 :(得分:1)

这里:

HttpResponse.set_cookie(stateKey, state)

您是在类本身而不是实例上调用HttpResponse.set_cookie,因此您将获得一个将实例作为第一个参数的未绑定方法。正确的方法实际上是先实例化响应,然后在其上调用set_cookie

qs = urllib.parse.urlencode({
          "response_type": 'code',
          "client_id": client_id,
          "scope": scope,
          "redirect_uri": redirect_uri,
          "state": state
        })
url = 'https://accounts.spotify.com/authorize?{}'.format(qs) 
response = HttpResponseRedirect(request, url)
reponse.set_cookie(whatever)
return response