Djiango: The first lecture on Djiango's introductory knowledge

Insert picture description here

(According to the content of teacher cheney's live lecture)

1. Virtual environment

1 Why do we need a virtual environment

  • So far, all of our third-party package installations have been installed directly through pip install xx, so that the installation will install that package into your system-level Python environment. But there is a problem with this, that is, if you write a website with Django 1.10.x now, and your leader tells you that there was an old project developed with Django 0.9 and let you maintain it, but Django 1.10 no longer Compatible with some syntax of Django 0.9. At this time, there will be a problem. How can I have both Django 1.10 and Django 0.9 environments on my computer? At this time, we can solve this problem through the virtual environment.
  • Commonly used virtual environment creation methods are: virtualenv, virtualenvwrapper and pipenv
  • Recommend pipenv

2、pipenv

Two, Django framework introduction

  • Django also follows the MVC idea, but has its own noun called MVT

1. Why use a framework?

  • In order to better explain this problem, we compare the process of developing an application. Often developing an application (web application, system application) is the same as the process of building a house. You need to lay the foundation, build the skeleton, and then build a brick by brick. Stack it up.

  • What about developing an application? It also requires a good architecture design, database modeling, and then a module by module using code implementation.
    Insert picture description here

  • If you develop a software application without using a frame, it is essentially the same as when we build a house, every brick and every steel bar needs to be produced by ourselves.

  • Obviously, if we need to produce every brick and every kind of building material before building a house, the efficiency of building a house is extremely low, and it may not even be possible to build a house for a lifetime.

  • When developing an application system, using the framework can bring the following benefits:

    • Greatly improve development efficiency
    • Make application development more standardized and expandable
    • Let programmers focus more on the realization of business logic, instead of repetitive and complex basic environment (such as web server, low-level implementation, etc.)

2. Why use Django and Flask framework?

  • In the world of Python programming language, there are two most powerful and popular frameworks.
  • These two frameworks are widely used not only in web back-end development and microservice development, but also in ERP system development and API interface development.

3. The difference between Django and Flask

3.1 Image analogy

Insert picture description here

  • If Django is similar to a well-decorated house, with its own luxurious furniture, a very complete set of powerful household appliances, and everything, you can move in with a bag, which is very convenient.
    Insert picture description here
  • Flask is similar to a rough house. You want to decorate the house by looking for materials and buying furniture to install it yourself. The materials and furniture are very rich in variety, and they are all ready-made for free, just take them and use them.

3.2 The difference in volume

  • Flask:
    • Small and flexible, allowing programmers to decide which functions to customize, which is very suitable for small websites.
    • It is still very troublesome for ordinary workers to decorate a rough house into an urban complex, and it is the same to develop a large-scale website with Flask. The development is more difficult, the code structure needs to be designed by yourself, and the development cost depends on the developer's ability and experience .
  • Django:
    • Large and complete, extremely powerful, it is the pioneer of the Python web framework, with many users and extremely rich third-party libraries.
    • It is very suitable for the development of enterprise-level websites, but for small microservices, there is always a feeling of "killing a chicken". It is large and very bloated. The degree of customization is not as high as Flask, and it is not as flexible as Flask. .

3.3 Complete the same Hello World function

  • Use Flask to complete:
    • The first step is to install Flask, pip install flask

    • The second step is to create the my_first_app.py file and add the following code
      Insert picture description here

    • To complete the simplest Hello World function, Flask only requires 7 lines of code, which is very simple and convenient.

  • Use Django to complete:
    • The first step is to install Django, pip install django

    • The second step is to create a project directory, django-admin startproject myproject

    • The third step is to create a sub-application, python manage.py startapp myapp

    • The fourth step is to add the following code to the views.py file in the directory where the myapp application is located
      Insert picture description here

    • The fifth step is to create a urls.py routing file in the directory where the myapp application is located, and add the following code
      Insert picture description here

    • The sixth step is to add a route to the main route file.

  • From the above operation steps, it can be seen that to achieve the same function, Flask is often simpler with less code, while Django involves more processes, and the project structure is clear, which has advantages in large-scale projects.

2.4 How to choose these two frameworks in actual work?

  • If you want to understand the principle and implementation process of Python web development WSGI protocol, or you want to flexibly customize components, completely DIY your application, and want to implement microservices, then I suggest you choose Flask.
  • If you are concerned about the final delivery of the product and want to quickly develop a large application system (such as news websites, shopping malls, ERP, etc.), then it is recommended that you choose Django, which has all the functions you want, as well as the unexpected functions.
  • In short: Djiango framework is recommended for large projects, flask framework is recommended for small projects

Three, Django development principles

  • Rapid development and DRY principle. Do not repeat yourself. Do not repeat yourself.
  • Official website manual introduction

Django's official website: https://www.djangoproject.com/
Django Book2.0 version of the Chinese document: http://djangobook.py3k.cn/2.0/chapter01/

Four, Django project creation

  • First, install Django in a virtual environment
    • pip install django==2.2 -i https://pypi.tuna.tsinghua.edu.cn/simple

1. Use pycharm (not recommended)

If pycharm is a professional version, you can use pycharm to create a Django project
Insert picture description here

2. Use the command line

  • Create a project: open the terminal, use the command: django-admin startproject [project name]
  • Hiyo: django-admin startproject django_demo
    Insert picture description here
  • The command is executed successfully without any prompt, but the project-related files are automatically createdInsert picture description here

3. Run the Django project

  • manage.py: project startup file (flask needs to be handwritten by yourself, Django automatically generated), also known as the entry file, is a file that interacts with the project

3.1 Via the command line: python manage.py runserver

Insert picture description here
Insert picture description here

3.2 Start the service according to the specified port: python manage.py runserver port

Insert picture description here
Insert picture description here

3.3 Start the service according to the specified port: python manage.py runserver port

Insert picture description here
Insert picture description here

3.4 Database migration: python manage.py migrate

  • Although the system starts normally, there is an error message:
    Insert picture description here

3.4.1 After executing the database migration, no error will be reported when restarting

Insert picture description here

3.4.2 Why can the migration succeed without configuring mysql or other databases?

  • When Django creates the project, the sqlite3 database is configured by default, and the database is migrated to sqlite3 when the database is migrated. Therefore, the migration can be successful without starting the database and configuring the database.

    Insert picture description here

3.5 Start the project in the pycharm editor

  • In the development process, the command line is used to start the project, which is not convenient for debugging and the operation is very cumbersome

3.5.1 To start the project in pycharm, you need to configure the parameters parameter:

Insert picture description here

  • Run manage.py again

3.5.2 Start the project in pycharm, do not configure the parameters parameter, the operation is as follows

Insert picture description here

  • Can't open in browser
  • Related information is the help document of manage.py: python manage.py help

4. Automatically create the main file description of the project

Insert picture description here

4.1 the init .py: Project initialization file

  • The file is empty, add as needed

4.2 settings.py: configuration file

  • The system automatically generates many configuration items

4.3 urls.py: routing configuration file

  • The system automatically generates a route: manage the background route
from django.contrib import admin
from django.urls import path

urlpatterns = [
   path('admin/', admin.site.urls),
]

4.4 wigi.py: used when deploying

  • The system automatically creates some content

Five, Django app

  • The app here is not the same concept as the app in the mobile phone

1. Why create an app

  • Django app is to separate different function codes and divide them into folders to manage
  • Good management
  • Collaborative development is more convenient
  • Good maintenance

2. Create app: python manage.py startapp [app name]

2.1 Such as creating a book function app

  • Execute the following command on the command line: python manage.py app book
    -After the creation is successful, there is no prompt
    Insert picture description here
  • But the system automatically generates a book folder, and automatically creates the relevant files needed for the project

2.2 Files in the app

Insert picture description here in **Bold Style**

2.2.1 the init .py: Contents is a Python module

2.2.1 admin.py: related to website background management

2.2.1 apps.py: related to website background management

  • The system automatically creates content and declares the book app
from django.apps import AppConfig
class BookConfig(AppConfig):
    name = 'book'

2.2.2 models.py: write database-related content, models, for database migration

  • The system automatically creates a reference
from django.db import models
# Create your models here.

2.2.1 tests.py: a file for writing test code (cases) (don’t care about it for the time being)

2.2.3 views.py: receive requests, process data and interact with M and T (code logic)

2.3 Application registration

  • To establish the connection between the application and the project, the application needs to be registered.
  • Modify the INSTALLED_APPS configuration item in settings.py.

Six, the first experience of Django

1. Show hello world on the project homepage

  • Define an index function in urls.py to return hello world
  • Add reference to urlpatterns in urls.py
# ./django_demo/urls.py 
from django.contrib import admin
from django.urls import path
from django.http import HttpResponse

def index(request):
    # name=reuqest.GET.get("name")
    return HttpResponse("hello world")

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
]

