一、Cookie

  1、cookie机制

  会话(Session)跟踪是Web程序中常用的技术,用来跟踪用户的整个会话。常用的会话跟踪技术是Cookie与Session。Cookie通过在客户端记录信息确定用户身份Session通过在服务器端记录信息确定用户身份

  在程序中,会话跟踪是很重要的事情。理论上,一个用户的所有请求操作都应该属于同一个会话,而另一个用户的所有请求操作则应该属于另一个会话,二者不能混淆。例如,用户A在超市购买的任何商品都应该放在A的购物车内,不论是用户A什么时间购买的,这都是属于同一个会话的,不能放入用户B或用户C的购物车内,这不属于同一个会话。

  而Web应用程序是使用HTTP协议传输数据的。HTTP协议是无状态的协议。一旦数据交换完毕,客户端与服务器端的连接就会关闭,再次交换数据需要建立新的连接。这就意味着服务器无法从连接上跟踪会话。即用户A购买了一件商品放入购物车内,当再次购买商品时服务器已经无法判断该购买行为是属于用户A的会话还是用户B的会话了。要跟踪该会话,必须引入一种机制。

  Cookie就是这样的一种机制。它可以弥补HTTP协议无状态的不足。在Session出现之前,基本上所有的网站都采用Cookie来跟踪会话。

  关于cookie,需要记住几点:

    - 1.cookie是保存在用户浏览器的已加密的键值对

    - 2.可以被主动清除(浏览器界面、前端、后台)

    - 3.可以被"伪造"

    - 4.处于隐私保护的目的,禁止跨域共享:即www.googole.com和www.baidu.com各自的cookie不可被共享,因为域名对应的谷歌公司和百度公司服务器是不同的。

  2、cookie设置  

  在django中,cookie是在声明一个HttpResponse之后,通过set_cookie方法来设置的。它通过在响应头里Set-Cookie设置键值对来实现在浏览器客户端保存Cookie。

# views.py
from django.http import HttpResponse
# 打开源码
# HttpResponse类,继承了HttpResponseBase,在HttpResponse类中没有关于cookiede方法
class HttpResponse(HttpResponseBase):
"""
An HTTP response class with a string as content.
This content that can be read, appended to, or replaced.
"""
streaming = False def __init__(self, content=b'', *args, **kwargs):
super().__init__(*args, **kwargs)
# Content is a bytestring. See the `content` property methods.
self.content = content
...... # 查看HttpResponseBase类
class HttpResponseBase:
......
def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
domain=None, secure=False, httponly=False):
"""
Set a cookie.
``expires`` can be:
- a string in the correct format,
- a naive ``datetime.datetime`` object in UTC,
- an aware ``datetime.datetime`` object in any time zone.
If it is a ``datetime.datetime`` object then calculate ``max_age``.
"""
self.cookies[key] = value
if expires is not None:
if isinstance(expires, datetime.datetime):
if timezone.is_aware(expires):
expires = timezone.make_naive(expires, timezone.utc)
delta = expires - expires.utcnow()
# Add one second so the date matches exactly (a fraction of
# time gets lost between converting to a timedelta and
# then the date string).
delta = delta + datetime.timedelta(seconds=)
# Just set max_age - the max_age logic will set expires.
expires = None
max_age = max(, delta.days * + delta.seconds)
else:
self.cookies[key]['expires'] = expires
else:
self.cookies[key]['expires'] = ''
if max_age is not None:
self.cookies[key]['max-age'] = max_age
# IE requires expires, so set it if hasn't been already.
if not expires:
self.cookies[key]['expires'] = cookie_date(time.time() +
max_age)
if path is not None:
self.cookies[key]['path'] = path
if domain is not None:
self.cookies[key]['domain'] = domain
if secure:
self.cookies[key]['secure'] = True
if httponly:
self.cookies[key]['httponly'] = True
def setdefault(self, key, value):
"""Set a header unless it has already been set."""
if key not in self:
self[key] = value
  # 签名的cookie
def set_signed_cookie(self, key, value, salt='', **kwargs): # salt加盐之后并加密;与它相应的用request.COOKIES.get_signed_cookie(...)来解密
value = signing.get_cookie_signer(salt=key + salt).sign(value)
return self.set_cookie(key, value, **kwargs) def delete_cookie(self, key, path='/', domain=None): # 删除cookie
self.set_cookie(key, max_age=, path=path, domain=domain,
expires='Thu, 01-Jan-1970 00:00:00 GMT')
...

  3、cookie参数

属  性  名 描    述
String name 该Cookie的名称。Cookie一旦创建,名称便不可更改
Object value 该Cookie的值。如果值为Unicode字符,需要为字符编码。如果值为二进制数据,则需要使用BASE64编码
int maxAge 该Cookie失效的时间,单位秒。如果为正数,则该Cookie在maxAge秒之后失效。如果为负数,该Cookie为临时Cookie,关闭浏览器即失效,浏览器也不会以任何形式保存该Cookie。如果为0,表示删除该Cookie。默认为–1
boolean secure 该Cookie是否仅被使用安全协议传输。安全协议。安全协议有HTTPS,SSL等,在网络上传输数据之前先将数据加密。默认为false。当使用https式,必须要secure设置为Y=True。
String path 该Cookie的使用路径。如果设置为“/sessionWeb/”,则只有contextPath为“/sessionWeb”的程序可以访问该Cookie。如果设置为“/”,则本域名下contextPath都可以访问该Cookie。注意最后一个字符必须为“/”
String domain 可以访问该Cookie的域名。如果设置为“.google.com”,则所有以“google.com”结尾的域名都可以访问该Cookie。注意第一个字符必须为“.”
boolean httponly 限制在浏览器控制台获取键值对,但无法对抓包工具进行限制。

  4、用例

