Home Backend Development Python Tutorial In-depth understanding of Python's Django framework

In-depth understanding of Python's Django framework

Apr 03, 2018 pm 04:21 PM
django python frame

This article mainly introduces the Python code to implement the Django framework. The editor thinks it is quite good. Now I will share it with you and give it a reference. Let’s follow the editor and take a look.

1. URLconf

When the user accesses the URL through the browser to request the website, he finds the corresponding function through the URL for execution, and Django The url configuration in is configured in settings.py in the folder with the same name as the project

1, configuration

(1), test1/settings.py configuration file

settings.py has specified the url configuration through ROOT_URLCONF by default, pointing to the urls.py file under test1:


## (2), test1/ The configuration items in urls.py are as follows:


Note:

Perform inclusion configuration in test1/urls.py , create the corresponding urls.py in each application, and perform specific configurations in the urls.py file under each application.

Define the urlpartterns list and store the url() object. The name of this list is fixed.

2. The syntax of url definition

url() object is defined in the django.conf.urls package and consists of two syntax structures

(1), Syntax 1 : Contain, include the urls.py of other applications in the urls.py under the project folder with the same name

Create a urls.py file in the custom application to define url(), and then add the urls.py The custom urls.py is introduced in the urls.py under the folder. The purpose of this is to configure urls.py inside the application, so that the data is clearer and easier to maintain.

Introduce the syntax of booktest/urls.py into test1/urls.py

url(r'^',include('应用名称.urls')),
# 此处的urls指的是各自应用(booktest)中urls.py文件的名称,如果是urls.py,即为urls
Copy after login

(2), Syntax 2: Definition, specify the corresponding relationship between URL and view function

Create urls.py inside the respective applications and specify the corresponding relationship between the request address and the view. The format is as follows:

url(正则,'视图函数名称')
Copy after login

Example:

Create the url of the homepage in booktest/urls.py:

from django.conf.urls import url
from booktest import views
urlpatterns=[
    url(r'^$',views.index),
]
Copy after login

Note: It is recommended to use r in the regular part, which means that the string is not escaped, so you only need to write one \ in the regular expression. You cannot add a backslash at the beginning. It is recommended to add a backslash at the end, because the browser's URL is the same with or without adding \ at the end.

3. Obtain the parameter value carried in the url

The requested url is regarded as an ordinary python string and matches request parameters that do not include domain name, get or post, such as: The request address is as follows:

http://localhost:8080/detail/1?a=10

Among the above request addresses, the only strings that match the regular expression in the url() function are:

detail/

If you want to carry RESTFUL style parameters in the requested url, you need to use grouping in the regular expression of the url() function, that is, use the () sign, which is divided into: Positional parameters, keyword parameters.

Note: Do not mix the two parameter methods. Only one parameter method can be used in a regular expression.

(1) Positional parameters

Use the () sign directly and pass it to the view through the positional parameters

The regular expression in the url() function is written as:# The corresponding function writing in ##
url(r'^detail(\d+)/$',views.show_books),
Copy after login

views.py is:

def show_books(request, id):    # 此处获取的id为1
    return HttpResponse('show_books')
Copy after login

(2), keyword parameters

If keyword parameters are used, the regular expression in the url() function The expression grouping is to name each group

. For example, the accessed url is: http://localhost:8000/delete/1?a=10

The regular expression of the url() function The expression is written as:

url(r&#39;^delete(?P<id1>\d+)/$&#39;,views.show_book),
Copy after login

The function in views.py is written as:

def show_arg(request,id1):
    return HttpResponse(&#39;show %s&#39;%id1)
Copy after login

Note: If keyword parameters are used, Then the parameter name of the corresponding function in views.py must be consistent with the name of the group in the regular expression, otherwise an error will be reported. 2. View

1. What is a view

A view is a function in python. Views are generally defined in the "application/views.py" file, which is this file. Example "booktest/views.py".

The view must return an HttpResponse object or sub-object as a response. The response can be the HTML content of a web page, a redirect function, or a 404 error, etc.

The first parameter of the view must be an HttpRequest object. Other parameters may also include: keyword parameters or positional parameters (either one of the two)

                                                                         Built-in error view

(1), built-in error view

Django has built-in views for handling HTTP errors. The main errors and views include:

404: page not found View

          500: server error View

If you want to see the error view instead of debugging information, you need to modify the DEBUG item configuration information in the "test/settings.py" file


(2)、404错误及视图

将请求地址进行url匹配之后,没有找到匹配的正则表达式,则调用404视图,这个视图会调用404.html模版进行渲染,视图传递变量request_path给模版,表示导致错误的URL。

在templates中创建404.html

<html>
<head>
    <title></title>
</head>
<body>
找不到了
<hr/>
{{request_path}}
</body>
</html>
Copy after login

在浏览器中输入如下网址:

http://localhost:8000/test/

运行效果如下:


(3)、500错误及视图

        在视图中代码运行报错将会发生500错误,调用内置错误视图,使用templates/500.html模版进行渲染。

三、HttpRequest对象

1、HttpRequest对象

        服务器接收到HTTP请求后,会根据报文创建HttpRequest对象,这个对象不需要我们手动创建,直接使用服务器构建好的对象即可。视图函数中的第一个参数必须是HttpRequest对象,该对象类定义在django.http模块中。

2、属性

        path:一个字符串,表示请求的页面的完整路径,不包含域名和参数部分。

        method:一个字符串,表示请求使用的HTTP方法,常用值包括:'GET'、'POST'。

                在浏览器中给出地址发出请求采用get方式,如超链接。

                

                在浏览器中点击表单的提交按钮发起请求,如果表单的method设置为post则为post请求。

        encoding:一个字符串,表示提交的数据的编码方式。

                如果为None则表示使用浏览器的默认设置,一般为utf-8。

                这个属性是可写的,可以通过修改它来修改访问表单数据使用的编码,接下来对属性的任何访问将使用新的encoding值。

        GET:QueryDict类型对象,类似于字典,包含get请求方式的所有参数。

        POST:QueryDict类型对象,类似于字典,包含post请求方式的所有参数。

        FILES:一个类似于字典的对象,包含所有的上传文件。

        COOKIES:一个标准的Python字典,包含所有的cookie,键和值都为字符串。

        session:一个既可读又可写的类似于字典的对象,表示当前的会话,只有当Django 启用会话的支持时才可用,详细内容见"状态保持"。

The above is the detailed content of In-depth understanding of Python's Django framework. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles