复习django概念全文档的记录

关于跨域

你有一个网站,叫做 mydomain.com。 这个网站上的 JavaScript 代码想要去访问另一个网站,比如 api.otherdomain.com 上的数据。浏览器出于安全考虑,默认情况下会阻止这种行为。 这就是 “跨域请求”。 “跨域” 指的是你的 JavaScript 代码所在的域名 (origin) 和它要访问的 API 所在的域名不同。

同源策略 (Same-Origin Policy):
这是浏览器的核心安全机制。 两个 URL 的 "协议" (protocol, 比如 http 或 https)、"域名" (domain, 比如 mydomain.com) 和 "端口" (port, 比如 80 或 443) 都相同,才被认为是 "同源"。

如何解决跨域问题?
CORS (Cross-Origin Resource Sharing): 这是最常用的方法,让 api.otherdomain.com 允许 mydomain.com 的请求。


image.png

django框架的运行逻辑

image.png

关于筛选

image.png
  1. 链式过滤 (Chained Filtering)
    Chained filtering: You can filter a queryset multiple times to form a chained filter. For example, get all novels with a price between 50 and 100:
    2、q过滤
    hen, you can use Q objects to perform complex logical queries, such as using logical operators AND, OR, NOT, etc. For example, find books where the author is John Doe or the price is less than 50.

model管理器

可以指定选项

image.png

一些概念

image.png

1.Use appropriate field types: Choose the appropriate field type based on the data type and storage requirements
2.Index optimization: Create indexes for fields that are frequently used for querying and filtering to accelerate data retrieval and filtering. At the same time, avoid excessive indexes and creating indexes on frequently updated fields.
3.Normalize data structure: Through reasonable database design, split data tables according to normal forms to avoid data redundancy and update anomalies, thereby improving data consistency and query efficiency.
4.Use foreign key relationships: For database models with complex relationships, use foreign key relationships to establish relationships between tables, in order to perform join queries and connection operations, avoid data redundancy, and improve query efficiency.

一些概念 auto_now和auto_now_add的区别

image.png

一些概念 关于时间

image.png

一些概念 日期格式

image.png

一些概念 数据库事务

image.png

Django中数据库迁移的性能优化⽅式主要包括以下⼏点:


image.png

批量创建和批量更新

image.png
image.png

F字段

定义: F 字段是 Django 提供的一种用于在数据库级别引用模型字段的表达式。 它允许你在不将数据加载到 Python 内存中的情况下,直接在数据库中执行字段之间的运算。


image.png

Q字段

image.png

惰性加载


Django模型的延迟查询机制是指在查询数据库时,Django并不⽴即执⾏实际的查询操作,⽽是在需要时
才执⾏。这种延迟查询机制通过惰性加载和缓存来实现
The lazy evaluation mechanism in Django models refers to the fact that Django does not immediately execute the actual query operation when querying the database, but only executes it when needed. This lazy evaluation mechanism is implemented through lazy loading and caching.

为什么外键放在 “多” 的一方?

这是为了维护关系数据库的完整性和避免数据冗余。 如果外键放在 “一” 的一方,那么一个作者就需要存储多个书籍的信息,这会导致数据冗余和更新困难。 将外键放在 “多” 的一方,可以确保每个书籍对象只存储一个作者的信息,避免了这些问题。


image.png

The English term for "级联删除" is cascading delete13.
Definition
Cascading delete is a database feature where deleting a parent record automatically triggers the deletion of related child records. This mechanism maintains referential integrity, preventing orphaned records in relational databases1.

Django 的信号机制

image.png

image.png

几种关联

  1. 反向关联 (Reverse Relation)


    image.png

    2、正向关联


    image.png

    3、自引用关联
    image.png

onetoone和外键的区别

image.png

通用视图(class-based view)

image.png

URL和视图

image.png

In the urls.py file of the project, configure URL mappings to associate URL patterns with view functions. When a client initiates an HTTP request, Django will match the requested URL and execute the corresponding view function.

URLCONF

image.png