from django.shortcuts import render, redirect
import datetime def login(request):
msg = ""
# print(request.environ["Set-Cookie"])
if request.method == "POST":
user= request.POST.get("user", False)
pwd = request.POST.get("pwd", False)
if user == "root" and pwd == "root":
red = redirect("index") # 同JsonResponse, FileResponse, render, HttpResponse一样,redirect是HttpResponseBase的子类,red是一个httpresponse对象
# red.set_cookie("username", user)
# print(red.items())
# print(red.serialize_headers())
# print("cookie", red.cookies)
# print(red.content)
# print(red.status_code)
# print(red.has_header("Cookie"))
# red.set_cookie("key", "value", expires=datetime.timedelta(seconds=20), )
red.set_cookie("key", "value", max_age=20, path="/app04/", domain="127.0.0.1", httponly=False)
return red
else:
msg = "用户名或密码错误"
return render(request, 'app04/login.html', {"msg": msg})

  链接[https://blog.csdn.net/gaoyong_stone/article/details/79524321]

二、Session

  1、session机制

  为了保持会话,客户端浏览器可以在用户登录后,将cookie从本地读入客户端内存;因为cookie放在请求头中,所以在服务端也可以通过request.COOKIE来获取所有的cookie值。服务端可以通过响应头中的Set-Cookie字段来告诉浏览器添加、修改或删除cookie。执行cookie的主体是客户端浏览器

  session则是在request到来时,通过SessionMiddleWare中间件,在进行视图函数执行之前,做了一些操作。它在Cookie中生成了一段随机字符串作为session id,并且将key-value随机化处理,存储到了服务器(django默认存在django_session表里)。

  来扒一下django的源码,彻底理清楚session的整个流程:

# 1.查找django.contrib.sessions.middleware.SessionMiddleware中间件,因为session是由这个中间件定义的,所以一定要看清它在一次请求中干了什么勾当
# from django.contrib.sessions.middleware import SessionMiddleware
# 2.点开SessionMiddleware,源码如下: import time
from importlib import import_module from django.conf import settings
from django.contrib.sessions.backends.base import UpdateError
from django.core.exceptions import SuspiciousOperation
from django.utils.cache import patch_vary_headers
from django.utils.deprecation import MiddlewareMixin
from django.utils.http import cookie_date class SessionMiddleware(MiddlewareMixin):
def __init__(self, get_response=None):
self.get_response = get_response
    # 7.self.SessionStore是一个session存储引擎的实例化对象
    # 它是根据settings.SESSIOn_ENGINE的值(默认是
django.contrib.sessions.backends.db)来导入相应的db模块【跳转到下面第二个文档】
engine = import_module(settings.SESSION_ENGINE)
self.SessionStore = engine.SessionStore
  # process_request在调用视图函数之前被调用
def process_request(self, request):
     # 1.从request.COOKIES那里获取了一个默认您设置变量settings.SESSION_COOKIE_NAME作为session_key【跳转到下面第一个文档】

     session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME) # 5.紧挨着下面的3.4.5步,得知sessionid是django自带的session_key的cookie中的名字名字
     # 6.生成一个reqeust属性,名为session,它的值是一个SessionStore对象,这个对象包含了accessed和modified
     
request.session = self.SessionStore(session_key)
     # 10、根据下面的步骤9,可以知道request.session就是一个对象,这个对象可以以字典的形式添加键值对,并支持向django_session或者其它数据库(缓存)中写入/修改/删除操作。
  # process_response在返回响应前调用
def process_response(self, request, response):
"""
If request.session was modified, or if the configuration is to save the
session every time, save the changes and set a session cookie or delete
the session cookie if the session has been emptied.
"""
try:
       # 11.accessed不用管,看modified;在步骤9中得知,一但request.session传入了键值对,这货就是True
accessed = request.session.accessed
modified = request.session.modified
empty = request.session.is_empty()
except AttributeError:
pass
else:
# First check if we need to delete this cookie.
# The session should be deleted only if the session is entirely empty
if settings.SESSION_COOKIE_NAME in request.COOKIES and empty:
response.delete_cookie(
settings.SESSION_COOKIE_NAME,
path=settings.SESSION_COOKIE_PATH,
domain=settings.SESSION_COOKIE_DOMAIN,
)
else:
if accessed:
patch_vary_headers(response, ('Cookie',))
          # 12.如果session被设置,那么走这一步
if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty:
if request.session.get_expire_at_browser_close():
max_age = None
expires = None
else:
max_age = request.session.get_expiry_age()
expires_time = time.time() + max_age
expires = cookie_date(expires_time)
# Save the session data and refresh the client cookie.
# Skip session save for 500 responses, refs #3881.
if response.status_code != 500:
try:
                 # 调用SessionStore.save()方法,往数据库写入session
request.session.save()
except UpdateError:
raise SuspiciousOperation(
"The request's session was deleted before the "
"request completed. The user may have logged "
"out in a concurrent request, for example."
)
               # 13.在response响应前,通过response.set_cookie方法将sessionid(前面赋值了settings.SESSION_COOKIE_NAME)以及参数写到响应头中
