django 프레임워크 기초-장기 유지보수-20191212

33629 단어
django 프레임워크 기초:
 
##############django 프레임의 학습 방법 ######################
12,        ,        ,
34,       

 
############## MVC 아키텍처 소개 ###################
# MVC  
#
#
# django    MVC     
# MVC     :  。            ,
# MVC    :  ,                       ,              ,         
# M:model,  ,        
# V:view,  ,  html  
# C:controller,   ,    ,    ,
######################################
#     ,MVC        
#    ,       ,       
# C:   ,    ,    , M V    
# C              ,   M             ,  M         C,
#         ,C        ,    V  HTML  ,  V  html    C,
#   C,    html        

 
###############django 프레임워크-MVT ######################
# django  
# django python      MVC     ,           ,  MVT,         MVC        
# M:model,  , MVC  M    ,        ,
# V:view,  , MVC  C    ,    ,    , M T    ,      ,
# T:templates,  , MVC  V    ,    HTML  ,
#
#    ,    ,        
#   django  C ,       ,           ,
#   M         ,       V,
#       V  html   ,   T     HTML   ,       V,
#   V      ,      ,
####################
# django        :https://yiyibooks.cn/xx/Django_1.11.6/index.html

 
##############django 설치, 프로젝트 만들기, app 만들기 구성, 프로젝트 시작 #####################
#      Django:
#   pycharm Terminal ,    cmd ,
pip install django==1.11.11 -i https://pypi.tuna.tsinghua.edu.cn/simple
Django - admin  #         Django - admin,            
python -m django --version  #     ,      Django  

#      Django  :
#    :    pycharm  ,         django,
#    :    ,
#                 ,      ,    :
django-admin startproject test1 #(   )

#
manage.py  #        ,            django  
test1
    __init__.py #   test1    python  
    settings.py #      
    url.py #      
    wsgi.py  # web    django       


#
python manage.py startapp app  
#       
admin.py #               
__init__.py
migirations
    __init__.py
model.py #        
views.py  #     ,    , M T    
test.py #         
#
#  settings  INSTALLED_APPS,  app   

#     ,  cmd       ,   pytcharm  terminal 
#
python manage.py runserver
#      pycharm         ,

 
############## django-ORM 작업 #####################
---> django 프레임워크 기반 - ORM 운영 - 장기 유지 관리
##############django--admin의 사용 #######################
# django    :
#
#  settings          
LANGUAGE_CODE = 'zh-hans'  #     
TIME_ZONE = 'Asia/Shanghai'  #     
#
#
python manage.py createsuperuser
#
#      
from django.contrib import admin
from app01.models import Book,Publisher,Author
admin.site.register(Book)
admin.site.register(Publisher)
admin.site.register(Author)
#     
http://127.0.0.1:8000/admin/
#
#       ,models.py   ,  __str__    :
def __str__(self):
    #         
    return self.name
#             ,     admin,
#      admin.py    ,   
class BookAdmin(admin.ModelAdmin):
    list_display = ['title','publisher','pub_data']

 
##############django-뷰 사용 #######################
# django        ,           ,
#        
#
from django.http import HttpResponse
def index(request):
    #     , M T    ,
    return HttpResponse('    ')

#    url       :
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # url(r'^index/$',views.index)
    url(r'^',include('app01.urls'))
]

#    url     
from django.conf.urls import url,include
from app01 import views
urlpatterns = [
    url(r'^index/$',views.index)
]

 
###############python 베이스 리뷰: 인테리어 ####################
#        ,1       ,2      ,  python        ,
#        ,     ,         python,
#   Python   (Decorator)
#     Python     ,        (closure)    。
#
#                    ,           ,                ,           ,
#                    ,       ,

#
#              ,      ,                  ,       ,
#
#   :            ,
#                 ?                ,          ,
#        ,            ,         ,            ,          ,          

#
#              
#

 
다음은 장식기의 사상을 사용하여 로그인의 검사 기능을 실현한다.
 
############## django-cookie 작업 #####################
# cookie   ?
#     ,            
#   :    ,       ,                    ?
# cookie   ,
#   HTTP        ,          ,       ,             
# cookie   ?
# cookie             ,(   cookie      )
#       ,         ,           ,
#                      ,        cookie,              cookie ,
#              ,          ,

# cookie   :
# cookie         ,          ,
# 1,    , 7    
# 2,           ,
# 3,       ,
# cookie       ,                 cookie(    cookie,),
#                 cookie,
# cookie            ,

# cookie   :
#               ,              ,
#               
# cookie      ,      cookie           ,            ,
#           session ,

 
코드:
from django.shortcuts import render,redirect
from django.views.decorators.csrf import csrf_exempt, csrf_protect