The principle of the URL dispatcher is to achieve route matching and dispatch through the mapping relationship between URL patterns and view functions in the URLConf configuration file.

After receiving an HTTP request, it distributes the request to the corresponding view function according to the URL rules.

It implements the mapping relationship between URLs and view functions, enabling the program to correctly handle different HTTP requests.

drf实现rest api

image.png

序列化和反序列化

Serialization and deserialization of data: Use Serializers to define the way data is serialized and deserialized, ensuring effective data transmission and processing.

Django中的装饰器在视图函数中的应⽤

In Django, decorators are a very useful tool that can be used to add extra functionality or perform permission validation in view functions. Decorators can be used to wrap view functions and execute specific logic before or after the view function is executed. The following are applications of decorators in view functions


image.png

url conf和url调度器

INCLUDE

image.png
image.png

通过URLconf和视图函数的配合,Django能够实现灵活的URL分发和调度,将请求分发给对应的视图函
数处理和响应。
Through the collaboration of URLconf and view functions, Django can achieve flexible URL dispatch and routing, directing requests to the corresponding view functions for processing and response.

image.png

在Django中,可以使⽤URL模式和视图函数来处理动态URL和参数传递。⾸先,在urls.py中定义URL模
式,使⽤正则表达式来捕获动态部分,并将其传递给视图函数。然后,在视图函数中,接收参数并执⾏
相应的逻辑。
In Django, you can use URL patterns and view functions to handle dynamic URLs and parameter passing. First, define URL patterns in urls.py, using regular expressions to capture dynamic parts and pass them to the view function. Then, in the view function, receive the parameters and execute the corresponding logic.

请求钩子

image.png
image.png
image.png

在Django中,Middleware是⼀个轻量级插件,⽤于处理每个请求和响应。它们允许开发者在视图中间件
中编写来⾃请求的处理逻辑和来⾃响应的预处理逻辑。中间件可以⽤于验证、拦截请求、处理会话、⽇
志记录以及更改请求/响应。如果请求到达Django服务器,它会依次经过每个中间件。中间件能够捕获
请求并在响应返回之前进⾏处理
In Django, middleware is a lightweight plugin used to process each request and response. They allow developers to write processing logic from requests and preprocessing logic from responses in the view middleware. Middleware can be used for validation, intercepting requests, handling sessions, logging, and changing requests/responses. If a request reaches the Django server, it passes through each middleware in sequence. Middleware can capture requests and process them before the response is returned.

url 文件上传

request.FILE


image.png

缓存

image.png
image.png

DRF的序列化取代了传统的form

DRF 的序列化器取代了传统 Django forms 的大部分功能,使得 API 开发更加高效和便捷。


image.png
image.png

中间件和信号机制的区别

中间件是Django框架中⽤于在请求和响应处理过程中介⼊的⼀种机制。它允许您在处理请求之前或处理
响应之后执⾏特定的操作,如⽇志记录、安全检查等。与信号机制相⽐,中间件主要⽤于请求和响应的
处理过程,⽽信号机制则更加灵活,可以监听到特定事件的发⽣并执⾏相应的操作。
In Django, middleware is a mechanism used to intercept the request and response processing. It allows you to perform specific operations before processing a request or after processing a response, such as logging, security checks, etc. Compared to the signal mechanism, middleware is mainly used for the request and response processing, while the signal mechanism is more flexible and can listen for the occurrence of specific events and perform corresponding operations.

image.png

专业名词:
Model Operations: Django has built-in signals related to models, such as pre_save, post_save, pre_delete, and post_delete. These signals are triggered before and after a model is saved or deleted.
Custom Signals: You can define your own signals and send them anywhere in your application.

image.png

In Django, middleware is a mechanism for processing requests and responses, while the signal mechanism is a mechanism for communication between components within an application. Combining these two allows for custom operations and logic to be performed during request and response processing. For example, a signal can be triggered in middleware, and other components can listen for this signal and take appropriate action. This combined approach allows for adding extra processing logic without modifying existing code, thereby achieving more flexible and extensible functionality.