response.set_cookie(
settings.SESSION_COOKIE_NAME,
request.session.session_key, max_age=max_age,
expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
path=settings.SESSION_COOKIE_PATH,
secure=settings.SESSION_COOKIE_SECURE or None,
httponly=settings.SESSION_COOKIE_HTTPONLY or None,
)
     # 14.将response做上述处理后,将response交给下一个中间件
return response
  """
  2.在这里,根据from django.conf import settings打开settings,进到django.conf.__init__.py中
  3.再根据from django.conf import global_settings打开global_sesstings.py,可以看到有关session的设置如下:

    """
    """
    Default Django settings. Override these with settings in the module pointed to
    by the DJANGO_SETTINGS_MODULE environment variable.
    """
    ...
    ############
    # SESSIONS #
    ############     # Cache to store session data if using the cache session backend.
    SESSION_CACHE_ALIAS = 'default'
    # Cookie name. This can be whatever you want.
    SESSION_COOKIE_NAME = 'sessionid'
    # Age of cookie, in seconds (default: 2 weeks).
    SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2
    # A string like "example.com", or None for standard domain cookie.
    SESSION_COOKIE_DOMAIN = None
    # Whether the session cookie should be secure (https:// only).
    SESSION_COOKIE_SECURE = False
    # The path of the session cookie.
    SESSION_COOKIE_PATH = '/'
    # Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others)
    SESSION_COOKIE_HTTPONLY = True
    # Whether to save the session data on every request.
    SESSION_SAVE_EVERY_REQUEST = False
    # Whether a user's session cookie expires when the Web browser is closed.
    SESSION_EXPIRE_AT_BROWSER_CLOSE = False
    # The module to store session data
    SESSION_ENGINE = 'django.contrib.sessions.backends.db'
    # Directory to store session files if using the file session module. If None,
    # the backend will use a sensible default.
    SESSION_FILE_PATH = None
    # class to serialize session data
    SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
    """
    ...
  # 4.可以看到这是django默认的环境配置文件,并且文件开头,提示可以通过在项目文件夹下的settings.py重写变量来重新配置这些环境变量。
  """
# 8.通过 from django.contrib.sessions.backends import db 导入db.py,源码如下:
# 它做了两件事情:第一件,继承了SessionBase类,这个类生成了session字典,并提供了该字典的增删改差的基本操作;第二件,自己在这个字典对象上又添加了一些额外的静态方法和实例方法
# 这些静态方法和实例方法主要用于操作缓存或者数据库中的django_session表
# 接着点开SessionBase,它的源码文件如下面内容所示【跳转到下面】

...
from django.contrib.sessions.backends.base import (
CreateError, SessionBase, UpdateError,
)
...
class SessionStore(SessionBase):
"""
Implement database session store.
"""
def __init__(self, session_key=None):
super().__init__(session_key)
@classmethod
def get_model_class(cls):
# Avoids a circular import and allows importing SessionStore when
# django.contrib.sessions is not in INSTALLED_APPS.
from django.contrib.sessions.models import Session
return Session
@cached_property
def model(self):
return self.get_model_class()
def load(self)def exists(self, session_key):
return self.model.objects.filter(session_key=session_key).exists()
def create(self)
def create_model_instance(self, data)def save(self, must_create=False)
def delete(self, session_key=None)
@classmethod
def clear_expired(cls)
# 9.这个SessionBase就是所有配置session数据库的基类,它规定了session字典层面上的操作,包括增删改查以及对age、expire、encode等的设置
# 【跳转回第一个文件】

...
# session_key should not be case sensitive because some backends can store it
# on case insensitive file systems.
...
class SessionBase:
"""
Base class for all Session classes.
"""
TEST_COOKIE_NAME = 'testcookie'
TEST_COOKIE_VALUE = 'worked' __not_given = object() def __init__(self, session_key=None):
self._session_key = session_key # 注意:初始化self._session_key = None,但是当设置了session键值对之后,self._session_key就成了字典
self.accessed = False
self.modified = False
self.serializer = import_string(settings.SESSION_SERIALIZER) def __contains__(self, key)def __getitem__(self, key)def __setitem__(self, key, value):
    self._session_key = value
    self.modified = True # 注意,一旦session添加了一个键值对,self.modified的值就变成了Truedef __delitem__(self, key)def get(self, key, default=None)def pop(self, key, default=__not_given)def setdefault(self, key, value):def set_test_cookie(self):def test_cookie_worked(self)def delete_test_cookie(self)def _hash(self, value)def encode(self, session_dict)def decode(self, session_data)def update(self, dict_)def has_key(self, key)def keys(self)def values(self)def items(self)def clear(self)def is_empty(self)def _get_new_session_key(self)def _get_or_create_session_key(self)def _validate_session_key(self, key)
def _get_session_key(self)
def _set_session_key(self, value)def _get_session(self, no_load=False)def get_expiry_age(self, **kwargs)def get_expiry_date(self, **kwargs)def set_expiry(self, value)def get_expire_at_browser_close(self)def flush(self)def cycle_key(self)
def exists(self, session_key)def create(self)def save(self, must_create=False)def delete(self, session_key=None)def load(self)
@classmethod
def clear_expired(cls)

  上面的整个流程如下图所示:

  总结一下session和cookie:

    - session和cookie一样,都是通过response.set_cookie来设置的;

    - session将名为"sessionid"(默认)的key交给浏览器保存,将键值对(session_key和session_date)存储在服务器;cookie将键值对直接保存到客户端浏览器文件夹下;

    - session借助SessionMiddle中间件实现了对request.session对象的生成和对response.set_cookie的设置,分别在process_request和process_response里;cookie直接在视图函数中写即可;

    - 要记住django.contrib.sessions.backends是用来搞session的文件夹,request.session数据库读写方法在.db.SessionStore类里,requesion.session字典操作方法在.base.SessionBase里

  2、session配置

  在django.conf.global_settings文件中包含了对所有django默认环境变量的配置,这里把源码拉出来看一下(500行):