Insert picture description here

Insert picture description here

2. The above code must pay attention to the specifications

2.1 The routing function must take the request parameter

  • Namely def function name (request), otherwise it will report a bunch of errors

2.2 The return value of the routing function must be the HttpResponseBase class or its subclass

  • Otherwise, the return value data type is wrong

3. Error messages are easy to report at the beginning of the project:

3.1 "UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xa6 in position 9737: illegal multibyte sequence "

Insert picture description here

  • Cause Analysis:
    • This is a coding problem of debug.py in Django2.2, the code is not wrong, it will not appear
  • Solution path:
    • Click on debug.py above,
      Insert picture description here
  • change into
    Insert picture description here

3.2 The following error message is displayed on the page:

Insert picture description here

  • Cause Analysis:
    • This is because the routing function is missing the request Insert picture description here
    • Solution path: def index(request) is fine
      Insert picture description here

3.3 The following error message is prompted on the page:

Insert picture description here

  • Cause Analysis:

    • This is the return value of the routing function does not use HttpRespense("Return String")
      Insert picture description here
    • Solution path: return HttpResponse("hello world")
      Insert picture description here

4. Display "Book Homepage" on the homepage of the book app

  • Define the book function in book/view.py and return to "Book Homepage"
  • Add reference to urlpatterns in urls.py
# ./book/view.py 
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def book(request):
    return HttpResponse("图书首页")
from django.contrib import admin
from django.urls import path
from django.http import HttpResponse
from lesson01.django_demo.book import views

def index(request):
    # name=reuqest.GET.get("name")
    return HttpResponse("hello world")

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
    path('book/', views.book),
]

Insert picture description here

The above content also refers to the following article:
Blog Garden Keyou "Really understand the difference between Django and Flask framework in Python"

Guess you like

Origin blog.csdn.net/laoluobo76/article/details/111333748