image.png
image.png

关于信号机制

image.png

关于性能优化

image.png

select_related 和 prefetch_related 是 Django ORM 中用于优化数据库查询性能的两种方法,它们通过减少数据库查询次数来提高效率,特别是在处理关联数据时。这两种方法都用于避免 N+1 查询问题,但它们以不同的方式工作。


image.png

image.png
image.png
image.png

select_related is suitable for one-to-one and foreign key relationships, fetching all data in a single query using a JOIN operation.
prefetch_related is suitable for many-to-many and reverse foreign key relationships, fetching data through multiple queries and connecting it in Python.
The choice of which to use depends on your data model and query requirements. Using them wisely can significantly improve the performance of your Django application.

image.png

Distributed Caching
Use a distributed caching system, such as Redis or Memcached, to store cached data in the application and ensure that multiple application servers can share the same cache.
Load Balancing
Use a load balancer (such as Nginx or HAProxy) to distribute traffic to multiple Django application servers and ensure that these servers can share session data.

celery和消息代理

image.png

For example, in an e-commerce website project, I needed to handle a large number of orders asynchronously. After an order was placed, complex tasks such as deducting inventory, generating shipping invoices, and sending email notifications needed to be performed. I used the Celery framework to handle these tasks asynchronously, ensuring the system's responsiveness and reliability.
The above is my experience and solution for handling complex asynchronous task processing scenarios I encountered during Django development.
使⽤合适的消息代理
选择⾼性能的消息代理如RabbitMQ或Redis,以提⾼异步任务处理的性能和稳定性。
Use an Appropriate Message Broker
Choose a high-performance message broker such as RabbitMQ or Redis to improve the performance and stability of asynchronous task processing.

image.png
image.png

Relationship with Asynchronous Task Processing:
Asynchronous task processing allows you to place tasks in a queue and have them executed asynchronously by background processes, while scheduled task processing allows you to set the execution time and frequency of tasks. They can be used in combination; for example, you can use Celery and Django-celery-beat to execute scheduled tasks asynchronously, thereby achieving the timed and concurrent processing of tasks.

image.png

最大的挑战,通常是性能,错误处理,重试机制

performance, error handling, and retry mechanisms

负载均衡

image.png

The round-robin algorithm is a simple load balancing algorithm that forwards requests to different servers in the order they are received. Each new request selects the next server in sequence until all servers have been selected once, and then the process restarts.

image.png

A stateless service refers to a service that does not store session state or client state itself. Each request is independent of the others and does not rely on previous requests. Stateless services are crucial for horizontal scaling because they allow requests to be routed to any available service instance without considering session or client state. This means that the number of service instances can be easily increased, and the load balancer can distribute requests to any idle instance, thereby improving the overall scalability and availability of the system. A typical example of a stateless service is a simple RESTful API service that receives requests, processes them, and returns responses without retaining any state information about the requests.

image.png

Load balancing is an effective means of improving system performance because it can distribute network traffic, enhance reliability and stability, and efficiently utilize system resources. Load balancing can distribute traffic across multiple servers, avoiding overloading a single server and improving the system's response speed and processing capacity. Through load balancing, the system can better cope with sudden traffic spikes and high load situations, ensuring a positive user experience. For example, in Django, we can use a load balancer (such as Nginx) to distribute user requests to multiple Django servers, thereby improving the system's performance and stability.

权限

image.png
image.png

djangodrf的权限控制

image.png

RBAC权限控制

image.png

In Django, RBAC is a Role-Based Access Control model. RBAC manages access control by assigning users to specific roles and then assigning corresponding permissions to each role. Specifically, RBAC grants permissions to roles, and users are then assigned these roles, thereby gaining the corresponding permissions.
Unlike RBAC, ABAC is an Attribute-Based Access Control model. ABAC determines whether to grant access based on the attributes of the object, the attributes of the user, and the attributes of the environment. This model is more flexible and can make decisions based on the specific context, rather than relying solely on the user's role.

image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容