"""
Default Django settings. Override these with settings in the module pointed to
by the DJANGO_SETTINGS_MODULE environment variable.
""" # This is defined here as a do-nothing function because we can't import
# django.utils.translation -- that module depends on the settings.
def gettext_noop(s):
return s ####################
# CORE #
#################### DEBUG = False # Whether the framework should propagate raw exceptions rather than catching
# them. This is useful under some testing situations and should never be used
# on a live site.
DEBUG_PROPAGATE_EXCEPTIONS = False # Whether to use the "ETag" header. This saves bandwidth but slows down performance.
# Deprecated (RemovedInDjango21Warning) in favor of ConditionalGetMiddleware
# which sets the ETag regardless of this setting.
USE_ETAGS = False # People who get code error notifications.
# In the format [('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com')]
ADMINS = [] # List of IP addresses, as strings, that:
# * See debug comments, when DEBUG is true
# * Receive x-headers
INTERNAL_IPS = [] # Hosts/domain names that are valid for this site.
# "*" matches anything, ".example.com" matches example.com and all subdomains
ALLOWED_HOSTS = [] # Local time zone for this installation. All choices can be found here:
# https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all
# systems may support all possibilities). When USE_TZ is True, this is
# interpreted as the default user time zone.
TIME_ZONE = 'America/Chicago' # If you set this to True, Django will use timezone-aware datetimes.
USE_TZ = False # Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us' # Languages we provide translations for, out of the box.
LANGUAGES = [
('af', gettext_noop('Afrikaans')),
('ar', gettext_noop('Arabic')),
('ast', gettext_noop('Asturian')),
('az', gettext_noop('Azerbaijani')),
('bg', gettext_noop('Bulgarian')),
('be', gettext_noop('Belarusian')),
('bn', gettext_noop('Bengali')),
('br', gettext_noop('Breton')),
('bs', gettext_noop('Bosnian')),
('ca', gettext_noop('Catalan')),
('cs', gettext_noop('Czech')),
('cy', gettext_noop('Welsh')),
('da', gettext_noop('Danish')),
('de', gettext_noop('German')),
('dsb', gettext_noop('Lower Sorbian')),
('el', gettext_noop('Greek')),
('en', gettext_noop('English')),
('en-au', gettext_noop('Australian English')),
('en-gb', gettext_noop('British English')),
('eo', gettext_noop('Esperanto')),
('es', gettext_noop('Spanish')),
('es-ar', gettext_noop('Argentinian Spanish')),
('es-co', gettext_noop('Colombian Spanish')),
('es-mx', gettext_noop('Mexican Spanish')),
('es-ni', gettext_noop('Nicaraguan Spanish')),
('es-ve', gettext_noop('Venezuelan Spanish')),
('et', gettext_noop('Estonian')),
('eu', gettext_noop('Basque')),
('fa', gettext_noop('Persian')),
('fi', gettext_noop('Finnish')),
('fr', gettext_noop('French')),
('fy', gettext_noop('Frisian')),
('ga', gettext_noop('Irish')),
('gd', gettext_noop('Scottish Gaelic')),
('gl', gettext_noop('Galician')),
('he', gettext_noop('Hebrew')),
('hi', gettext_noop('Hindi')),
('hr', gettext_noop('Croatian')),
('hsb', gettext_noop('Upper Sorbian')),
('hu', gettext_noop('Hungarian')),
('ia', gettext_noop('Interlingua')),
('id', gettext_noop('Indonesian')),
('io', gettext_noop('Ido')),
('is', gettext_noop('Icelandic')),
('it', gettext_noop('Italian')),
('ja', gettext_noop('Japanese')),
('ka', gettext_noop('Georgian')),
('kab', gettext_noop('Kabyle')),
('kk', gettext_noop('Kazakh')),
('km', gettext_noop('Khmer')),
('kn', gettext_noop('Kannada')),
('ko', gettext_noop('Korean')),
('lb', gettext_noop('Luxembourgish')),
('lt', gettext_noop('Lithuanian')),
('lv', gettext_noop('Latvian')),
('mk', gettext_noop('Macedonian')),
('ml', gettext_noop('Malayalam')),
('mn', gettext_noop('Mongolian')),
('mr', gettext_noop('Marathi')),
('my', gettext_noop('Burmese')),
('nb', gettext_noop('Norwegian Bokmål')),
('ne', gettext_noop('Nepali')),
('nl', gettext_noop('Dutch')),
('nn', gettext_noop('Norwegian Nynorsk')),
('os', gettext_noop('Ossetic')),
('pa', gettext_noop('Punjabi')),
('pl', gettext_noop('Polish')),
('pt', gettext_noop('Portuguese')),
('pt-br', gettext_noop('Brazilian Portuguese')),
('ro', gettext_noop('Romanian')),
('ru', gettext_noop('Russian')),
('sk', gettext_noop('Slovak')),
('sl', gettext_noop('Slovenian')),
('sq', gettext_noop('Albanian')),
('sr', gettext_noop('Serbian')),
('sr-latn', gettext_noop('Serbian Latin')),
('sv', gettext_noop('Swedish')),
('sw', gettext_noop('Swahili')),
('ta', gettext_noop('Tamil')),
('te', gettext_noop('Telugu')),
('th', gettext_noop('Thai')),
('tr', gettext_noop('Turkish')),
('tt', gettext_noop('Tatar')),
('udm', gettext_noop('Udmurt')),
('uk', gettext_noop('Ukrainian')),
('ur', gettext_noop('Urdu')),
('vi', gettext_noop('Vietnamese')),
('zh-hans', gettext_noop('Simplified Chinese')),
('zh-hant', gettext_noop('Traditional Chinese')),
] # Languages using BiDi (right-to-left) layout
LANGUAGES_BIDI = ["he", "ar", "fa", "ur"] # If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
LOCALE_PATHS = [] # Settings for language cookie
LANGUAGE_COOKIE_NAME = 'django_language'
LANGUAGE_COOKIE_AGE = None
LANGUAGE_COOKIE_DOMAIN = None
LANGUAGE_COOKIE_PATH = '/' # If you set this to True, Django will format dates, numbers and calendars
# according to user current locale.
USE_L10N = False # Not-necessarily-technical managers of the site. They get broken link
# notifications and other various emails.
MANAGERS = ADMINS # Default content type and charset to use for all HttpResponse objects, if a
# MIME type isn't manually specified. These are used to construct the
# Content-Type header.
DEFAULT_CONTENT_TYPE = 'text/html'
DEFAULT_CHARSET = 'utf-8' # Encoding of files read from disk (template and initial SQL files).
FILE_CHARSET = 'utf-8' # Email address that error messages come from.
SERVER_EMAIL = 'root@localhost' # Database connection info. If left empty, will default to the dummy backend.
DATABASES = {} # Classes used to implement DB routing behavior.
DATABASE_ROUTERS = [] # The email backend to use. For possible shortcuts see django.core.mail.
# The default is to use the SMTP backend.
# Third-party backends can be specified by providing a Python path
# to a module that defines an EmailBackend class.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending email.
EMAIL_HOST = 'localhost' # Port for sending email.
EMAIL_PORT = 25 # Whether to send SMTP 'Date' header in the local time zone or in UTC.
EMAIL_USE_LOCALTIME = False # Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
EMAIL_USE_SSL = False
EMAIL_SSL_CERTFILE = None
EMAIL_SSL_KEYFILE = None
EMAIL_TIMEOUT = None # List of strings representing installed apps.
INSTALLED_APPS = [] TEMPLATES = [] # Default form rendering class.
FORM_RENDERER = 'django.forms.renderers.DjangoTemplates' # Default email address to use for various automated correspondence from
# the site managers.
DEFAULT_FROM_EMAIL = 'webmaster@localhost' # Subject-line prefix for email messages send with django.core.mail.mail_admins
# or ...mail_managers. Make sure to include the trailing space.
EMAIL_SUBJECT_PREFIX = '[Django] ' # Whether to append trailing slashes to URLs.
APPEND_SLASH = True # Whether to prepend the "www." subdomain to URLs that don't have it.
PREPEND_WWW = False # Override the server-derived value of SCRIPT_NAME
FORCE_SCRIPT_NAME = None # List of compiled regular expression objects representing User-Agent strings
# that are not allowed to visit any page, systemwide. Use this for bad
# robots/crawlers. Here are a few examples:
# import re
# DISALLOWED_USER_AGENTS = [
# re.compile(r'^NaverBot.*'),
# re.compile(r'^EmailSiphon.*'),
# re.compile(r'^SiteSucker.*'),
# re.compile(r'^sohu-search'),
# ]
DISALLOWED_USER_AGENTS = [] ABSOLUTE_URL_OVERRIDES = {} # List of compiled regular expression objects representing URLs that need not
# be reported by BrokenLinkEmailsMiddleware. Here are a few examples:
# import re
# IGNORABLE_404_URLS = [
# re.compile(r'^/apple-touch-icon.*\.png$'),
# re.compile(r'^/favicon.ico$'),
# re.compile(r'^/robots.txt$'),
# re.compile(r'^/phpmyadmin/'),
# re.compile(r'\.(cgi|php|pl)$'),
# ]
IGNORABLE_404_URLS = [] # A secret key for this particular Django installation. Used in secret-key
# hashing algorithms. Set this in your settings, or Django will complain
# loudly.
SECRET_KEY = '' # Default file storage mechanism that holds media.
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' # Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '' # Absolute path to the directory static files should be collected to.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = None # URL that handles the static files served from STATIC_ROOT.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = None # List of upload handler classes to be applied in order.
FILE_UPLOAD_HANDLERS = [
'django.core.files.uploadhandler.MemoryFileUploadHandler',
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
] # Maximum size, in bytes, of a request before it will be streamed to the
# file system instead of into memory.
FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB # Maximum size in bytes of request data (excluding file uploads) that will be
# read before a SuspiciousOperation (RequestDataTooBig) is raised.
DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB # Maximum number of GET/POST parameters that will be read before a
# SuspiciousOperation (TooManyFieldsSent) is raised.
DATA_UPLOAD_MAX_NUMBER_FIELDS = 1000 # Directory in which upload streamed files will be temporarily saved. A value of
# `None` will make Django use the operating system's default temporary directory
# (i.e. "/tmp" on *nix systems).
FILE_UPLOAD_TEMP_DIR = None # The numeric mode to set newly-uploaded files to. The value should be a mode
# you'd pass directly to os.chmod; see https://docs.python.org/3/library/os.html#files-and-directories.
FILE_UPLOAD_PERMISSIONS = None # The numeric mode to assign to newly-created directories, when uploading files.
# The value should be a mode as you'd pass to os.chmod;
# see https://docs.python.org/3/library/os.html#files-and-directories.
FILE_UPLOAD_DIRECTORY_PERMISSIONS = None # Python module path where user will place custom format definition.
# The directory where this setting is pointing should contain subdirectories
# named as the locales, containing a formats.py file
# (i.e. "myproject.locale" for myproject/locale/en/formats.py etc. use)
FORMAT_MODULE_PATH = None # Default formatting for date objects. See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'N j, Y' # Default formatting for datetime objects. See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATETIME_FORMAT = 'N j, Y, P' # Default formatting for time objects. See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
TIME_FORMAT = 'P' # Default formatting for date objects when only the year and month are relevant.
# See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
YEAR_MONTH_FORMAT = 'F Y' # Default formatting for date objects when only the month and day are relevant.
# See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
MONTH_DAY_FORMAT = 'F j' # Default short formatting for date objects. See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
SHORT_DATE_FORMAT = 'm/d/Y' # Default short formatting for datetime objects.
# See all available format strings here:
# http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
SHORT_DATETIME_FORMAT = 'm/d/Y P' # Default formats to be used when parsing dates from input boxes, in order
# See all available format string here:
# http://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
DATE_INPUT_FORMATS = [
'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
'%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
'%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
'%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
'%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
] # Default formats to be used when parsing times from input boxes, in order
# See all available format string here:
# http://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
TIME_INPUT_FORMATS = [
'%H:%M:%S', # '14:30:59'
'%H:%M:%S.%f', # '14:30:59.000200'
'%H:%M', # '14:30'
] # Default formats to be used when parsing dates and times from input boxes,
# in order
# See all available format string here:
# http://docs.python.org/library/datetime.html#strftime-behavior
# * Note that these format strings are different from the ones to display dates
DATETIME_INPUT_FORMATS = [
'%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200'
'%Y-%m-%d %H:%M', # '2006-10-25 14:30'
'%Y-%m-%d', # '2006-10-25'
'%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
'%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.000200'
'%m/%d/%Y %H:%M', # '10/25/2006 14:30'
'%m/%d/%Y', # '10/25/2006'
'%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
'%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.000200'
'%m/%d/%y %H:%M', # '10/25/06 14:30'
'%m/%d/%y', # '10/25/06'
] # First day of week, to be used on calendars
# 0 means Sunday, 1 means Monday...
FIRST_DAY_OF_WEEK = 0 # Decimal separator symbol
DECIMAL_SEPARATOR = '.' # Boolean that sets whether to add thousand separator when formatting numbers
USE_THOUSAND_SEPARATOR = False # Number of digits that will be together, when splitting them by
# THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands...
NUMBER_GROUPING = 0 # Thousand separator symbol
THOUSAND_SEPARATOR = ',' # The tablespaces to use for each model when not specified otherwise.
DEFAULT_TABLESPACE = ''
DEFAULT_INDEX_TABLESPACE = '' # Default X-Frame-Options header value
X_FRAME_OPTIONS = 'SAMEORIGIN' USE_X_FORWARDED_HOST = False
USE_X_FORWARDED_PORT = False # The Python dotted path to the WSGI application that Django's internal server
# (runserver) will use. If `None`, the return value of
# 'django.core.wsgi.get_wsgi_application' is used, thus preserving the same
# behavior as previous versions of Django. Otherwise this should point to an
# actual WSGI application object.
WSGI_APPLICATION = None # If your Django app is behind a proxy that sets a header to specify secure
# connections, AND that proxy ensures that user-submitted headers with the
# same name are ignored (so that people can't spoof it), set this value to
# a tuple of (header_name, header_value). For any requests that come in with
# that header/value, request.is_secure() will return True.
# WARNING! Only set this if you fully understand what you're doing. Otherwise,
# you may be opening yourself up to a security risk.
SECURE_PROXY_SSL_HEADER = None ##############
# MIDDLEWARE #
############## # List of middleware to use. Order is important; in the request phase, these
# middleware will be applied in the order given, and in the response
# phase the middleware will be applied in reverse order.
MIDDLEWARE = [] ############
# SESSIONS #
############ # Cache to store session data if using the cache session backend.
SESSION_CACHE_ALIAS = 'default'
# Cookie name. This can be whatever you want.
SESSION_COOKIE_NAME = 'sessionid'
# Age of cookie, in seconds (default: 2 weeks).
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2
# A string like "example.com", or None for standard domain cookie.
SESSION_COOKIE_DOMAIN = None
# Whether the session cookie should be secure (https:// only).
SESSION_COOKIE_SECURE = False
# The path of the session cookie.
SESSION_COOKIE_PATH = '/'
# Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others)
SESSION_COOKIE_HTTPONLY = True
# Whether to save the session data on every request.
SESSION_SAVE_EVERY_REQUEST = False
# Whether a user's session cookie expires when the Web browser is closed.
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
# The module to store session data
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
# Directory to store session files if using the file session module. If None,
# the backend will use a sensible default.
SESSION_FILE_PATH = None
# class to serialize session data
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer' #########
# CACHE #
######### # The cache backends to use.
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
CACHE_MIDDLEWARE_KEY_PREFIX = ''
CACHE_MIDDLEWARE_SECONDS = 600
CACHE_MIDDLEWARE_ALIAS = 'default' ##################
# AUTHENTICATION #
################## AUTH_USER_MODEL = 'auth.User' AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend'] LOGIN_URL = '/accounts/login/' LOGIN_REDIRECT_URL = '/accounts/profile/' LOGOUT_REDIRECT_URL = None # The number of days a password reset link is valid for
PASSWORD_RESET_TIMEOUT_DAYS = 3 # the first hasher in this list is the preferred algorithm. any
# password using different algorithms will be converted automatically
# upon login
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
] AUTH_PASSWORD_VALIDATORS = [] ###########
# SIGNING #
########### SIGNING_BACKEND = 'django.core.signing.TimestampSigner' ########
# CSRF #
######## # Dotted path to callable to be used as view when a request is
# rejected by the CSRF middleware.
CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure' # Settings for CSRF cookie.
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_COOKIE_AGE = 60 * 60 * 24 * 7 * 52
CSRF_COOKIE_DOMAIN = None
CSRF_COOKIE_PATH = '/'
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN'
CSRF_TRUSTED_ORIGINS = []
CSRF_USE_SESSIONS = False ############
# MESSAGES #
############ # Class to use as messages backend
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage' # Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within
# django.contrib.messages to avoid imports in this settings file. ###########
# LOGGING #
########### # The callable to use to configure logging
LOGGING_CONFIG = 'logging.config.dictConfig' # Custom logging configuration.
LOGGING = {} # Default exception reporter filter class used in case none has been
# specifically assigned to the HttpRequest instance.
DEFAULT_EXCEPTION_REPORTER_FILTER = 'django.views.debug.SafeExceptionReporterFilter' ###########
# TESTING #
########### # The name of the class to use to run the test suite
TEST_RUNNER = 'django.test.runner.DiscoverRunner' # Apps that don't need to be serialized at test database creation time
# (only apps with migrations are to start with)
TEST_NON_SERIALIZED_APPS = [] ############
# FIXTURES #
############ # The list of directories to search for fixtures
FIXTURE_DIRS = [] ###############
# STATICFILES #
############### # A list of locations of additional static files
STATICFILES_DIRS = [] # The default file storage backend used during the build process
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' # List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
] ##############
# MIGRATIONS #
############## # Migration module overrides for apps, by app label.
MIGRATION_MODULES = {} #################
# SYSTEM CHECKS #
################# # List of all issues generated by system checks that should be silenced. Light
# issues like warnings, infos or debugs will not generate a message. Silencing
# serious issues like errors and criticals does not result in hiding the
# message, but Django will not stop you from e.g. running server.
SILENCED_SYSTEM_CHECKS = [] #######################
# SECURITY MIDDLEWARE #
#######################
SECURE_BROWSER_XSS_FILTER = False
SECURE_CONTENT_TYPE_NOSNIFF = False
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
SECURE_HSTS_PRELOAD = False
SECURE_HSTS_SECONDS = 0
SECURE_REDIRECT_EXEMPT = []
SECURE_SSL_HOST = None
SECURE_SSL_REDIRECT = False

