2012-05-16 29 views
0

我想添加reddit API的login功能,但不会保存cookie。以下代码在自定义身份验证后端中调用,该身份验证后端在堆栈中安装得比Django自带的ModelBackend更高。使用Reddit API登录时Cookie未保存

response = requests.post(REDDIT_LOGIN_URL, data={'user' : username, 
               'passwd' : password}) 
cookie = SimpleCookie() 
cookie.load(response.headers.get('set-cookie')) 

印刷的cookie [ 'reddit_session']返回了一下(模糊)

<Morsel: reddit_session='5356323%2C2012-05-15T17%3A15%3A08%xxxxxxxxxxxx7a4f25351b003a2484'> 

这个cookie,但是,无处在浏览器中找到。当页面重新加载时,我的reddit会话消失了,除非再次创建此会话,否则我无法使用其他reddit API调用。 当我使用Chrome开发人员工具查看我的Cookie时,我在Resources> Cookies下看到一个名为“空白”的条目。当我点击这个,我得到的是一个白色的页面,“这个网站有没有饼干”

我在Django-1.4这样,与

SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" 

settings.py中启用。我尝试过,没有得到相同的结果。

我在这里错过了什么吗?我也试过使用narwa,并且cookie也没有被保存。我的浏览器中肯定启用了Cookie,因为同一个Django会话保存了django_language和session_id cookie。

任何指针或答案表示赞赏。

+0

为什么不使用HttpResponse_object.set_cookie方法在浏览器中删除cookie? –

+0

您的问题在所有浏览器中都存在吗? –

+0

它在所有浏览器中是否一致? SimpleCookie不应该放弃cookie吗?由于我在Authentication Backend模块中获得了Reddit响应,因此我没有可用的HttpResponse对象。 –

回答

1

我并不确定,但是当我玩API时,我只需要存储modhash并将其发送到我的请求中。另外,如果您使用的是requests模块,请改为使用会话实例,并将它存储在呼叫之间。不过,我不确定这将如何发挥到Django。以下是我为登录所写的代码:

def login(username, password): 
    """logs into reddit, saves cookie""" 

    print 'begin log in' 
    #username and password 
    UP = {'user': username, 'passwd': password, 'api_type': 'json',} 
    headers = {'user-agent': '/u/STACKOVERFLOW\'s API python bot', } 
    #POST with user/pwd 
    client = requests.session() 

    r = client.post('http://www.reddit.com/api/login', data=UP) 

    #print r.text 
    #print r.cookies 

    #gets and saves the modhash 
    j = json.loads(r.text) #I believe r.json == j at this point 

    client.modhash = j['json']['data']['modhash'] 
    print '{USER}\'s modhash is: {mh}'.format(USER=username, mh=client.modhash) 

    #pp2(j) 

    return client