def check_cookie(func):  # #            ,func              ,
    print('     ')

    def wrapper(request,*args,**kwargs):  # wrapper       ,         ,               ,              ,             ,       
        # cookie_info=request.COOKIES.get('is_login')
        cookie_info =request.get_signed_cookie('is_login',salt='SOS',default=0)  #          ,      default
        print(cookie_info)
        if cookie_info == '1':
            return func(request,*args,**kwargs)  #      ,            (       )
        else:
            return redirect('/login/')
    return wrapper


@csrf_exempt
def login(request):
    if request.method=='POST':
        user=request.POST.get('user')
        pwd=request.POST.get('pwd')
        if user=='liqian' and pwd =='123':
            ret = redirect('/home/')
            # ret.set_cookie('is_login',1)  #   
            ret.set_signed_cookie('is_login',value=1,salt='SOS',max_age=10)  #   
            return ret
    return render(request,'login.html')


#        @  
@check_cookie
def home(request):
    return render(request, 'home.html')


def logout(request):
    #     cookie
    ret = redirect('/login/')
    ret.delete_cookie('is_login')
    return ret

 
##############django-session의 작업 ######################
 
# session
# Cookie           “    ”   ,    Cookie      4096  ,  Cookie        ,        ,
#             ,         ,         ,       。   Session。
# session       ,        ,
#    cookie          ,
# K1:{is_login: 1, user: xiaohei}
# K2:{is_login: 1, user: xiaowang}
#   session,
# session    cookie ,
#         cookie,      :  :XX:k1,
#      K1  ,            ,
#
# session   ?
#             ,

# django session   ?
# qewrqerqe:{is_login: 1, user: xiaohei}
# werwewerwr:{is_login: 1, user: xiaowang}
#  session
# 1,           ,  session key
# 2,                   ,         ,   session key  cookie     ,
# 3,        cookie      ,sessionid:       session key

#  session:
# 1,      cookie         ,
# 2,        session        ,
# 3,       key  ,

# session   :
# 1, cookie     
# 2,    ,         ,
# session   ,
# 1,           session,      ,      ,       ,


#     Session Cookie     
# request.session.set_expiry(value)
# *  value    ,session        。
# *  value  datatime timedelta,session          。
# *  value 0,        session    。
# *  value None, session     session    。
#     , cookie  ,      session    
#        Session               
# request.session.clear_expired()

코드:
from django.shortcuts import render,redirect
from django.views.decorators.csrf import csrf_exempt, csrf_protect


def check_session(func):
    print('     ')
    def wrapper(request,*args,**kwargs):
        session_info=request.session.get('is_login')
        print(session_info)
        if session_info=='1':
            return func(request,*args,**kwargs)
        else:
            return redirect('/login/')
    return wrapper


@csrf_exempt
def login(request):
    if request.method=='POST':
        user=request.POST.get('user')
        pwd=request.POST.get('pwd')
        if user=='liqian' and pwd =='123':
            ret = redirect('/home/')
            request.session['is_login'] = '1'
            request.session.set_expiry(7)  # 7   ,
            # session            ,    orm,django      ,django_session, 
            #                 session,        ,    ,---
            # session         ,            ,  Redis  ,      setting   ,
            #                  ,             ,
            return ret
    return render(request,'login.html')


@check_session
def home(request):
    return render(request, 'home.html')


def logout(request):
    #     session
    request.session.flush()  #       session,  cookie    ,
    # request.session.delete() #      session,  cookie  ,      ,     ,
    return redirect('/login/')

 
############## django-캐시 페이지 ##################
###########################################
#
#               
#
#
#      ,           ,          ,   FetchFromCacheMiddleware          ,
#         ,           ,      UpdateCacheMiddleware         ,        

MIDDLEWARE = [
    'django.middleware.cache.UpdateCacheMiddleware',  #    
    #      ...
    'django.middleware.cache.FetchFromCacheMiddleware',  #    
]

CACHE_MIDDLEWARE_ALIAS = ""
CACHE_MIDDLEWARE_SECONDS = ""  #
CACHE_MIDDLEWARE_KEY_PREFIX = ""

#             ,       ,              ,

##################################

#      
#          ,            ,
#
#
from django.views.decorators.cache import cache_page
@cache_page(60 * 15)  #       ,       ,
def my_view(request):
    ...

#
from django.views.decorators.cache import cache_page
urlpatterns = [
    url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)),
]
#            ,             ,      ,        ,
#

#######################################
#
# a.   TemplateTag
# {% load cache %}
# b.     
# {% cache 5000   key %}  # 5000   5000     ,key     
#         
# {% endcache %}

#

 
 
 
###############끝선 ######################
###############끝선 ######################

좋은 웹페이지 즐겨찾기