current position:Home>Django's 35000 word blog post

Django's 35000 word blog post

2022-02-02 08:05:24 Huterox

@[TOC]

Preface

Before that , You need to master

  1. HTML
  2. CSS
  3. JS
  4. JQuery
  5. Linux
  6. SQL
  7. Redis

python part :

  1. Multithreading , Multi process , Sync , Thread pool , queue , understand GIL
  2. socket Network programming TCP,UDP,HTTP

It's best to master some : Regular expressions xpath

This final chapter is actually a review of the previous django Make a summary of the series , Then you can just read this blog directly . Currently involved django Basic operation , Model , middleware , wait , There are also some common wrong solutions .

Django Installation

Configuration of virtual environment

In the use of django It is recommended to set up the virtual environment first , The purpose of this is to make your environment cleaner . How to do , See my previous blog : Blog links This is written using virtualenv and virtualenvwapper To build a virtual environment . This effect is that you directly use pycharm It's the same , It's all about , stay Linux Next and in Windows Next . If you're directly in pycharm If so, just click the mouse . Of course, here's how to use it directly virtualenv stay window Use , This is not mentioned in my blog above .

1. Create project files 2. Use instruction virtualenv env Creating a virtual environment ( The file name is env) 3. find Script Catalog 4. Execute startup script ( Start the shutdown script on shutdown )  Insert picture description here

 Insert picture description here

 Insert picture description here Then in your IDE Just specify the virtual environment inside . Direct use pycharm It will be more friendly .

establish Django project

Django Directory structure of the project

 Insert picture description here The relationship between them is as follows :  Insert picture description here

 Create project 
django-admin startproject projectname
 Create an 
django-admin startapp appname
 Copy code 

After creation, register the application ,pycharm May create django The project will not help you create an application project by default, so you have to create it yourself on the console , Besides ,pycharm By default, it helps you create a virtual environment .  Insert picture description here

Project file diagram

First, let's take a look at the routing file , This file is responsible for processing the request path .  Insert picture description here When the route comes , perform views Function of . Pay attention to my time here APP Next function , The function is in views Next  Insert picture description here Template file We read HTML The file is placed in our template file .  Insert picture description here

Later on models file , This is the part responsible for our processing of the database .  Insert picture description here

Multiple routing

When our logic processing is complex, we need to use this thing , We usually set up multiple routes in the project . We can create routing files in the application .  Insert picture description here This is actually very similar to the main route file . Then we go to the main route file to declare .  Insert picture description here So when you visit /Two/index This directory will get a response .

Django Configuration of database

Activate default sqllite

stay Django As a default with a database  Insert picture description here Next, please use pycharm Database tools ,vscode Please download the relevant plug-ins ( At present, my learning environment is still windows When I do the project, I will move to Ubuntu, Write md Documentation is a good habit , I will keep recording and uploading to csdn)  Insert picture description here Find where the arrow points , My time 2018 pro , If it is another version, it may not be in this position , Look for .  Insert picture description here  Insert picture description here Then the table will appear on your right , But it's not over , You have to move . Input instruction ( Console )

python manage.py migrate
 Copy code 

If everything goes well, you can see the following figure :  Insert picture description here You can check the table after clicking , Change, etc , Very convenient .

Switch database (sql)

In our settings You can fix it , But here are a few more questions .  Insert picture description here

        'ENGINE':'django.db.backends.mysql',
        'NAME':' Database name ',
        'USER':'username',
        'PASSSWORD':'password',
        'HOST':'host',
        'PORT':'port',
 Copy code 

Download driver installation , Here we must use pymysql. But in use, we should pay attention to a problem , find , Initialization file . Write this code , Drive camouflage , Disguised as a MYSQLDB  Insert picture description here Then migrate ,

python manage.py migrate
 Copy code 

The database is easy to operate

Create table

This is in our models Handle .  Insert picture description here Now we have created the table , But also , Complete mapping , That is to transfer the file code

python manage.py makemigrations

 Copy code 

Then it will generate such a file  Insert picture description here Then in the migration

python manage.py migrate
 Copy code 

 Insert picture description here

CURD Simple operation

This will directly demonstrate the process .

1. Find the watch , That is, the class that defines the table , Here is Student class 2. Operate on the instance object (students = Student()) 3. increase for example : students.name = 'jack',students.name = 'jack1' Two data will be added at this time 4. Read students.object,all() Read all students.object.get( Conditions such as :pk=2 find id=2 Of ) 5. modify , Based on queries , Modify it directly after finding it for example :stu1 = students.object.get(pk=2) stu1.name=‘hello’ 6. Delete , Based on queries , direct delete() stu1.delete() 7. Last , All operations must be submitted 8. students.save() Otherwise, it can't be submitted

Add

Diagram process

 Insert picture description here

--------------------------------------------------------------------------------------------------------------

The creation of a table

Simple creation of tables

To create a table , Then you must inherit Model, This is actually due to Django One of its own data processing methods , stay Django All database operations are encapsulated .

from django.db import models


class Student(models.Model):
    S_name = models.CharField(max_length=32)
    S_age = models.ImageField(default=1)

 Copy code 

At this point, we have created a table . But we still need to operate when processing .

python manage.py makemigrations
python manage.py migrate
 Copy code 

As for what this is , Let's get to know django Processing of data model .

Django The creation process of

Before that, let's take a look at Django The general pattern of database processing .

 Insert picture description here

