Djang project building foundation 2

1. Class view (mastery)
  • Function: Use classes to provide view functions

  • benefit:

    • 1. Better readability
    • 2. Provide code reusability
  • manual:

    • 1. Define the class view in the views of the sub-application

      #1,编写类视图处理业务
      class RegisterView(View):
      
          def get(self,request):
      
              print(request.GET)
      
              return HttpResponse("RegisterView get")
      
      
          def post(self,request):
      
              print(request.GET)
              print(request.body)
      
              return HttpResponse("RegisterView post")
      
      
    • 2. Define the path (routing) in the urls file of the sub-application

      from django.conf.urls import url
      from . import views
      
      
      urlpatterns = [
      
          #1,编写类视图处理业务,
          url(r"^register/$",views.RegisterView.as_view())
      ]
      
    • 3. Set the urls file of the sub-application to the root application

      url(r'^', include('booktest.urls'))
      
2. Class view principle (understanding)

Xnip2019-03-07_09-48-35

3. Add a decorator to the class view (understand)
  • Function: Add additional functions to existing class views

  • There are two processes of decoration:

    • method one:

      • 1. Define the decorator

      • 2. Use decorators in the url path to decorate

        views.py
        # 定义装饰器
        def user_login_data(view_func):
            def wrapper(request,*args,**kwargs):
        
                #可以实现用户数据的封装
                print(request.method)
        
                return view_func(request,*args,**kwargs)
        
            return wrapper
        
        urls.py
        #2,给类视图增加装饰器,给RegisterView2返回的view装饰即可
        url(r"^register2/$",views.user_login_data(views.RegisterView2.as_view())),
        
    • Method two:

      • 1. Define the decorator

      • 2. Decorate using the method_decorator decorator method provided by the system

        # 定义装饰器
        def user_login_data(view_func):
            def wrapper(request,*args,**kwargs):
        
                #可以实现用户数据的封装
                print(request.method)
        
                return view_func(request,*args,**kwargs)
        
            return wrapper
        
        #3,给类视图增加装饰器,方式二,使用系统提供的method_decrator方法
        # @method_decorator(user_login_data,name="get")
        # @method_decorator(user_login_data,name="post")
        @method_decorator(user_login_data,name="dispatch") #该类视图中的所有请求方法都会装上
        class RegisterView3(View):
        
            # @method_decorator(user_login_data)
            def get(self,request):
        
                print("RegisterView3 get")
        
                return HttpResponse("RegisterView3 get")
        
            # @method_decorator(user_login_data)
            def post(self,request):
        
                print("RegisterView2 post")
        
                return HttpResponse("RegisterView3 post")
        
4. Middleware (understanding)
  • Function: Similar to the request hook in flask, perform corresponding processing before and after the request, such as: database link, parameter verification, unified data format return

    • 1, create file

    • 2. Write the middleware function (decorator) in the file

    • 3. Register the decorator into the middleware of settings.py

      middleware.py文件
      def my_middleware(view_func):
      
          print("1, init")
      
          def wrapper(request):
      
              print("1, before_request")
      
              #在这里就可以取校验参数
      
              response = view_func(request)
      
              print("1, after_request")
      
              return response
      
          return wrapper
      
      
      #中间件(settings.py)
      MIDDLEWARE = [
          ...
          'booktest.middleware.my_middleware',
          'booktest.middleware.my_middleware2',
          'booktest.middleware.my_middleware3',
      ]
      
      

      Xnip2019-03-07_10-50-01

5. Template (understand)
  • Function: used to render data

  • manual:

    • 1. Use the loader object to obtain the template

    • 2. Use templates to render pages

    • 3. Return the response and carry the template page

      #4,使用模板渲染数据
      class TempView(View):
      
          def get(self,request):
      
      
              #一, 完整写法:
              """
              # - 1, 使用loader对象,获取模板
              template = loader.get_template("file01.html")
      
              # - 2,使用模板渲染页面
              file_data =  template.render()
      
              # - 3,返回响应,携带模板页面
              return HttpResponse(file_data)
              """
      
              #二,简化写法
              return render(request,"file01.html")
      
      
    • Note that you need to set the template folder path settings.py

      'DIRS': [os.path.join(BASE_DIR,"templates")],
      
6. Database configuration (mastery)
  • Function: Allow django program to operate the database

  • Configuration content

    #数据库配置
    DATABASES = {
          
          
        'default': {
          
          
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'python10',
            'USER': 'root',
            'PASSWORD': '123456',
            'HOST': '127.0.0.1',
            'PORT': '3306',
        }
    }
    
    
  • Note: You need to create the database yourself in the terminal

7. Book model class (understanding)
8. Hero model class (understanding)
9. Database migration, adding test data (master)
  • Create process
    • 1. Define the model class file in the models of the sub-application
    • 2. The sub-application needs to be registered in install_apps of settings.
    • 3, and then migrate
  • Tips for a successful migration
    • 1. Ensure that the version of django in the virtual environment is 1.11.11
      • Note: The default version of ubuntu is 1.8.7
      • Solution: pip install django==1.11.11 will overwrite 1.8.7
    • 2. After defining the model class, you need to register the model class in the settings file.
      • image-20190307160605671
    • 3. Ensure that the database driver used is pymysql
      • image-20190307160659333
    • 4. Execute the migration command
10. View database log information (understand)
  • 1. Enter the terminal

​ python manage shell

  • 2. Modify the database log information record file

    sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf
    放开68,69行
    
    
    
    
  • 3. Monitor the operation of logs

    • tail -f /var/log/mysql/mysql.log
      如果不能监控,加上sudo
      如果还监控不了,重启数据库 sudo service mysql restart
      
      
11. Add data (master)
12.Basic query (master)
13, FQ object query (understanding)
14. Related query (understanding)
15. Database modification, deletion (mastery)
16, laziness, caching, restriction (understanding)

Guess you like

Origin blog.csdn.net/weixin_44774466/article/details/88555042