directory
[TOC]
- Course Features:
- Learning is difficult and requires understanding and memorizing most of the content
- A large number of files can be confusing
- The learning phase focuses on using the framework, while the working phase focuses on implementing the business logic
- Strong comprehensive application, little practice
Introduction to the Django framework
-
Released in 2005, an open source Web framework written in Python
-
In its early days Django did news and content management
-
A heavyweight Python Web framework, Django comes with most of the usual components
- The basic configuration
- Routing system
- Native HTML template system
- View the view
- Model, database connection, and ORM database management
- The middleware
- Cookie & Seesion
- paging
- Database background management system admin
-
Django USES
- Website backend development
- Wechat public account, wechat small program and other background development
- Background server development based on HTTP/HTTPS protocol
- Tornado/gevent 4 layers
- Online voice/image recognition server
- Online third-party authentication server, etc
-
Django version
- Latest version :2.2.x
- Current teaching version :1.11.8
-
Django’s website
- Official website: www.djangoproject.com
- Chinese Document (third party):
- yiyibooks.cn/
- djangobook.py3k.cn/
- Django’s offline documentation
- Unzip packet
Django docs - 1.11 - en. Zip
- Open it in a browser
Django docs - 1.11 - en/index. HTML
- Unzip packet
Django installation
-
View the installed version
>>> import django >>> print(django.VERSION) (1.11.8.'final'.0) Copy the code
-
The installation
- Online installation
$ sudo pip3 install django
Install the latest version of Django- or
$sudo pip3 install Django [== version]
Install the specified version of Django- Such as:
$ sudo pip3 install django==1.11.8
- Offline installation
- Download the installation package:
- Installing an Offline package
$tar - XVF Django - 1.11.8. Tar. Gz
$CD Django - 1.11.8
$ sudo python3 setup.py install
- Use wheel for offline installation
- Download the installation package:
Pip3 download -d /home/tarena/django_packs Django ==1.11.8
- Installing an Offline package
- $pip3 install Django – 1.11.8. WHL
- Download the installation package:
- Online installation
-
Django’s uninstall
-
$ pip3 uninstall django
-
Django development environment
- Django 1.11.x supports Python 2.7, 3.4, 3.5, and 3.6 (long-supported version LTS)
- Note: Django 1.11.x does not support Python 3.7
Django Framework Development
Instructions to create a project
-
$django-admin startProject Specifies the project name
-
Such as:
- $ django-admin startproject mysite1
-
run
$ cd mysite1 $ python3 manage.py runserver #or $ python3 manage.py runserver 5000 # specify that only the host can access the host using the 5000 port 127.0.0.1 Copy the code
The directory structure of a Django project
-
Example:
$ django-admin startproject mysite1 $ tree mysite1/Mysite1 / ├ ─ ─ the manage. Py └ ─ ─ mysite1 ├ ─ ─ just set py ├ ─ ─ Settings. Py ├ ─ ─ urls. Py └ ─ ─ wsgi. Py 1 directory, 5 filesCopy the code
-
Project directory structure parsing:
- manage.py
- This file is the main program for project management and is used to manage the modality of the development run of the entire project during the development phase
manage.py
Contains project management subcommands such as:python3 manage.py runserver
Start the servicepython3 manage.py startapp
Create anpython3 manage.py migrate
Database Migration.
- Mysite1 Project package folder
- The home folder of the project package (defaults to the project name)
-
__init__.py
- Package initialization file, which is automatically run when the project package is imported
-
wsgi.py
- WSGI is the Web Server Gateway Interface that connects to NGINx
- The configuration file of the WEB service gateway interface is used only for project deployment
-
urls.py
- The basic routing profile of the project, through which all dynamic paths must first be matched
-
settings.py
- The Django project configuration file, which contains global variables that pass parameters for running the Django framework
- Setting. py configuration file, automatically called when starting the service,
- Some custom variables can also be defined in this configuration file for global scoped data passing
http://127.0.0.1:8000/admin/
- manage.py
-
Settings. py file introduction
-
BASE_DIR
- The absolute (dynamically calculated) path used to bind the current project to which all files can follow
-
DEBUG
- Used to configure the enabled mode for a Django project. Values:
- True: used in the development environment
Debug mode
(In development) - False indicates that the current project is running in
In production environment
(No debugging enabled)
- True: used in the development environment
- Used to configure the enabled mode for a Django project. Values:
-
ALLOWED_HOSTS
- Set the list of network addresses allowed to access the project. The value is as follows:
- [] Empty list: indicates only
127.0.0.1
.localhost
Access to this project - [‘*’] : indicates that any network address can access the current project
- [‘192.168.1.3’, ‘192.168.3.3’] indicates that only two hosts can access the current project
- Note:
- To enable other hosts on the LAN to access the host, use the following boot mode:
- [] Empty list: indicates only
Python3 manage. Py runserver then executes 0.0.0.0:5000
All hosts can be accessed through port 5000ALLOWED_HOSTS = ['*']
)
- Set the list of network addresses allowed to access the project. The value is as follows:
-
INSTALLED_APPS
- Specifies the list of applications installed in the current project
-
MIDDLEWARE
- Used to register middleware
-
TEMPLATES
- Configuration information used to specify the template
-
DATABASES
- The configuration information used to specify the database
-
LANGUAGE_CODE
- Used to specify the language configuration
- Values:
- English:
"en-us"
- English:
"zh-Hans"
- English:
-
TIME_ZONE
- Specifies the current server time zone
- Values:
- World Standard Time:
"UTC"
- China time zone:
"Asia/Shanghai"
- World Standard Time:
-
ROOT_URLCONF
- Use the root URL configuration ‘mysit1.urls’
- Such as:
ROOT_URLCONF = 'mysite1.urls'
Note: This module can be imported and used from Django. conf import Settings
-
The URL is introduced
-
Url is a Uniform Resource Locator
-
Function:
- The address used to represent a resource on the Internet.
-
Description:
- Every file on the Internet has a unique URL that contains information indicating where the file is and what the browser should do with it.
-
The general syntax format of a URL is:
-
www.djangoproject.com/download/
protocol :// hostname[:port] / path [?query][#fragment] Copy the code
-
Such as:
http://tts.tmooc.cn/video/showVideo?meuId=657421&version=AID201908#s Copy the code
-
Description:
- Protocol
- HTTP Access to the resource through HTTP. format
HTTP://
- HTTPS Access the resource using secure HTTPS. format
HTTPS://
- File resources are files on the local computer. Format:
file:///
- .
- HTTP Access to the resource through HTTP. format
- Hostname (hostname)
- It is the domain name System (DNS) host name, domain name, or IP address of the server on which resources are stored.
- Port (Port number)
- An integer, optional. If omitted, use the default port of the scheme.
- Each transport protocol has a default port number. For example, HTTP has a default port number of 80. HTTPS 443
- Path (Routing address)
- A string separated by zero or more slashes (/) to indicate the address of a directory or file on a host. The routing address determines how the server handles the request
- The query (query)
- This parameter is used to pass parameters to a dynamic web page. Multiple parameters can be separated by ampersand (&), and the name and value of each parameter are separated by =.
- Fragment (information)
- A string that specifies a fragment in a network resource. For example, if there are multiple definitions in a web page, you can use fragment to locate a specific definition.
- Note: [] represents the content can be omitted
- Protocol
View function
-
View functions are functions that receive a browser request and return data via an HttpResponse object. This function accepts the browser request and returns the corresponding content to the browser based on the business logic
-
The syntax format for the functions handled by the view:
def xxx_view(Request [, other parameters...]) : returnHttpResponse objectCopy the code
-
Parameters:
- Request is used to bind an HttpRequest object to obtain browser parameters and data
-
Example:
- View handler function
views.py
# file: < project name >/views.py from django.http import HttpResponse def page1_view(request) : html = "
This is page 1
" return HttpResponse(html) Copy the code
- View handler function
Route configuration in Django
- Settings. In py
ROOT_URLCONF
Specifies the file location of the main routing configuration list, URlPatterns - Urls.py main routing profile
# file: < project name >/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), ... # Configure the main route ] Copy the code
Urlpatterns is a list of routing-view function mappings that are determined by the URL function
- The url () function
- Describes the mapping between routes and view functions
- The module
from django.conf.urls import url
- Grammar:
- url(regex, views, name=None)
- Parameters:
- Regex: a string, matching the request path, can be a regular expression
- Views: Specifies the name of the view processing function corresponding to the path
- Name: specifies an alias name for an address. It is used for reverse address resolution in the template
The r before each regular expression represents the unescaped original string
- practice
- Create a small website:
- Enter the url: http://127.0.0.1:8000, in the webpage output: this is my home page
- Input url: http://127.0.0.1:8000/page1, in a web page output: this is the page number is 1
- Enter the url: http://127.0.0.1:8000/page2, in a web page output: this is the page number is 2
Note: The re for the home route is r’^$’.
- thinking
- /page3 /page4 …. /page100
- How to establish the above one hundred web pages?
- Create a small website:
Routing and view functions with grouping
-
Within view functions, you can use regular expression grouping () to extract arguments and pass them to view functions using function positional arguments
-
A group indicates a parameter. Multiple parameters need to be grouped and separated by slashes
-
- http://127.0.0.1:8000/year/2018
- http://127.0.0.1:8000/year/2019
- http://127.0.0.1:8000/year/???? # 4 digits
-
-
Practice:
-
Define a route in the following format:
- http://127.0.0.1:8000/ Integer/Operation string/integer
-
Data is extracted from the route and returned to the browser
-
Such as:
Input: 127.0.0.1:8000/100 / add / 200 page displays results: 300 input: 127.0.0.1:8000/100 / sub / 200 page displays results: - 100 type: 127.0.0.1: the mul / 200/8000/100 page displays results: 20000Copy the code
-
Routing and view functions with named groups
-
You can use named groups (capture groups) in regular expressions for urls
-
Description:
- Within view functions, you can group them using regular expressions
(? P<name>pattern)
The arguments are extracted and passed to the view function using the function keyword
- Within view functions, you can group them using regular expressions
-
Example:
- Routing profile
# file: < project name >/urls.py The following example matches # http://127.0.0.1:8000/person/weimingze/35 # http://127.0.0.1:8000/person/shibowen/29 # http://127.0.0.1:8000/person/xiaowei/9 urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^person/(? P
\w+)/(? P < age > \ d {1, 2}) ' ,views.person_view), ] Copy the code
- Routing profile
-
Practice:
- Visit address:
- http://127.0.0.1:8000/birthday/ four Numbers/one or two/one or two digits
- http://127.0.0.1:8000/birthday/ one or two digits/one or two digits/four digits
- Final output: date of birth: xx, XX, XXXX
- Such as: input url: http://127.0.0.1:8000/birthday/2015/12/11 is shown as: birthday: on December 11, 2015 input url: http://127.0.0.1:8000/birthday/2/28/2008 is shown as: the birthday is: on February 28, 2008
- Visit address:
-
PyCharm community edition debugs methods for Django projects
- Add your own modal configuration
- Select Add Configuration…
- Click on the
+
Add a configuration of your own- Select the main module location of the running project manage.py
- Add the runServer command-line argument
- Add your own modal configuration
HTTP request and response
- Requests refer to data sent from the browser to the server over HTTP
- A response refers to the data that the server receives and processes the request before sending back to the browser
The HTTP request
-
According to the HTTP standard, HTTP requests can use multiple request methods.
-
HTTP1.0 defines three request methods: GET, POST, and HEAD (the most common)
-
HTTP1.1 adds five new request methods: OPTIONS, PUT, DELETE, TRACE, and CONNECT.
-
HTTP1.1 request details
The serial number methods describe 1 GET Requests the specified page information and returns the entity body. 2 HEAD Similar to a GET request, except that there is no concrete content in the response returned, which is used to retrieve the header 3 POST Submit data to a specified resource for processing requests (such as submitting a form or uploading a file). The data is contained in the request body. POST requests may result in the creation of new resources and/or the modification of existing resources. 4 PUT Data transferred from the client to the server replaces the contents of the specified document. 5 DELETE Asks the server to delete the specified page. 6 CONNECT Reserved in HTTP/1.1 for proxy servers that can pipe connections. 7 OPTIONS Allows clients to view server performance. 8 TRACE The command output displays the requests received by the server for testing or diagnosis. -
The HttpRequest object
- The first argument to the view function is an HttpRequest object
- After receiving an HTTP request, the server creates an HttpRequest object based on the request data packet
- The HttpRequest properties
- Path: indicates the requested routing information
- Path_info: URL string
- Method: A string representing the HTTP request method. Common values: ‘GET’, ‘POST’
- Encoding: Indicates the encoding method of the submitted data
- None indicates that the browser’s default setting is used, typically ‘UTF-8’.
- This property is writable and can be modified to modify the encoding used to access the form data, and any subsequent access to the property will use the new Encoding value
- GET: QueryDict Queries dictionary objects that contain all data for GET requests
- POST: QueryDict dictionary query object that contains all data in the POST request
- FILES: dictionary-like object that contains information about all uploaded FILES
- COOKIES: Python dictionary that contains all COOKIES with strings of keys and values
- Session: dictionary-like object representing the current session,
- Body: string, the content of the request body (POST or PUT)
- Environ: A character string containing information about environment variables that the client is running
- Scheme: Request protocol (‘ HTTP ‘/’ HTTPS ‘)
- Request.get_full_path () : indicates the full path of the request
- Request.get_host () : the requested host
- Request.meta: Metadata in the request (headers)
- Request. META[‘REMOTE_ADDR’] : Client IP address
The HTTP response
-
When a visitor visits a web page, the visitor’s browser makes a request to the server where the page is located. When the browser receives and displays a web page, the server on which the web page is located returns a header containing an HTTP status code in response to the browser’s request.
-
The HTTP Status Code is HTTP Status Code.
-
The following are common HTTP status codes:
- 200 – Request successful
- 301 – Resources (web pages, etc.) are permanently transferred to another URL
- 404 – Requested resource (web page, etc.) does not exist
- 500 – Internal server error
-
HTTP status code classification
-
The HTTP status code consists of three decimal digits. The first decimal digit defines the type of the status code, and the second two digits do not classify. HTTP status codes are classified into five types:
classification Classification description 1 * * Message, the server receives the request and requires the requester to proceed with the operation 2 * * Success, the operation is received and processed successfully 3 * * Redirect, requiring further action to complete the request 4 * * Client error, request contains syntax error or request cannot be completed 5 * * Server error. The server encountered an error while processing the request
-
-
HttpResponse in Django:
-
Constructor format:
HttpResponse(Content = response body, content_type= response body data type, status= status code)
-
Function:
- Returns the response to the client browser, along with the response body content
-
Parameters:
- Content: Indicates the returned content.
- Status_code: returned HTTP response status code (default: 200).
- Content_type: Specifies the MIME type of the returned data (default: “text/ HTML “). The browser will display the data based on this property. If it is text/ HTML, the string will be parsed, if it is text/plain, a plain text will be displayed.
- Common content-types are as follows:
'text/html'
(Default, HTML file)'text/plain'
(Plain text)'text/css'
(CSS file)'text/javascript'
(JS file)'multipart/form-data'
(Submission of documents)'application/json'
(JSON transfer)
'application/xml'
(XML file)
Note: The keyword MIME(Multipurpose Internet Mail Extensions) refers to a Multipurpose Internet Mail extension type.
- Common content-types are as follows:
-
-
HttpResponse subclass
type role Status code HttpResponseRedirect Reset to ring 301 HttpResponseNotModified unmodified 304 HttpResponseBadRequest Bad request 400 HttpResponseNotFound There is no corresponding resource 404 HttpResponseForbidden Request denied 403 HttpResponseServerError Server error 500
Parameter transfer in GET mode
-
A GET request can pass data to the server as a Query String
-
URL format: XXX? Parameter name 1= value 1& Parameter name 2= value 2…
- Such as:
http://127.0.0.1:8000/page1?a=100&b=200
- Such as:
-
The server receives parameters
- Determine the value of request.method Determine whether the request is a GET request
if request.method == 'GET': Business logic for processing GET requestselse: Business logic for processing other requestsCopy the code
- Gets the data submitted by the client request GET
- grammar
request.GET['Parameter name'] # QueryDict request.GET.get('Parameter name'.'Default value') request.GET.getlist('Parameter name') # mypage? a=100&b=200&c=300&b=400 # request.GET=QueryDict({'a':['100'], 'b':['200','400'], 'c':['300']}) # a = request.GET['a'] # b = request.GET['b'] # Error Copy the code
- Situations in which get requests can be generated
- Address bar manual input, such as: http://127.0.0.1:8000/mypage? a=100&b=200
<a href=" address? Parameter = value & parameter = value ">
- Method in the form form is GET
<form method='get' action="/user/login">Name:<input type="text" name="uname"> </form> Copy the code
- grammar
- Determine the value of request.method Determine whether the request is a GET request
The size of the query string is limited by the browser (2048 bytes are not recommended).
-
Practice:
- Access the address: http://127.0.0.1:8000/sum? Start = integer &stop= integer &step Integer = word
- The output is sum(range(start, step, stop)) and:
- Such as:
- Input url: http://127.0.0.1:8000/sum? start=1&stop=101&step=1
- Result: 5050
- Input url: http://127.0.0.1:8000/sum? stop=101&step=2
- The following information is displayed: Result: 2550
- Input url: http://127.0.0.1:8000/sum? start=1&stop=101&step=2
- Result: 2500
-
Practice:
- Access the address: http://127.0.0.1:8000/birthday? Year = four-digit integer &month= integer &day= integer
- Final output: date of birth: xx, XX, XXXX
- Such as:
- Input url: http://127.0.0.1:8000/birthday? year=2015&month=12&day=11
- The date of birth is December 11, 2015
POST transfer parameters
- The client passes data to the server through POST requests such as forms, such as:
<form method='post' action="/login">Name:<input type="text" name="username">
<input type='submit' value='login'>
</form>
Copy the code
-
The server receives parameters
- Check whether the request is A POST request using request.method, for example:
if request.method == 'POST': Processes the data of the POST request and responds to itelse: Processes responses to non-POST requestsCopy the code
-
Receive client data in POST mode
- methods
request.POST['Parameter name'] # Request.post bind QueryDict request.POST.get('Parameter name'.' ') request.POST.getlist('Parameter name') Copy the code
-
Disable CSRF validation, or Django will reject POST requests from clients
-
Disable CSRF authentication
- Remove the MIDDLEWARE CsrfViewsMiddleWare from Settings. py
MIDDLEWARE = [ ... # 'django.middleware.csrf.CsrfViewMiddleware',. ]Copy the code
-
The name property of the form
-
When the Form control submits data, the name attribute and the corresponding value of the child label inside the form control are automatically searched, and these names and values are submitted as key-value pairs to the server-specific location specified by the action
-
The name tag controls that can be automatically collected in the form are
<input name='xxx'> <select name='yyy'></select> <textarea name='zzz'></textarea> Copy the code
- Such as:
<form action="/page1" method="POST"> <input name="title" type="text" value="Please enter"> <select name="gender"> <option value=1>male</option> <option value=0>female</option> </select> <textarea name="comment" rows="5" cols="10">Ps...</textarea> <input type="submit" value="Submit"> </form> Copy the code