So we found that django The reason why it can encapsulate the operation of the database , In fact, there is a processing mechanism , This mechanism is equivalent to a translator , Can help us put our operation , Become the operation language of the corresponding database . Therefore, in order to realize this scheme , Then there is a conversion process , And the actual operation process to the database . And this is what we just

python manage.py makemigrations
python manage.py migrate
 Copy code 

When the first instruction is executed , It generates such a file , It says something like this .( In fact, yesterday's blog mentioned )  Insert picture description here

 Insert picture description here Then execute the second instruction , Then our table will be created .  Insert picture description here  Insert picture description here  Insert picture description here

But what's important here is , His name is not Student But he has created another name himself , Stored in the database .

“ Individualization ” The creation of a table

Control of table fields

db_colum               Field name 
null                  False Indicates that the field cannot be empty 
blank                 False Indicates that the field cannot be blank 
primary_key            Set the primary key ( A primary key field will be generated for you by default id, Just like the table shown above )
unqiue   			   Is it unique 
 Copy code 

Example :

class Person(models.Mode):
	p_name = models.CharField(max_length=16,unqiue=True,null=False)
	p_age = modeIntegerField(default=18)
	p_sex  = models.BooleanField(default=False)
 Copy code 

Notice here , Corresponding sql In fact , There are only a few types of strings , Numbers , The dates are . that Boolean Actually in django Short integers are used in . This point can be seen in the generated DDL.

Change the name of the watch

This is also simple , Look at the code

class Person(models.Mode):
	p_name = models.CharField(max_length=16,unqiue=True,null=False)
	p_age = modeIntegerField(default=18)
	p_sex  = models.BooleanField(default=False)
	class Meta:
		db_table = "Person"
 Copy code 

But please pay attention , That is, whether you modify the table name or the field , In fact, they are all the contents of the modified database , When we control with code , Or with the class name we define ourselves , Variable names !!!!!!

Assignment of table

Attribute assignment method

These methods are defined and named by myself, which may not be accurate . This is a direct instance object, and then assign a value , after save() preservation , Uploaded to the database .

def set_value():
	person = Person()
	person.p_age=20
	person.p_name = "XiaoMing"
	person.save()
 Copy code 

Instance assignment method

This is where new( When creating an object, directly pass the value )

person = Person(p_name="XiaoMing",p_age=20)
 The disadvantage is when writing code IDE No hints , And it's easy to make mistakes , And there are Django Version compatibility issues 
 Copy code 

Custom class method assignment

So let's create one create() Method , stay Person in

class Person(models.Mode):
	p_name = models.CharField(max_length=16,unqiue=True,null=False)
	p_age = modeIntegerField(default=18)
	p_sex  = models.BooleanField(default=False)#0 Woman 1 male 
	class Meta:
		db_table = "Person"
 @classmethod
	def create(cls,p_name,p_age=18,p_sex=True):
		return cls(p_name=p_name,p_age=p_age,p_sex=p_sex)
	
 Copy code 

This cls It's actually our Person class Call create

Person = Person.create("XiaoMing")
Person.save()
 Copy code 

Data filters ( Inquire about )

The words here are divided into two categories , One is to return the query results that meet the conditions , One is to return the results that do not meet the conditions . In addition, it can be subdivided into , Methods that return multiple results and methods that return one . In addition, we need to understand that all queries are actually through objects Controlled , And this is actually a controller , We can specify ourselves .

Methods that return multiple results

all()		 Return all results 
filter()     Return all results that meet the conditions 
exinclude()  Return all results that do not meet the conditions 
order_by()   Sort order_by('p_age')  Sort by age 
values()	 This can wrap the returned results into a list , Every element is a dictionary ({’ Field name ':value}) Suitable for conversion to json
 Copy code 

Return a single method

get()
first()
last()
count()		 Number of Statistics 
exisits()	 Returns a Boolean value 
 Copy code 

All these methods can be used together

Query examples

def get_age(request):
	person = Person.objects.all().first()
	print(person.name)
 Copy code 

This is a simple query , A lot of filters can be connected behind .. For example, I want to check that the age is older than 18 Less than 80 Yes, we can write

persons = Person.objects.filter(p_age>18).filter(p_age<80)
 Copy code 

You can also write like this .

persons = Person.objects.filter(p_age__gt=18).filter(p_age__lt=80)
 Copy code 

Variable name __ Conditions = value In this form Then the conditions are probably gt > lt < gte >= lte <= exact = in In what :Person.objects.filter(p_age__in=[18,20,30])

contains : Contains something similar to sql Medium like like %xx%(icontains Ignore case ) startswith : What does it start with (istartswith) endswith : What's the end (iendswith)

Now I check the names of "X" Of

persons = Person.objects.filter(p_name__contains="X")
for person in persons:
	print(person.p_name)
	
 Copy code 

Now let's simply implement our personnel verification through this , Let's assume that the name is the user name , Age is the password , See if this person is this person .

def find_person(person_name,person_age):
	persons = Person.objects.filter(p_name=person_name)
	if person.exists():#person.count()
		person = persons.first()
		if person.p_age == person_age:
			print(" The information is correct ")
		else:
			print(" Age error ")
	else:
		print(" Check no one ")
		
	
	
 Copy code 

Query slice

Or the previous example .

persons = Person.objects.filter(p_age>18).filter(p_age<80)
 Copy code 

This guy returns an iteratable object , So that means you can slice . But the principle of this slice is actually similar to sql In the middle of limit offerset Operation of the . Instead of loading all the results directly into memory , Then perform the slice operation .

persons = Person.objects.filter(p_age>18).filter(p_age<80)[0:3]
 Left closed right away 
[0,3)
 Copy code 

Besides, there can't be plural in the slice, because that thing is limit operation

Cross relational query

In fact, this is the association of tables . Now suppose you create two tables , One is the student table , It's a class watch , The relationship is many to one .

class Grade(models.Model):
	g_name = models.CharField(max_length=32)
	

class Student(models.Model):
	s_name = models.CharField(max_length=16)
	s_grade = models.ForeignKey(Grade) # Add a foreign key constraint 
	
 Copy code 

There are actually two ways , Suppose we have a query called Xiao Ming What is your class . The first one is to query step by step . Let's assume that the name is unique

student = Student.objects.get(s_name=" Xiao Ming ")
grade_name = student.s_grade.g_name
 Copy code 

One time query , One step in place , Let's check the class directly

grade_name = Grade.objects.filter(student__s_name=" Xiao Ming ").first().g_name
 Copy code 

F object

This is actually related to query filtering , stay Django.db.models Next , This is mainly to help us compare the two fields . for example :

class Company(models.Model):
	c_name = xxxxx
	c_girl = xxxxx  Number of boys 
	c_boy = xxxxxx  Number of girls 
 Copy code 

Now I want to find companies with more boys than girls

companies = Company.objects.filter(c_boy>F('c_girl'))
 perhaps 
companies = Company.objects.filter(c_boy__gt=F('c_girl'))
 Copy code 

Q object

This is mainly used to help us filter multiple conditions . The advantage is that you don't have to write so many filtering methods . for example :

persons = Person.objects.filter(p_age>18).filter(p_age<80)
 Copy code 

I could change it like this

persons = Person.objects.filter(Q(p_age>18) and Q(p_age<80))
 In addition, you can do this 
persons = Person.objects.filter(Q(p_age>18) & Q(p_age<80))

or  ---> |
not ---> ~
 Copy code 

Aggregate functions

For example, look at what we defined earlier Person How do we find the oldest

max_person = Person.objects.aggregate(Max("p_age"))
Max Also in the  django.db.models Next 
 Besides, there are :
	Max
	Avg
	Min
	Sum
	Count
	 The returned result is in the following format :
	 for example :{'c_age_max':88}
 Copy code 

This is actually encapsulated .

Model members

In front, I don't know if you noticed , Every time I want to query data, I need to call objects So what the hell is this thing . This is actually a model .  Insert picture description here But there are two kinds , One is recessive and the other is dominant . our objects It's hidden , The most obvious reason is , We haven't defined this thing at all . This is our parent class Model Self contained . So what does dominance look like , Obviously, what we define ourselves is explicit . So what are the benefits of doing this , That is, we can make our own rules . Here is a simple example .

Dominant model

class Person(models.Mode):
	p_name = models.CharField(max_length=16,unqiue=True,null=False)
	is_delete = models.BooleanField(default=False)#0 No, 1 deleted 
 Copy code 

If we want to get the data, the data we get must not be deleted . So normally we can write

persons = Person.objects.filter(is_delete=False)
 Copy code 

But obviously we need to filter every time we get the data , Well, if you write like this every time, it will be very troublesome , So we can specify the model ourselves , Write a filter rule .

class PersonManager(model.Manager):
	def get_queryset(self):# This is the method of the data returned by the model 
		return super(PersonManager,self).get_queryset().filter(is_delete=False)

class Person(models.Mode):
	p_name = models.CharField(max_length=16,unqiue=True,null=False)
	is_delete = models.BooleanField(default=False)#0 No, 1 deleted 
	objects = PersonManager()# You can also call other names, such as :p_m, So the call is :Person.p_m.all() etc. 
	
	
 Copy code 

The picture below is Model.Manger Part of the code  Insert picture description here

Soft delete

That's it , I have to say soft deletion , It is impossible to delete data, especially important data, such as user data , Then the deletion at this time will not be really deleted in the database , But through the one we just had, which is similar to is_delete To hide the value of the field , Filter . In other words, when deleting, we just set the value to true , And we specify the model ourselves, so if it is true, it will be filtered first , As soon as the data comes, a deletion effect is realized . How to do it? , It's also very simple. , rewrite delete The method can .

class Person(models.Mode):
	p_name = models.CharField(max_length=16,unqiue=True,null=False)
	is_delete = models.BooleanField(default=False)#0 No, 1 deleted 
	objects = PersonManager()# You can also call other names, such as :p_m, So the call is :Person.p_m.all() etc. 
	def delete(self):
		self.is_delete = True
		self.save()	
 Copy code 

That's good .

Add (Django Database area problem )

Because in Django I used a time zone ( We set it up by ourselves , The default is also world time ) These three solutions , One is to set the time zone of the database . Another is to make mistakes and not set the effective time zone for the time being  Insert picture description here The last one is to check the time zone , Change our current time zone to the world time zone . Reference blog :django--- Time zone problem (USE_TZ)

--------------------------------------------------------------------------------------------------------------

Template statement

Templates exist in HTML In the code , But this will not be recognized by the browser. It needs to Django Or other frames or renderers after rendering , Will be displayed in the browser . Here, templates can be roughly divided into two types of use , One is template logic statement , For example, conditional judgment , loop . The other is assignment , This is through powerful ‘ spot ’ Grammar is easy to handle .

Let's talk about it briefly django The implementation process . When we use it render Directly give out the template and data . In fact, the complete step is to load , Then render , And then use httpResponse send out .( Update with fate , It's hard to sort out the content )

temp = loder.get_template("Base.html")
content = temp.render(data)
return HttpResponse(temp)
 Copy code 

interpolation

spot grammar

The dot syntax in the template is very interesting , It is similar to python The point grammar , Point everything . Here's an example :

adopt key Take value

def Test(request):
	Data = {
		"name":"xiaoming",
		"age":18,
		"Person":{"height":175},
		}
	return render(request,"base.html",content=Data)

 Copy code 

Now get it Data Name

<p> {{name}} </p>
 Copy code 

Get Person height

<p> {{Person.height}} </p>
 Copy code 

Passing attribute & Method

In addition, point syntax can also call methods . for instance :

class Student(models.Model):
    S_name = models.CharField(max_length=32)
    S_age = models.ImageField(default=1)
    def get_s_name(self):
    	return self.S_name
 Copy code 
def Test(request):
	student = Student.objects.get(S_name="XiaoMing")
	Data = {
		"name":"xiaoming",
		"age":18,
		"Person":{"height":175},
		"student":studnet,
		}
	return render(request,"base.html",content=Data)
 Copy code 

Now get it student Name

<p> {{studnet.S_name}} </p>
 Copy code 

perhaps

<p> {{studnet.get_s_name}} </p>
 Copy code 

Through the index

Now change it again

def Test(request):
	student = Student.objects.get(S_name="XiaoMing")
	Data = {
		"Person":[{"height":175},{"height":185}],
		}
	return render(request,"base.html",content=Data)
 Copy code 

Now take it 185

<p> {{Person.1.height}} </p>
 Copy code 

Injection prevention

The reason is simple , We said {{value}} This is interpolation , Insert data into it later , Fill in , So here comes the question , If I insert a paragraph HTML What about code? ? By default , If you insert HTML perhaps js Code templates are not rendered , It will shield , But if you want to, there are ways .

<p> {{ code|safe}} </p>
 So if you have to code The value of is HTML The code will also be put in it , And it also has the function of corresponding code in the browser 
 So you have to make sure your value is safe , Otherwise, it is likely to be implanted with malicious js Code 
 There are other ways 
{ % autoescape off %} on Is the default on 
{{ code}}
{{code }}
{ % endautoescape %}
 Copy code 

Logical statement

Let's start with the format , This interpolation is {{ }} So we are {% sentence %} {% end sentence %}, This is like HTML The label is similar to , In general, there are echoes . But not all of them , Individual don't need this and **<input>** Similar labels .

loop

def Test(request):
	student = Student.objects.all()
	Data = {
		"students":studnet,
		}
	#return render(request,"base.html",content=Data)
	return render(request,"base.html",locals())
 Copy code 

locals() Method will convert local variables into dictionaries , The effect is the same as the commented out code

<ul>
	{% for student in students %}
		<li>{{student.S_name}}</li>
	{% endif %}
</ul>
 Copy code 

In addition, we can use forloop.counter View the current number of cycles

<ul>
	{% for student in students %}
		<li>{{{forloop.counter}}-{student.S_name}}</li>
	{% endif %}
</ul>
 Copy code 

filter

This is to filter the results . for example

def Test(request):
	student = Student.objects.all()
	count = 5
	return render(request,"base.html",locals())
 Copy code 
<p>{{count|add:5}}</p>
		  |lower  A lowercase letter 
		  |upper  Capitalization 
 Yes  count  Add  5
 There is no reduction here , You add a negative number to do 
 Multiply and divide with this 
{% withratio count 1 5} count   multiply  5
{% withratio count 5 1} count   Divide  5 ( Take a look at this position , It's not very useful , Efficiency is too low , Yes, to load , Re operation, re rendering , That directly 
 Is it not good to calculate and render )

 Copy code 

With this, we can do the remainder operation .

count | divisibleby:2  Yes 2 Remainder 
 Copy code 

Judgment statement

Here's an explanation , The conditional judgment here is not direct if = value Use , If you want to use it like this Just equalif value Instead of , Other IDE There's a hint . This combination of remainder operation to make an interlaced color changing thing. Let's have a look .

<ul>

{ % for studnet in students %}
	{% if foorloop.counter|divisibleby:2 %}
		<li style="color:red">{{studnet.S_name}}</li>
	{ #{% elif %} #}  This is a comment with elif Branch judgment 
	{% else %}
		<li style="color:blue">{{studnet.S_name}}</li>

{% endfor %}

</ul>
 Copy code 

The code above is wrong , Self correcting

notes

Template comments are compared to HTML The benefit of text annotation is ,HTML The comments will be displayed in the code , But the template will not ( In the browser )

Single-line comments

{ #  Content  # }
 Copy code 

Block annotation

{ % comment %}
 The comment 
{% endcomment %}
 Copy code 

Template inheritance

file name Base.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>Title</title>
</head>

<body>
    <div id="sidebar">
        {% block sidebar %}

        {% endblock %}
    </div>

    <div id="content">
        {% block content %}
         <p> I am a Base</p>
        {% endblock %}
    </div>
</body>
</html>
 Copy code 

Now you have defined a template , We use block Define the area , That is to divide the area . When inheriting the template, the word template can obtain the content of the parent template , But in the sub template, so HTML The code can only be written in block In the divided area , If you leave, it will be invalid . This external child template will overwrite the contents of the parent template , If you want to save, you need to inherit .

{% extends "base.html" %}

<h2> I'm outside , Will not show , But there are no mistakes </h2>
{% block content %}

{{block.super}}  Show   I am a Base

{% for student in students %}

    <p>{{ student.S_name }}</p>
    
{% endfor %}
{% endblock %}
 Copy code 

Then there's another include This thing can put a html The file is loaded directly from one part of it , Be similar to frame

{ % include 'base.html' % }
 This method consumes a lot of resources , Not recommended .
 Copy code 

Static resources

What is this? It's very simple. That's our css js Placement of , We can't put all these documents in html The file of , All we have to do is store that file exclusively .  Insert picture description here Then register  Insert picture description here

 Insert picture description here Or use the template to dynamically load , Load resources first {% load static %} then href = "{ % static 'css/hello.css' %} " The advantage of this is that in the future, the project changes only need to change the configuration file  Besides href You can also write

--------------------------------------------------------------------------------------------------------------

Routing path

Don't be misled here path Regular is not supported, only url To support In fact, this is mainly about the route in detail , That is, the problem of the request path accessed by our browser client .  Insert picture description here And how we use it or get parameters , And how to request (GET、POST) Get the parameters of the client in Django among .

Matching rules

stay Django In fact, such a match is not a strict match , This sentence involves some regular . For example, there is now such a routing path .

r"^adminnn"
r"^admin"
 Copy code 

After you start the service , for example 127.0.0.1:8000/admin At this time, the visit is likely to be adminnn page . The match is not strict , Plus the principle of proximity leads to this consequence . So when writing, this path must be followed by Forward slash “/"

Pass parameters through routing

Suppose I have a picture website , I need to do a pagination , So obviously, I need to use routing to help us pass parameters , For example, there is a page

127.0.0.1:8000/image/
 Copy code 

When we are passing 1 Give the content of the first page when ,2 Give the content of the second page .

127.0.0.1:8000/image/2
 Copy code 

I can't write a bunch of routes at this time , So how to do it This time we need to use regular

r"^image/(\d+)/
 Copy code 

In this way, the problem is solved So how to get the parameters? Carve it and see view Processing function of

def images(request,id):
	pass
	 such  id  That's the data we got 
 Copy code 

If we have more than one , for example

r"^image/(\d+)/(\d+)/
 Copy code 

Then our acceptance parameters should also have multiple , And this is one-to-one correspondence, in order

def images(request,id,id1):
	pass
 Copy code 

This is obviously inconvenient , Sometimes our parameter order may be confused , Then we need a name .

r"^image/(?P<username>\d+)/(?P<password>\d+)/
 Copy code 
def images(request,username,password):
	pass
 Copy code 

Sub route

Pay attention to the default path This is very clear in the previous blog .( The main purpose of blogging is to serve myself , I just made it public , If you feel confused, or you don't read my blog in order , This thing is in order , Learning blogs like this . Or you didn't take it seriously , Or you just can't accept this style . It doesn't matter , Or that sentence , This is mainly for myself , It makes sense for you to whore for nothing ??!!! I probably don't reply to private letters , Not open , Unless you pay ) Django Learning Series ( One . First time to know )

Reverse route resolution

This function is to dynamically load the request path , The placement path change caused the client request to fail , This should match the template syntax . On the client side .

    url(r'^admin/', admin.site.urls,name="admin"),
    url('',views.hello),
    url(r"^app/", include(("APP.urls","APP"),namespace="APP")),# Register sub routes in the root route 
 Copy code 

url(r"^app/", include("APP.urls",namespace="APP")) It's OK to write like this , But in the sub route, you have to add app_name

app_name='APP'
urlpatterns = [
    path('',index,name='index'),
]
 Copy code 

In the sub route, it is like this

from django.conf.urls import url
from Two import views
# Create a sub route 
urlpatterns=[
    url(r'^index/',views.hello,name="hello"),
]
 Copy code 

Now access admin and tow/hello

<a href="{% url 'admin' %}"></a>
<a href="{% url 'two:hello' %}"></a>
 Copy code 

So it's simple in the code

url = reverse("admin")
url1 = reverse("two:hello")
 Get it done 
 Copy code 

GET To obtain parameters

First of all URL The composition of , This player should be familiar with . How do you play with this thing , That's what I didn't mention in these blogs request. This contains all the information of all clients , Include COOKIE IP Your equipment model , Even the software installed on your device . Basically through request You can get most of the information on your computer , So please don't visit unknown malicious websites , Especially a small website and so on , Your information has been exposed . Let's talk about it first. request About what things are there

 request.method
 		.path
 		.GET
 		.POST
 		.session
 Copy code 

These things are clear at a glance , Handle session, This is conversation technology , The next blog will say

Now construct such a url

http://127.0.0.1:8000/login?username="jack"&password="123456789"
 Copy code 

obtain username,password

def get_parmers(request):
	username = request.GET.get("username")
	password = request.GET.get("password")
 Copy code 

Here's another detail That's it get What you get is not a complete values Suppose there is such a request

http://127.0.0.1:8000/login?username="jack"&username="surry"
 Copy code 

Then come back and get username

def get_parmers(request):
	username = request.GET.get("username")
 Copy code 

The return is : surry So this is the time to

def get_parmers(request):
	username = request.GET.getlist("username")
 Copy code 

The result is a list

POST To obtain parameters

This is simple , It's simpler . Look at the code

<form action="/test/" method="POST">
<input name = "username" type = "text">
<button> Submit <button>
</form>
 Copy code 
def get_parmers(request):
	username = request.POST.getlist("username")
 Copy code 

  Directly through the label name Get

META View all information

Get IP

IP= request.META.get("REMOTE_ADDR")
 Copy code 

You can see this by reading it

for key in request.META:
	print(request.META.get(key))
 Copy code 

--------------------------------------------------------------------------------------------------------------

COOKIE conversation

Remember one sentence before you start , That's it cookie The server must send it to the client , And saved in the client's

cookie technological process

 Insert picture description here

Example

Here's an example , Make a simple so-called login page , In order to simplify the process , An understanding will not involve verification ( Below token Will join this link ) The login page login.html

<form action="/login/" method="POST">
<input name = "username" type = "text">
<button> Submit <button>
</form>
 Copy code 

minespace.html

<h2> Welcome :{{username}}!</h2>
 Copy code 
def login(request):
	if request.method == "GET":
		render(request,"login.html")
	elif request.method =="POST":
		username = request.POST.get("username")
		response = HttpResponse(" Login successful ")
		response.set_cookie('username',username)
		#  This cookie You can set the survival time , The default is to close the browser , Specifically, you can set a parameter ,max-age
		#render It can also be set , That's actually an abbreviation , You can see directly from the source code 
		return response
 Copy code 
def minspace(request):
	username = request.COOKIE.get("username")
	if username:
		return render(request,"minspace.html",context=locals())
	else:
		return redirect("/login/")
		#  If it fails, return to the login page 
 Copy code 

Log out

def logout(request):
	response = render(request)
	response.delete_cookie("username")
	return response
 Copy code 

cookie encryption

Now we are still in clear text , Obviously, this is not safe In this way, a very simple process is realized . Although there is no simple verification here . Then encryption is also simple . The previous settings cookie encryption , Then decrypt when reading .

response.set_signed_cookied('username',username,salt=" secret key ")
request.get_signed_cookied("username",salt=" secret key ")
 Copy code 

SEESION conversation

This is actually the same as ours in code cookie similar , In fact, it is the same in essence . But the difference is , Saved on the client cookie It's actually a key , This is in django It stores the information of temporary users . We can look at this watch  Insert picture description here Client saved cookie Namely session_key Field stuff The process is as follows  Insert picture description here

Example

All page relationships are just the same

def login(request):
	if request.method == "GET":
		render(request,"login.html")
	elif request.method =="POST":
		username = request.POST.get("username")
		response = HttpResponse(" Login successful ")
		request.session["username"]=username
		#  This cookie You can set the survival time , The default is to close the browser , Specifically, you can set a parameter ,max-age
		#render It can also be set , That's actually an abbreviation , You can see directly from the source code 
		return response
 Copy code 
def minspace(request):
	
	if request.session.get("username"):
		# He will check the client's return cookie And get username( Be encrypted ) Of session_key Go to the database and look 
		# If it is not found, an error will be reported , So it's better to add 
		return render(request,"minspace.html",context=locals())
	else:
		return redirect("/login/")
		#  If it fails, return to the login page 
 Copy code 

Log out

def logout(request):
	response = render(request)
	#response.delete_cookie("username")  Delete client cookie
	#del request.session["username"]  Delete database information , But here we just delete the value , Did not delete that line 
	request.flush() # This has been operated , And the row in the database is deleted directly  clear()  Clear the database directly 
	return response
 Copy code 

stay session You can input Chinese directly , This is because it does a lot of transcoding , Then he did a lot of encryption himself .

This is in django Which is stored in a database , The rest is not clear . Similarly, this is also ineffective , In the database, the default is 14 Days in effect . But this is only effective , That's it. key It works , Does not seem to automatically delete key. You have to operate it yourself .

Token conversation

This is actually a custom one cookie Conversational Technology , Through the flow chart above, it is clear what the so-called conversation technology is , To put it bluntly, it is to give a user a temporary pass . So why was this thing born , In fact, it is to meet the needs of non BS Apps and mobile apps . After all cookie This thing is only supported by browsers . Therefore, in order to meet other needs, we need not to submit automatically based on the browser like the browser cookie To verify . So in our other clients, we usually use json data , We return a field token, This is our temporary token . Next, let's continue to take the browser as an example to implement a Token. When we are in, for example, Andrews , We go straight back json Data brought into token Field can be for example :

data = {'msg':"hello, 'satus':800, 'token':token,}  Copy code 

What we need to do on the server side is to token To the client , You can identify in the server . As for the others , You have to see the developer of the client ( Hey, hey, just throw the pot ) Now let's build a table and walk through the completed process .

class User(models.Model):
	user_name = models.CharField(max_length=64,unqine=ture)
	user_password = models.CharField(max_length=64)
	token = models.CharField(max_length=256)
 Copy code 

It's a direct HTML Code omitted , Anyway, users are username The code is password register :

def register(request):
	if request.method == "GET":
		return render(request,"register.html")
	elif request.method == "POST":
		username = request.POST.get("username")
		password = requrst.POST.get("password")
		user = User.objects.filter(user_name = username)
		if user.exists():
			return render(request,"register.html")
		else:
			user = user.first()
			user.user_name=username
			user.user_password = password
			user.save()
	return HttpResponse(" Registered successfully ")
 Copy code 

Sign in :

def login(request):
	if request.method=="GET":
		return render(request,"login.html")
	elif request.method == "POST":
		username = request.POST.get("username")
		password = requrst.POST.get("password")
		user = User.objects.filter(Q(user_name=username)and Q(user_password=password))
		if user.exists():
			user = user.first()
			ip = request.META.get("REMOTE_ADDR")
			token = JiaMi(ip,username)
			user.token = token
			user.save()
			response =  render(request,"minespace.html")
			response.set_cookie("token",token)
			return response
			
		else:
			# The user is wrong / password 
			return render(request,"login.html")
			
 Copy code 

Here we define a simple encryption program

def JiaMi(ip,username):
	time = time.ctime()
	return hashlib.new('md5',(ip+username+time).encode('utf-8')).hexdigest()
 Copy code 

Personal space module

def minespace(request):
	token = request.COOKIE.get("token")
	try:
		user = user.objects.get(token=token)
		username = user.user_name
		return return render(request,"minspace.html",context=locals())
	expect Expection as e:
		return redisrect("/login/")
 Copy code 

minespace.html

<h2> Welcome :{{username}}!</h2>
 Copy code 

flow chart

 Insert picture description here Finally, delete , It's not easy . And look at the flow chart above. In fact, this is similar to our session It's like , We just defined the encryption method ourselves , And the difference is that in the future, we can return... Through the client json To maintain the conversation , instead of cookie, Of course we can pass it cookie If you support it .

--------------------------------------------------------------------------------------------------------------

Template migration

This is a platitude , Here, let's briefly say pit point .

Template record

Many friends are modifying the structure of the original table , Will definitely put django Originally generated init Delete the file and rewrite it , Migrate write . But when writing, there is no response at all , The meter of your database hasn't moved at all . This reason is actually because ,django The record in it has not been deleted .  Insert picture description here This table contains a large number of migration records , You can only delete the corresponding migration records , Then the system will migrate to you again , Then write it to the database .

Model reflection

Our previous operation

python manage.py makemigrations
python manage.py migrate
 Copy code 

Are all the Model become sql, So now we will sql become Model, That is to change the table we built in the database into our django In the model , This is also simple .

python maganer.py inspectdb > APP/models.py
  So we get this thing into our model file 
 Copy code 

Model relationship

This is actually the correspondence between the tables of the database we learned before . for example : one-on-one , One to many , Many to many

One to many

This one sucks. Actually , And the most basic , Other relationships are actually built through it . stay sql Just set a foreign key directly in the statement , Also in django The same is true of . Look at the code :

class Grade(models.Model):
	g_name = models.CharField(max_length=32)
	

class Student(models.Model):
	s_name = models.CharField(max_length=16)
	s_grade = models.ForeignKey(Grade) # Add a foreign key constraint 
 Copy code 

This is a very typical one to many , Add foreign keys to those who have more , stay djnago among , This foreign key actually refers to id, stay django The model will generate a by default id, All relationships default through id To bind . In fact, there is nothing to say. It is very easy to understand the relationship between the class and students , Add a field in the student table to save the class id, This field refers to (reference Grade(id) ) And can repeat the class id( Multiple students in the same class ), But in one to many , hypothesis ( Class and students one-on-one ) Then store the class in the student table id The fields of are not allowed to be repeated !  Insert picture description here

One to many

This is obvious from the picture above . So in django It's good to say so

class Person(models.Model):
	p_name = models.CharField(max_length=32)
	

class Person_id(models.Model):
	p_id = models.CharField(max_length=32)
	p_person = models.OneToOne(Person)
 Copy code 

Now use the relationship between ID card and people as an analogy  Insert picture description here

Many to many

We should pay attention to this , Because the operation is different . So how is it realized , Let's start with an example , The relationship between shopping cart and people , This is a typical many to many .

class Customer(model.Model):
	c_name = models.CharField(max_length=16)

class Goods(models.Model):
	g_name =  models.CharField(max_length=16)
	g_customer = models.MangToMangField(Customer)
 Copy code 

Now we have built the model , So let's operate the model first , Later, let's talk about how this thing is made . The query part is still the same as before , But there's an added relationship here , For example, we added a product in our shopping cart .

Phone = Goods()
Phone.g_name="iPhone12"
Phone.save()
Me = Customer.objects.get(c_name="xiaoming")
Me.goods_set.add(Phone)
			.remove(Phone)
			.set(Phone1,Phone2,...)
 Copy code 

Of course, we can also turn the other way around , But in fact, these effects are the same , The reason is shown in the figure below .  Insert picture description here So if you want to implement it yourself, you can also design it in this way , Even more complicated .

Master slave table

Every time this multi table relationship is involved, the problem of joint table relationship will appear , stay django For example, the ID card table in the relationship between person and ID card is from the table , When the main table is deleted , It will also be deleted from the table (delete on cascade), This is the default , So sometimes for data security , We should set up , For example, only when the corresponding data in the table is deleted , Then the main table can be deleted .

class Person_id(models.Model):
	p_id = models.CharField(max_length=32)
	p_person = models.OneToOne(Person,ondetele=models.PROTECT)
	 Of course, there are other models 
		SETNULL
		SET_DEFAULT()
		SET()
 Copy code 

--------------------------------------------------------------------------------------------------------------

Native cache

A lot of people are django It's for sql frame , as a result of django Of Model Most face sql. There are many reasons , The main reason is that in most cases, we are right sql More dependent on , A website can not redis But no sql Then you can't do it at all , Unless you're just a static page with an extremely rudimentary display of information , No data interaction , Or very little interaction . So in django Other databases can also be used , Just support relative to sql Not so good . This cache service is actually django There is a built-in cache, He will store the cache in the database , Of course, there must be no redis So fast , But relatively speaking, hard disk is much cheaper than memory . Build table You have to build a table first

python manage.py createcachetable my_table_name
 Copy code 

To configure : Open this setup file  Insert picture description here

CHACHES={
    'default':{
        'BACKEND':"django.core.cache.backends.db.DatabaseCache",
        'LOCATION':"my_cache_table",
        'TIMEOUT':'60',
    }
}
 Copy code 

Of course, there are other configurations , The first few are basically enough . Of course, you can also add option

CHACHES={
    'default':{
        'BACKEND':"django.core.cache.backends.db.DatabaseCache",
        'LOCATION':"my_cache_table",
        'TIMEOUT':'60',
        'OPTIONS':{"MAX_ENIRIES":'300',},
		'KEY_PREFIX':'Huterox',
    }
}


 Copy code 

Use cache to speed up There are many ways , The simplest thing is to create a cache decorator directly .

def index(request):
	sleep(5)
	return HttpResponse("Hello")
 Copy code 
@chache_page(60,'Huterox')# Expiration time , If you add option Option, then give the corresponding parameters to 
def index(request):
	sleep(5)
	return HttpResponse("Hello")
 Copy code 

Then a complete process is as follows :  Insert picture description here

Custom cache

The front decorator cuts across the board , This is obviously not good , And we should also customize it later when we limit the number of user visits . Let's start with a few methods set(key,value) get(key) This thing is the core

def index(request):
	result=cache.get('index')
	if result:
		return HttpResponse(result)
	else:
		#index=....
		# Here is index In order to simplify the operation of the page, I directly let it sleep for five seconds to simulate a lot of loaded pages .
		sleep(5)
		index="Hello"
		cache.set('index',index,timeout=60)
		return Httpresponse(index)
 Copy code 

Use Redis

Because of us django There is no original redis So we need to install a third party django plug-in unit

pip install django-redis
pip install django-redis-cache
 Copy code 

Then configure There are actually two ways to configure this One is direct configuration

CHACHES={
    'default':{
        'BACKEND':"django_redis.cache.RedisCache",
        'LOCATION':"redis://127.0.0.1:6379/1",# Data address, port and database library (/1 The first library )
       	"OPTIONS":{
       	"CLIENT_CLASS":"django_redis.client.DefaultClient",
       	}
    }
}
 Copy code 

So if configured like this , Then use the old method . Another configuration is to use two together .

CHACHES={
    'default':{
        'BACKEND':"django.core.cache.backends.db.DatabaseCache",
        'LOCATION':"my_cache_table",
        'TIMEOUT':'60',
    }
    'redis':{
    'BACKEND':"django_redis.cache.RedisCache",
    'LOCATION':"redis://127.0.0.1:6379/1",# Data address, port and database library (/1 The first library )
   	"OPTIONS":{
   	"CLIENT_CLASS":"django_redis.client.DefaultClient",
   	}
}
    
}
 Copy code 

So let's change in use If you want to continue using native, then cache() perhaps

cache = caches['default']
@cache_page(60,cache='default')
 Copy code 

If you use redis Words

cache = caches['redis']
@cache_page(60,cache='redis')
 Copy code 

--------------------------------------------------------------------------------------------------------------

middleware

flow chart

What is middleware? In fact, it is oriented to AOP The product of programming , Generally speaking, it is a decorator , But this decorator is more powerful . So in Django What is this thing like , Let's take a look at the flow chart first .  Insert picture description here

So, after looking at the picture above , Then it's easy to do next .

Custom middleware

Create a file under our project middleware Directory is ( relative ) /middleware/LearnMiddle There's a class in it

class HelloMiddle(MiddlewareMiXin) def process_request(self,request):
		pass
 Copy code 

Then register

middleware.LearnMiddle.HelloMiddle
 Copy code 

 Insert picture description here Then we can write things in the middleware .

Example ( Restrict access to the home page )

class HelloMiddle(MiddlewareMiXin) def process_request(self,request):
		if request.path=='/index/':
			black_list = cache.get('black',[])# The blacklist , Specify that the return data type is list 
			ip = request.META.get("REMOTE_ADDR")
			if ip in black_list:
				return HttpResponse(" You have been blacklisted ")
			requests_num = cache.get(ip,[])
			while requests_num and time.time()-requests_num>60:
				requests_num.pop() # User access time 
			requests_num.app(time.time())#requests_num.insert(0,time.time())
			cache.set(ip,requests_num,timeout=60)
			# In fact, if timeout=60 Then there is no need to clean the data 
			if len(requests_num)>10:
				return HttpResponse(" Boy, you visit too often ")
			if len(requests_num)>30:
				black_list.append(ip)
				cache.set("black",black_list,timeout=60*60*24)
			
		
 Copy code 

Let's just do the rest . So here, basically django Almost , As for others, there are some commonly used plug-ins , and django Use nginx(django Their own runserver Low performance )

summary

Basically, that's about it , This blog may be updated later

copyright notice
author[Huterox],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020805078127.html

Random recommended