Complicated by
'' ' 1.CDN: some third-party static files directly access someone else's server 2. sprite: a plurality of panels together into a large map by UI staff, reducing the number of requests image resource 3. Database: You can cache data , there is only redis, some data must only be stored in the hard disk in MySql, if a cache, you can also make use of redis hard disk data cache memory 4. own database optimization: sql optimization | index | sub-library sub-table | read write separation 5. caching: data can be cached files can be cached, the page can be cached, and even the entire project can be cached 6. architecture: cluster deployment: nginx can complete static and dynamic separation (static resource request specialized storage server static files) load equilibrium (s requests are assigned to a plurality of transverse deployment server) distributed asynchronous queue: clery distributed asynchronous frame, a request for processing a plurality of steps the overall management queue '' '
Cache
'' ' Cache can be stored in: file, database, memory, we have developed is usually stored in memory cache database memory database: redis and memcache ' ''
Django cache configuration
= CACHES { ' default ' : { # specified engine used by the cache ' BACKEND ' : ' django.core.cache.backends.locmem.LocMemCache ' , # unique value is written in the memory variables ' LOCATION ' : ' UNIQUE-Snowflake ' , # cache timeout (default is 300 seconds, None indicates never expires) ' tIMEOUT ' : 300 , ' the OPTIONS ' : { # maximum number of cache entries (default 300) ' MAX_ENTRIES ' : 300, # After reaching the maximum number of the cache, the cache remove number ratio, i.e.: 1 / CULL_FREQUENCY (default. 3) ' CULL_FREQUENCY ' :. 3 , } } }
# Partial page "" " by the Django rendered page {% Load Cache%} {% Cache 10 'name'%} <P> to be cached locally SUMMARY </ P> {% endCache%} " "" # a single page from django.views.decorators.cache Import cache_page @cache_page ( 10) # page representing the view is rendered cache function 10s DEF test_cache (Request): Import Time c_time = the time.time () return the render (Request, ' cache.html ' , about locals ()) # the station cache MIDDLEWARE = [ #HttpResponse response provided several headers (must be placed on top) ' django.middleware.cache.UpdateCacheMiddleware ' , # ... # used to cache obtained by GET HEAD method and the response status code of 200 (must be placed in the most below) ' django.middleware.cache.FetchFromCacheMiddleware ' , ] # cache time seconds CACHE_MIDDLEWARE_SECONDS = 10
Redis caching Token
# uitls.py import uuid def get_token(): return uuid.uuid4().hex # views.User.py class TestToken(ModelViewSet): authentication_classes = [auth.LoginAuthenticate] def get(self, request, *args, **kwargs): api_response = ApiResponse() api_response.message = '认证通过' return Response(api_response.api_dic) from django.core.cache import cache class UserView(ModelViewSet): defthe Login (Self, Request, * args, ** kwargs): api_response = ApiResponse () the User = models.User.objects.filter (** request.data) .first () IF the User: # login is successful operations token token = get_token () # cache cache module object is the object, the cache engine is used redis, # that can be used as cache operation redis redis database objects directly, but also the corresponding value cache fetch Object = { ' User ' : User, ' token ' : token } Import the pickle token_object = pickle.dumps(object) cache.set(token, token_object, 100) user_data = objectjson.UserJson(user).data api_response.message = 'login success' api_response.token = token api_response.results = user_data return Response(api_response.api_dic) api_response.status = 1 api_response.message = 'login failed' return Response(api_response.api_dic) # urls.py urlpatterns = [ url(r'^login/', views.UserView.as_view({'post': 'login'})), url(r'^token/', views.TestToken.as_view({'get': 'get'})), ]
Login authentication certification class
from django.core.cache Import Cache class LoginAuthenticate (BaseAuthentication): DEF the authenticate (Self, Request): token = request.META.get ( ' HTTP_TOKEN ' ) token_data = cache.get (token) # take redis database cache token IF not token_data: the raise AuthenticationFailed ( ' authentication failure ' ) # token has not expired, the pickle after deserialization using the serialized data Import pickle token_object = the pickle.loads (token_data) User= token_object['use
After the front end transmission request login
vue components
<-! VIP.vue -> < Template > < div class = "vip" > < h2 > VIP function, DC </ h2 > < the p- @click = "atcion" > function after logging operations </ the p- > < P > {{MSG}} </ P > </ div > </ Template > < Script > Export default { name: " the VIP ", data: function () { return { msg: '' } }, methods: { atcion: function () { let token = this.$cookie.get('token'); // window.alert(token); if (token) { // window.alert("登录后的请求") let _this = this; this.$ajax({ method: 'get', url: this.$base_api + 'token/', headers: { TOKEN: token } }).then(function (response) { _this.msg = response.data }) } else { window.alert("先登录") } } } } </script> <style scoped> </style>
Background CORS Middleware
from corsheaders.middleware Import CorsMiddleware # the intermediate file package defaults.py default_headers accede 'token' field