Django Cookies, как я могу установить их?

Модульный тест должен проверять одну единицу / функцию вашего кода по определению. Если он вызывает другие модульные тесты, он тестирует более одного модуля. Я разбиваю его на отдельные тесты.

116
задан Paul D. Waite 1 October 2012 в 19:17
поделиться

2 ответа

Это помощник для установки постоянного файла cookie:

import datetime

def set_cookie(response, key, value, days_expire = 7):
  if days_expire is None:
    max_age = 365 * 24 * 60 * 60  #one year
  else:
    max_age = days_expire * 24 * 60 * 60 
  expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT")
  response.set_cookie(key, value, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None)

Используйте следующий код перед отправкой ответа.

def view(request):
  response = HttpResponse("hello")
  set_cookie(response, 'name', 'jujule')
  return response

ОБНОВЛЕНИЕ : проверьте Peter's ответ ниже для встроенного решения:

65
ответ дан 24 November 2019 в 02:12
поделиться

You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).

18
ответ дан 24 November 2019 в 02:12
поделиться
Другие вопросы по тегам:

Похожие вопросы: