Some knowledge points in Django

Posted by The Bat on Sat, 01 Jan 2022 01:58:18 +0100

preface

django and vue are used

Tip: the following is the main content of this article. The following cases can be used for reference

1, setting configuration after installation

Static resource allocation

templates configuration

static (note the last comma, the data type is tuple)

STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), )

OK, that's the basic configuration

2, About ORM

Table migration

Generate table structure

python manage.py makemigrations  app01  

transfer

python manage.py migrate  app01

Creation of ORM model class

basic

Object (database field)

  • Self growth:
    • AutoField (generally used as id, which does not need to be added by the user)
    • If it's not enough, use BigAutoField
  • int type:
    • IntegerField
    • BigIntegerField
  • Binary field:
    • :BinaryField
  • Boolean type:
    • :BooleanField
    • Nullboolean field cannot be null
  • Shaping:
    • Five byte positive number: PositiveSmallIntegerField
    • Positive and negative number of six bytes: SmallIntegerField
    • Positive number of ten bytes: PositiveIntegerField
    • Ten bytes: IntegerField
    • Twenty bytes: BigIntegerField
  • String type:
    • Maximum string length to be specified: CharField
    • No need to specify (any length): TextField
  • Time type:
    • Date: DateField
    • Year month day hour minute second: DateTimeField
    • Period of time: DurationField
  • Floating point number:
    • Do not specify decimal places: FloatField
    • Need to specify: DecimalField
  • Email:
    • EmailField
  • picture
    • ImageField
  • One to many foreign keys
    • The class name of the attached table to be written in the parameter: ForeignKey
    • Must add on_delelte parameter
  • Many to many
    • The class name of the attached table to be written in the parameter: ManyToManyField

Wait

Parameters (field types and foreign keys)

  • All fields are available
    • 1. Change field name: db_colum=” “
    • 2. Set primary key: primary_key=True, False by default
    • 3. Set an alias for the field (note): verbose_name = "“
    • 4. Unique key attribute of the field: unique=True. After setting, each value of no record in this field is unique
    • 5. Allow fields to be empty: null=True (fields in the database can be empty), blank=True (web page form submission content can be empty). Remember not to set null to Fasle and set blank to True. An error will be reported.
    • 6. Index fields: db_index=True
    • 7. Display instructions in the form: help_text=” “
    • 8. The field value cannot be changed: editable=False, the default is True, and can be changed.
  • Time and string type
    • CharField type
      • Set the length of the string: max_length
    • DateField type
      • unique_for_date=True: the time of this field must be unique
      • auto_now=True: the time when the content of this record is updated
      • auto_now_add=True: the time when this record was inserted
      • max_digits=6, decimal_places=2: the former represents the total number of integers and decimals, and the latter represents the number of decimal places
  • Relational field
    • Set the foreign key management field (this field is added to the attached table, and the primary table field is specified by the primary table) primary_key = "cat_id"

3, django scheduled tasks implemented by celery+redis

Partial start command

redis startup

redis-server.exe redis.windows.conf

celery start worker

celery -A Orm_Mysql worker -l info   # Orm_Mysql is the project name

celery start beat

celery -A Orm_Mysql beat -l info

File configuration

Dependent package version

python 3.6
celery==5.0.5
django==3.1.4
django-celery-beat==2.2.0
redis==4.1.0

File directory

setting configuration

# Configuring celery
CELERY_BROKER_URL = 'redis://Localhost: 6379 / 0 '# broker configuration, using Redis as message middleware
CELERY_RESULT_BACKEND = 'redis://Localhost: 6379 / 0 '# backend configuration. redis is used here
CELERY_RESULT_SERIALIZER = 'json' # Result serialization scheme

celery configuration file (setting sibling directory)

# Import the updated content from the next version into the current version
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from datetime import timedelta
from celery.schedules import crontab

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Orm_Mysql.settings')  # Setting up django environment Orm_Mysql is the project name

app = Celery('Orm_Mysql') #And here

app.config_from_object('django.conf:settings', namespace='CELERY')  # Using CELERY_ As a prefix, write the configuration in settings

app.autodiscover_tasks()  # Find the task.under each app in the task file py

# Declare scheduled tasks
app.conf.beat_schedule = {
    u'app01_tasks_add': {		# Task name, which can be customized
        "task": "app01.tasks.add",	# Task function
        "schedule": timedelta(seconds=10),	# Timed every 10 seconds
        # "args": (1, 3),		# Pass undefined indefinite length parameter
        # 'kwargs': ({'name':'Zhang San'}),	# Pass defined indefinite length parameter
    },
    u'app01_tasks_mcn_name': {
        "task": "app01.tasks.mcn_name",
        "schedule": timedelta(seconds=15),		# Timed every 15 seconds
        # "args": (),
        # 'kwargs': (),
    },
    u'app01_tasks_mcn_gov': {
            "task": "app01.tasks.mcn_gov",
            "schedule": timedelta(seconds=20),		# Timed every 20 seconds
            # "args": (),
            # 'kwargs': (),
        },
}

project >init. Py (init file in the home directory)

# Import the updated content from the next version into the current version
from __future__ import absolute_import, unicode_literals
from .config_celery import app as celery_app
__all__ = ['celery_app']


# The next two lines are for configuring pymysql
import pymysql
pymysql.install_as_MySQLdb()

Add tasks to the created app Py file

from __future__ import absolute_import, unicode_literals
from celery import shared_task
import redis
rc = redis.Redis('127.0.0.1', 6379)  # The host address can also try localhost
import json
import time

from django.shortcuts import HttpResponse

@shared_task
def add():
	print("15 Second execution")

@shared_task
def mcn_name():
    print("20 Second execution")

def mcn_gov():
    print('25 Second execution')
 

Topics: Python Django Back-end