0

I would like to add the login feature of the reddit API, but the cookie is not being saved. The following code is being called in a custom Authentication Backend, which is installed higher in the stack than Django's own ModelBackend.

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

printing cookie['reddit_session'] returns a Morsel (obfuscated)

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

This Cookie, however, is nowhere found in my browser. When the page is reloaded, my reddit session is gone, and I can not use other reddit API calls unless I create this session again. When I use the Chrome developer tools to look at my cookies, I see an entry under Resources > Cookies called "blank". When I click this, all I get is a white page with "This site has no cookies"

I am doing this in django-1.4, with

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

enabled in settings.py. I tried it without with the same results.

Am I missing something here? I've tried using narwa as well, and the cookie is not being saved either. My cookies are definitely enabled in my browser as the same Django session is saving the django_language and session_id cookies.

Any pointers or answers are appreciated.

4

1 回答 1

1

我不太确定,但是当我在使用 API 时,我只需要存储它modhash并将其与我的请求一起发送。此外,如果您正在使用该requests模块,请改用会话实例,它将跨调用存储 cookie。不过,我不确定这对 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
于 2012-06-26T13:12:40.660 回答