【发布时间】:2020-02-10 15:14:25
【问题描述】:
我是 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'),
]
我得到的错误是“AttributeError at /login/'str' object has no attribute 'cookies'”,我什至不知道“return HttpResponseRedirect”方法是否是做所有这些事情的正确方法。你能帮帮我吗?
【问题讨论】: