【问题标题】:Why my requests session expire?为什么我的请求会话过期?
【发布时间】:2016-12-01 21:27:16
【问题描述】:

我在 Python 2.7 和 Django 1.10 中使用 requests 2.12.1 库来使用 Web 服务。当我使用会话保存 cookie 并使用持久性,并通过 10 秒〜不使用任何 Web 服务时,我的视图重新生成对象 requests.Session()...

这使得网络服务无法为我服务,因为我的视图改变了 cookie。

这是我的 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

谢谢。

【问题讨论】:

  • 你在用 django 吗?
  • 是的,我正在使用 django。

标签: python session cookies python-requests persistence


【解决方案1】:

我修复了它手动指定 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)

【讨论】:

    猜你喜欢
    • 2012-10-02
    • 1970-01-01
    • 2012-07-22
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 2016-01-15
    相关资源
    最近更新 更多