- Delete_cookie (key): Delete the specified key cookie, and nothing happens if key does not exist
Sub-class Httpresponseredirect
- Redirect, server-side jump
- The first parameter of a constructor is used to specify the address of the redirect
在views1.py中from django.http import HttpResponse,HttpResponseRedirectdef index(request): return HttpResponseRedirect(‘js/‘)def index2(request,id): return HttpResponse(id)在应用的urls.py中增加一个url对象url(r‘^([0-9]+)/$‘, views1.index2, name=‘index2‘),
- The address bar of the request result
- Recommended use of Reverse parsing
from django.core.urlresolvers import reversedef index(request): return HttpResponseRedirect(reverse(‘booktest:index2‘, args=(1,)))
Sub-class Jsonresponse
- Returns JSON data, typically used for asynchronous requests
- _init _ (data)
- Help users create JSON-encoded responses
- Parameter data is a Dictionary object
- The default content-type for Jsonresponse is Application/json
from django.http import JsonResponsedef index2(requeset): return JsonResponse({‘list‘: ‘abc‘})
Shorthand function Render
- Render (Request, template_name[, context])
- Combines a given template and a given context dictionary, and returns a rendered HttpResponse object
- Request: This request is used to generate the response
- Template_name: The full name of the template to use
- Context: A dictionary that is added to the template context, and the view will call it before rendering the template
from django.shortcuts import renderdef index(request): return render(request, ‘booktest/index.html‘, {‘h1‘: ‘hello‘})
redirect
- Redirect (To)
- Returns httpresponseredirect for passed in parameters
- To recommend using reverse parsing
from django.shortcuts import redirectfrom django.core.urlresolvers import reversedef index(request): return redirect(reverse(‘booktest:index2‘))
Get object or return 404
- get_object_or_404 (Klass, args, *Kwargs)
- The Get () method is called through the Model manager or query set, and if no object is found, the model's doesnotexist exception is raised, but the Http404 exception is thrown
- Klass: Gets the model class, manager object, or Queryset object of the object
- **kwargs: The parameters of the query, the format should be accepted by get () and filter ()
- Multipleobjectsreturned exception is thrown if multiple objects are found
from django.shortcuts import *def detail(request, id): try: book = get_object_or_404(BookInfo, pk=id) except BookInfo.MultipleObjectsReturned: book = None return render(request, ‘booktest/detail.html‘, {‘book‘: book})将settings.py中的DEBUG改为False将请求地址输入2和100查看效果
Get a list or return 404
- get_list_or_404 (Klass, args, *Kwargs)
- Klass: Gets a model, manager, or Queryset instance of the list
- **kwargs: The parameters of the lookup, the format should be accepted by get () and filter ()
from django.shortcuts import *def index(request): # list = get_list_or_404(BookInfo, pk__lt=1) list = get_list_or_404(BookInfo, pk__lt=6) return render(request, ‘booktest/index.html‘, {‘list‘: list})将settings.py中的DEBUG改为False
Status hold
- The HTTP protocol is stateless: Each request is a new request and will not remember the state of the previous communication
- A client-to-server communication is a session
- How to implement state retention: Store data about sessions on the client or server side
- Storage methods include cookies, sessions, and session objects
- Use cookies, all data stored on the client, and be careful not to store sensitive information
- It is recommended to use the Sesison method, where all data is stored on the server side and stored in the client cookie session_id
- The purpose of the state hold is to track the requester's state over a period of time, enabling the data for the current requestor to be accessed across the page
- Note: This data is not shared between different requesters, and is corresponding to the requestor
Enable session
- Projects created by using Django-admin startproject are enabled by default
- In the settings.py file
项INSTALLED_APPS列表中添加:‘django.contrib.sessions‘,项MIDDLEWARE_CLASSES列表中添加:‘django.contrib.sessions.middleware.SessionMiddleware‘,
- Disable session: Delete The two values specified above, disabling sessions will save some performance consumption
Use session
- After the session is enabled, each HttpRequest object will have a session property, which is a class Dictionary object
- Get (Key, Default=none): Gets the value of the session based on the key
- Clear (): Clear All sessions
- Flush (): Deletes the current session data and deletes the session's cookie
- Del request.session[' member_id ': delete session
User Login Example
- Operating effects such as:
- Create a view in a views.py file
from django.shortcuts import render, redirectfrom django.core.urlresolvers import reversedef index(request): uname = request.session.get(‘uname‘) return render(request, ‘booktest/index.html‘, {‘uname‘: uname})def login(request): return render(request, ‘booktest/login.html‘)def login_handle(request): request.session[‘uname‘] = request.POST[‘uname‘] return redirect(reverse(‘main:index‘))def logout(request): # request.session[‘uname‘] = None # del request.session[‘uname‘] # request.session.clear() request.session.flush() return redirect(reverse(‘main:index‘))
主url:from django.conf.urls import include, urlurlpatterns = [ url(r‘^‘, include(‘booktest.urls‘, namespace=‘main‘))]应用url:from django.conf.urls import urlfrom . import viewsurlpatterns = [ url(r‘^$‘, views.index, name=‘index‘), url(r‘login/$‘, views.login, name=‘login‘), url(r‘login_handle/$‘, views.login_handle, name=‘login_handle‘), url(r‘logout/$‘, views.logout, name=‘logout‘)]
- Create a template index.html
<!DOCTYPE html>
- Create a template login.html
<!DOCTYPE html>
Session Expiration Time
- Set_expiry (value): Sets the timeout period for the session
- Expires after two weeks if not specified
- If value is an integer, the session expires after values seconds are inactive
- If value is a Imedelta object, the session will expire at the current time plus the specified date/time
- If value is 0, then the cookie for the user session expires when the user's browser is closed
- If value is None, then the session never expires
- Modify the Login_handle function in the view to see the effect
def login_handle(request): request.session[‘uname‘] = request.POST[‘uname‘] # request.session.set_expiry(10) # request.session.set_expiry(timedelta(days=5)) # request.session.set_expiry(0) # request.session.set_expiry(None) return redirect(reverse(‘main:index‘))
Storage session
- Using the settings.py session_engine key, you can use the storage session to specify
- Database-based sessions: This is the default Django session store, which needs to be added django.contrib.sessions to the Installed_apps settings, run manage.py migrate install the session table in the database, and display the specified
SESSION_ENGINE=‘django.contrib.sessions.backends.db‘
- Cache-based sessions: only local intrinsic, if lost, can not be recovered, faster than the database read and write
SESSION_ENGINE=‘django.contrib.sessions.backends.cache‘
- You can use both the cache and the database: take precedence from the local cache and get from the database if not
SESSION_ENGINE=‘django.contrib.sessions.backends.cached_db‘
Using the Redis cache session
- Sessions also support files, pure cookies, Memcached, Redis, and other means of storage, and the following demo uses Redis storage
- Install package
pip install django-redis-sessions
- Modify the configuration in the settings to add the following
SESSION_ENGINE = ‘redis_sessions.session‘SESSION_REDIS_HOST = ‘localhost‘SESSION_REDIS_PORT = 6379SESSION_REDIS_DB = 0SESSION_REDIS_PASSWORD = ‘‘SESSION_REDIS_PREFIX = ‘session‘
- Commands for managing Redis
启动:sudo redis-server /etc/redis/redis.conf停止:sudo redis-server stop重启:sudo redis-server restartredis-cli:使用客户端连接服务器keys *:查看所有的键get name:获取指定键的值del name:删除指定名称的键
Python django-3 View