In-depth understanding of Python's Django framework
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:
url(r'^',include('应用名称.urls')), # 此处的urls指的是各自应用(booktest)中urls.py文件的名称,如果是urls.py,即为urls
url(正则,'视图函数名称')
from django.conf.urls import url from booktest import views urlpatterns=[ url(r'^$',views.index), ]
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 parametersUse the () sign directly and pass it to the view through the positional parametersThe regular expression in the url() function is written as:# The corresponding function writing in ##url(r'^detail(\d+)/$',views.show_books),
views.py is:
def show_books(request, id): # 此处获取的id为1 return HttpResponse('show_books')
(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'^delete(?P<id1>\d+)/$',views.show_book),
The function in views.py is written as:
def show_arg(request,id1): return HttpResponse('show %s'%id1)
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>
在浏览器中输入如下网址:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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.

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.

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.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.