django默认环境配置

  上面步骤2和3已经罗列了session的通用配置,在setting.py中重写即可修改配置。

# Cache to store session data if using the cache session backend.
SESSION_CACHE_ALIAS = 'default'
# Cookie name. This can be whatever you want.
SESSION_COOKIE_NAME = 'sessionid'
# Age of cookie, in seconds (default: 2 weeks).
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2
# A string like "example.com", or None for standard domain cookie.
SESSION_COOKIE_DOMAIN = None
# Whether the session cookie should be secure (https:// only).
SESSION_COOKIE_SECURE = False
# The path of the session cookie.
SESSION_COOKIE_PATH = '/'
# Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others)
SESSION_COOKIE_HTTPONLY = True
# Whether to save the session data on every request.
SESSION_SAVE_EVERY_REQUEST = False
# Whether a user's session cookie expires when the Web browser is closed.
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
# The module to store session data
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
# Directory to store session files if using the file session module. If None,
# the backend will use a sensible default.
SESSION_FILE_PATH = None
# class to serialize session data
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'

 根据django.contrib.sessions.backends文件夹中的模块,session支持cache、cached_db、db(默认)、file、signed_cookies等存储方式。其它数据库配置就必须要安装相应的组件来配置。

# settings.py
# 基于缓存的会话:只存在本地内在中,如果丢失则不能找回,比数据库的方式读写更快
SESSION_ENGINE='django.contrib.sessions.backends.cache'
# 可以将缓存和数据库同时使用:优先从本地缓存中获取,如果没有则从数据库中获取
SESSION_ENGINE='django.contrib.sessions.backends.cached_db'
#
SESSION_ENGINE='django.contrib.sessions.backends.file'
# 基于使用redis数据库
# 需要pip install django-redis-sessions并且启动redis-server
SESSION_ENGINE = 'redis_sessions.session'
SESSION_REDIS_HOST = 'localhost'
SESSION_REDIS_PORT = 6379
SESSION_REDIS_DB = 0
SESSION_REDIS_PASSWORD = ''
SESSION_REDIS_PREFIX = 'session' """
启动:sudo redis-server /etc/redis/redis.conf
停止:sudo redis-server stop
重启:sudo redis-server restart
redis-cli:使用客户端连接服务器
keys *:查看所有的键
get name:获取指定键的值
del name:删除指定名称的键
"""

