In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "what is the Django development method". In the daily operation, I believe many people have doubts about what the Django development method is. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what is the Django development method?" Next, please follow the editor to study!
PART 1. Before we begin
Django, as a powerful Web application framework, has been gradually welcomed by everyone in recent years, and more and more Python developers have devoted themselves to the embrace of Django, but also because of the many contents in Django, when they first entered Django, they always felt that they were "willing but powerless" and did not know where to start. Or after a preliminary understanding, I don't know whether the current practice is elegant, how to organize a project, how to reuse my own code.
PART 2. Project architecture
A good project structure is half the success.
2.1 overall structure
By default, the project structure generated by Django looks something like this:
With the continuous increase of Application in the project, there will be more and more package in the local root directory, which makes it more and more difficult to maintain, so we need to have a clear plan for the whole project and reasonable location of each file.
If the project is small and you do not intend to reuse the Application in it, you can consider the following ways:
The venv folder holds the project's virtualenv environment, which is optional and can be placed somewhere else.
Database this App is specifically used to store model, manage commands and some custom filters used in templates, stored in the project root directory.
Docs and logs store the relevant documents of the project and the log files generated at run time, respectively.
Static stores static files, such as css/js/img/font, etc.
Utils stores tool functions, classes, and some general modules used in the project, such as logger and so on.
Templates stores template files, parent templates or templates inherited by multiple templates in the root directory and named with names such as base for easy maintenance, while the rest of the templates are placed in the folder of the corresponding application name.
The web directory stores all the Application, and if there are a lot of Application, you can divide it into more package to plan on this basis, and each package stores a class of Application.
2.2 Model
In the part of Model module, we are mainly concerned with the mapping of data to classes. In general, the corresponding classes of each table will be placed in a separate file, and the corresponding classes will be imported in turn in models/__init__.py, so that they can be imported through from database.models import xxxx when they are used in other places. When naming the classes, it is recommended to add the name of the project. For example, I have a project whose name is Cherry, so all classes are CherryLeaks. CherryVulns, etc., will know at a glance in the reivew code and the process of writing that this class represents the data.
If there are many repetitive operations against Models, it is recommended that you add a separate manager to the current table and implement the corresponding method.
In addition, there are some suggestions that can be made according to the actual situation:
Types such as foreign keys are not recommended
Add is_deleted,created_time,updated_time fields to each table
Make good use of the index
2.3 View
The View section should be the core part, and most of the business logic should be here. It is also recommended that all View with similar functions be placed in the same file. And put it in a package called controller or view to facilitate future maintenance and development. For example, dealing with project-related routes, all placed in the controller/project.py.
Priority is given to some View classes built into Django, such as ListView,TemplateView. If you need to implement View yourself, it is recommended to use Class-based view to encapsulate different request methods into different methods for future maintenance.
2.4 Template
For template files, the best way is to cut different pages and functions into different template files, and store them by folder according to the name of Applicatio, so that you can quickly find the corresponding template file from each Application during later maintenance.
In addition, it is highly recommended to use the inheritance function of the template, all pages are inherited from the parent template, and use a variety of block to expand the page. The block name of each location is defined in the parent template, which is covered by the child template. It is recommended that you use a popular and short name for each block, such as sidebar,script,header,main_content,page_title,page_description, etc.
For general-purpose features, such as comment boxes, consider storing them in a separate file and loading them through {% include 'filename.tpl.html'%} where needed. It is important to note that if you need to use both extends and include instructions, be sure to use them in block, otherwise it will not work. The following examples are invalid:
It should be used as follows:
PART 3. Code style 3.1 docstring
Because the Python language is so flexible, we often forget the parameter types of certain methods or return value types when we write them. At this time, we need docstring to clearly label the information of each method, so as to facilitate the development and maintenance of others. If you are using PyCharm, you can refer to this link, writing PyCharm can automatically complete docstring.
3.2 multiple return values
In many cases, our method needs to return multiple values to the caller or to the front end through JSON. If the data is returned indiscriminately, it will lead to confusion in the development, and in the end, we have no idea what the method returned.
A better practice is to agree on the format of the return, and for returning it to the caller, simply return tuple and specify the meaning of each value in docstring. In many cases, in addition to returning results, we also need to return an err to indicate whether there is a problem or exception in the process of processing the data. In general, there are several methods available:
Throw an exception through raise
Returned via multiple return values, such as err, result = func ()
Returned through a property in the class, such as instance = Class (); err = instance.error_message
These three methods have advantages and disadvantages and need to be selected according to the actual situation of the project. No matter which method is used, it needs to be unified throughout the project and should not be mixed as much as possible.
For the JSON returned to the front end, it needs to be a little more complicated, with at least 2 fields returned:
Code is the status code returned by this call, which is agreed upon according to the actual situation. Message is the readable information of the status code and is used by the developer to debug or notify the user. Data is the actual returned data information, and this field may not be needed in many cases, and the specific field format needs to be agreed upon again according to the actual situation.
PART 4. Routing organization
Elegant and simple routing ensures project quality and reduces maintenance costs.
4.1 routing system
Django has a powerful routing system and routing algorithm, which can meet a variety of business needs, and the configuration is flexible and simple. Each routing profile is a mapping from URL PATH to function/class. All can be set up on their own, completely free from the framework or other restrictions. You can refer to this section of the document about the route finding strategy of Django when processing requests.
In configuring routing, you can enclose some variables in angle brackets for later use. You can use some "Path Converters" in angle brackets to specify variable types, such as str, int, slug, uuid, path. A complete URL routing file looks like this:
In addition, regular matching can be set in the route through re_path:
Sometimes, you may want to add a default route to some URL, such as returning a default page when visiting / blog/ and returning a specified page number when visiting / blog/page, which can be configured as follows
4.2 routes include
With the continuous expansion of the project, more and more routes will be used, so Django provides a mechanism for routing, so it is convenient for us to organize routes in different App. Let's look at a simple example:
In this example, all the community/* requests are parsed by aggregator.urls. Similarly, all contact/* requests are handled by another routing module. If you do not have so many Application in your project and still want to manage routes through include, you can use the following methods:
4.3 Namespace
In general, each Django project consists of multiple App. If you put all the App routes in the URLCONF_ROOT, this file will become more and more difficult to maintain over time. Moreover, routes with the same name may be used in different App, resulting in conflicts. To solve these problems, we can solve these problems by using "route inclusion" and "namespace", especially if you are maintaining an App that can be reused, in order to ensure that the route is unique, namespaces are particularly important.
There are usually two types of namespaces: Application namespace and Instance namespace, such as index routes where admin:index represents the admin namespace. For more information on this section, please refer to the official documentation.
Application Namespace is easy to understand and refers to namespaces at the application level, which are generally organized as follows:
Instance Namespace refers to the instance-level namespace, which is often used when an App is instantiated multiple times. In order to distinguish each instance, Instance Namespace needs to be introduced. Let's take a look at the examples in the official documentation:
You can see that the two routes author-polls and publisher-polls actually contain the same route, but specify a different namespace, which is the Instance-level namespace, that is, the namespace of the object currently being accessed. When different users visit different URL, they will get different namespaces. For example, both tourists and administrators visit the pages pointed to by polls:index, but they will get completely different results due to different namespaces.
At this point, the study of "what is the Django development method" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.