2016-11-24 33 views
1

我正在使用Python 2.7中的請求2.12.1庫和Django 1.10來使用Web服務。當我使用會話保存cookie並使用持久性,並且傳遞10秒〜而不使用任何web服務時,我的視圖重新生成對象requests.Session()...爲什麼我的請求會話過期?

這使Web服務不能爲我服務,因爲我的觀點已經改變了cookies。

這是我Views.py:

client_session = requests.Session() 

@watch_login 
def loginUI(request): 
     response  = client_session.post(URL_API+'login/', data={'username': username, 'password': password,}) 
     json_login  = response.json() 

@login_required(login_url="/login/") 
def home(request): 
    response_statistics = client_session.get(URL_API+'statistics/') 
    log('ClientSession: '+str(client_session)) 

    try: 
     json_statistics  = response_statistics.json() 
    except ValueError: 
     log('ExcepcionClientSession: '+str(client_session)) 

     return logoutUI(request) 

    return render(request, "UI/home.html", { 
     'phone_calls'   : json_statistics['phone_calls'], 
     'mobile_calls'   : json_statistics['mobile_calls'], 
     'other_calls'   : json_statistics['other_calls'], 
     'top_called_phones'  : json_statistics['top_called_phones'], 
     'call_ranges_week'  : json_statistics['call_ranges_week'], 
     'call_ranges_weekend' : json_statistics['call_ranges_weekend'], 
     'access_data'   : accessData(request.user.username), 
    }) 

    def userFeaturesFormInit(clientRequest): 
    log('FeaturesClientSession: '+str(client_session)) 
    response = client_session.get(URL_API+'features/') 

    try: 
     json_features = response.json() 
    except ValueError as e: 
     log('ExcepcionFeaturesClientSession: '+str(client_session)) 
     raise e 

謝謝。

+0

你使用Django? – Marcs

+0

是的,我使用django。 – ILoveYouDrZaius

回答

0

我修正它手動指定cookie並將其保存在請求中。

client_session = requests.Session() 
response = client_session.post(URL_API+'login/', {'username': username, 'password': password,}) 
request.session['cookiecsrf']  = client_session.cookies['csrftoken'] 
request.session['cookiesession'] = client_session.cookies['sessionid'] 

併發送它在獲取/職位:

cookies = {'csrftoken' : request.session['cookiecsrf'], 'sessionid': request.session['cookiesession']} 
response = requests.get(URL, cookies=cookies) 
相關問題