django(五):cookie和session的更多相关文章

  1. Django之Cookie、Session、CSRF、Admin

    Django之Cookie.Session.CSRF.Admin   Cookie 1.获取Cookie: 1 2 3 4 5 6 request.COOKIES['key'] request.get ...

  2. [py][mx]django的cookie和session操作-7天免登录

    浏览器同源策略(same-origin policy) csrf攻击防御核心点总结 django的cookie和session操作-7天免登录 flask操作cookie&django的see ...

  3. Django基础cookie和session

    Django基础cookie和session 1.会话跟踪 ​ 什么是会话!可以把会话理解为客户端与服务器之间的一次会晤,在一次会晤中可能会包含多次请求和响应.例如给10086打个电话,你就是客户端, ...

  4. Django之cookie 与session组件

    一.会话跟踪技术 1.1 什么是会话跟踪 我们需要先了解一下什么是会话!可以把会话理解为客户端与服务器之间的一次会晤,在一次会晤中可能会包含多次请求和响应.例如你给10086打个电话,你就是客户端,而 ...

  5. django的cookie和session以及内置信号、缓存

    cookie和session cookie和session的作用: cookie和session都记录了客户端的某种状态,用来跟踪用户访问网站的整个回话.两者最大的区别是cookie的信息是存放在浏览 ...

  6. django的cookie 和session

    Cookie 1.获取cookie: request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, salt=' ...

  7. Django组件-cookie与session

    一.会话跟踪技术 1.什么是会话跟踪技术 我们需要先了解一下什么是会话!可以把会话理解为客户端与服务器之间的一次会晤,在一次会晤中可能会包含多次请求和响应.例如你给10086打个电话,你就是客户端,而 ...

  8. web框架开发-Django组件cookie与session

    http协议的每一次都是无保存状态的请求,这会带来很多的不方便,比如,一刷新网页,或者进入该网页的其他页面,无法保存之前的登录状态.为了解决类似这样的问题,引入了会话跟踪 会话跟踪技术 1 什么是会话 ...

  9. Django 之 cookie和session

    一. Cookie 1.Cookie的由来 因为HTTP协议是无状态的,无状态的意思就是每次请求都是独立的,它的执行情况和结果与前面的请求和之后的请求都无直接关系,也不会受前后请求响应情况直接影响.简 ...

  10. django之COOKIE 与 SESSION

    COOKIE 与 SESSION 概念 cookie不属于http协议范围,由于http协议无法保持状态,但实际情况,我们却又需要“保持状态”,因此cookie就是在这样一个场景下诞生. cookie ...

