Django会话与Oauth - 无法通过request.session传递变量

2 投票
1 回答
1024 浏览
提问于 2025-04-17 06:52

我正在开发一个应用程序,用来向像Facebook、LinkedIn这样的网页发起API请求。我需要使用OAuth来授权我的应用程序,以便代表用户请求数据。现在我遇到了一个问题,就是在不同的视图之间存储我的网站接口库(LinkedIn)的实例。我使用了request.session,并且是用文件作为后端存储。

下面是代码 http://pastebin.com/QTgqSr7W

我是不是做错了什么?我在login()函数中能看到值被设置,但在token()函数中却看不到同样的值。这是我不应该期待的吗?有没有什么方法可以传递API实例的值?

谢谢,祝好,
Atul.

1 个回答

1

嗯,我觉得这是因为你在保存整个 API 的 Python 实例。我觉得会话不支持这种数据。为什么不直接把用户重定向到认证网址,而不在会话中保存任何东西呢?然后在回调视图中,你可以像这样实例化 linkedin.LinkedIn 类。

from django.conf import settings

key = settings.KEY
secret = settings.SECRET
return_url = settings.CALLBACK


# You make the api connection here, so its not tied to any function
api = linkedin.LinkedIn(key, secret, return_url)

def login(request):
    if api.request_token():
        auth_url = api.get_authorize_url()
        return HttpResponseRedirect(auth_url)

#below is the view that will get called with the oauth oken.
def token(request, param):
    #do stuff with the api.

撰写回答