随机推荐

  1. stacking

    向大佬学习:https://zhuanlan.zhihu.com/p/32896968 https://blog.csdn.net/wstcjf/article/details/77989963 这个 ...

  2. HDU 1024 最大M字段和

    一道关于求最大M字段和的问题,翻译完题之后感觉很简单但就是写不来,后来仿佛推到一个dp式子了,对,仿佛...然后抄袭了个式子,嘿,和我的式子大体相似,然后就是很玄学的优化了...不多瞎bb了 1.首先 ...

  3. Flask从入门到精通之自定义错误界面

    如果你在浏览器的地址栏中输入了不可用的路由,那么会显示一个状态码为404 的错误页面.现在这个错误页面太简陋.平庸,而且样式和使用了Bootstrap 的页面不一致. 像常规路由一样,Flask 允许 ...

  4. Pyplot绘图的格式

    字符 颜色 ‘b’ 蓝色,blue ‘g’ 绿色,green ‘r’ 红色,red ‘c’ 青色,cyan ‘m’ 品红,magenta ‘y’ 黄色,yellow ‘k’ 黑色,black ‘w’ ...

  5. ES6字符串相关扩展

    变量的解构赋值 // 数组的解构赋值 let [a,b,c] = [1,2,3]; //1,2,3 let [a,b,c] = [,123,]; //undefined 123 undefined l ...

  6. SecurityManager入门

    java安全管理器SecurityManager入门 SecurityManager 每个Java应用都可以有自己的安全管理器,它是防范恶意攻击的主要安全卫士. 安全管理器通过执行运行阶段检查和访问授 ...

  7. jmeter 中使用ServerAgen链接超时可能出错的原因之一ip不对

    因为我要压测的服务器是需要使用跳板机转发链接的,所以我开始用的是跳板机的IP+ServerAgen端口,发现连不通,实际上应该使用ServerAgen所在服务器的IP,如果:

  8. Spark安装过程

    Precondition:jdk.Scala安装,/etc/profile文件部分内容如下: JAVA_HOME=/home/Spark/husor/jdk CLASSPATH=.:$JAVA_HOM ...

  9. Java之IO(五)文件系统

    转载请注明源出处:http://www.cnblogs.com/lighten/p/6992043.html 1.前言 在讲解Java的文件流之前,先来认识一下Java的文件系统的实现.值得一提的是, ...

  10. redis配置详细解析

    # redis 配置文件示例 # 当你需要为某个配置项指定内存大小的时候,必须要带上单位, # 通常的格式就是 1k 5gb 4m 等: # # 1k => 1000 bytes # 1kb = ...