First, the routing system
1. Each routing rule corresponds to a function in the view
| 123 |
url(r‘^index/(\d*)‘, views.index),url(r‘^manage/(?P<name>\w*)/(?P<id>\d*)‘, views.manage),url(r‘^manage/(?P<name>\w*)‘, views.manage,{‘id‘:333}), |
2, according to the app to classify the rules
| 1 |
url(r‘^web/‘,include(‘web.urls‘)), |
The routing system in Django differs from the framework of other languages in that the URL for each request in Django has a route map so that the request can be handed to the function in the view for processing. Most other web frameworks are a route map for a class of URL requests, which makes the routing system concise.
A dynamic routing system demo for Django is developed through the reflection mechanism:
Second, the middleware
Middleware_classes = (
' Django.contrib.sessions.middleware.SessionMiddleware ',
' Django.middleware.common.CommonMiddleware ',
' Django.middleware.csrf.CsrfViewMiddleware ',
' Django.contrib.auth.middleware.AuthenticationMiddleware ',
' Django.contrib.auth.middleware.SessionAuthenticationMiddleware ',
' Django.contrib.messages.middleware.MessageMiddleware ',
' Django.middleware.clickjacking.XFrameOptionsMiddleware ',
' Django.middleware.security.SecurityMiddleware ',
' Middleware.middle1.mmm ',
' Middleware.middle1.xxx ',
)
Process_request_list = []
Process_view_list = []
Process_response_list = []
Process_exception_list = []
For class in middleware_classes:
obj = Class ()
There are process_request methods in if obj:
Process_request_list.append (Obj.process_request)
For I in Process_request_list:
I ()
For I in Process_view_list:
I ()
The function in views
For I in Process_response_list:
I ()
Obj.process_request
Three, Model (*)
1. Create a table
2. Operation table Data
Django uses a new approach, namely: Relational object Mapping (object relational Mapping, or ORM).
Php:activerecord
Java:hibernate
C#:entity Framework
Django follows the code Frist principle of automatically generating database tables based on classes defined in your code.
1, create the model, then you can create a database table according to the model
| 123456 |
from django.db import models class userinfo(models.Model): name = models.CharField(max_length=30) email = models.EmailField() memo = models.TextField() |
2. Connecting table relationship:
- A pair of more, models. ForeignKey (Colordic)
- One on one, models. Onetoonefield (Onemodel)
- Many-to-many, authors = models. Manytomanyfield (Author)
Application Scenarios:
- One to one: when you create a row of data in a table, there is a single-selection drop-down box (the contents of the drop-down box are used once and disappear).
For example, a table containing 10 columns of data holds relevant information, and after a period of time, 10 columns do not meet the requirements and need to add 5 columns of data to the original table.
- One-to-many: when a row of data is created in a table, there is a single-selection drop-down box (which can be selected repeatedly).
For example: When creating user information, you need to select a user type "ordinary user" "Gold user" "Platinum User" and so on.
- Many-to-many: a row of data is created in a table, and there is a drop-down box that you can choose from.
For example, to create user information, you need to specify multiple hobbies for the user.
3. Database operation
- Add: Create an instance and call save
- Update: A. Get instance, then Sava;b.update (Specify column)
- Delete: A. Filter (). Delete (); B.all (). Delete ()
- Get: A. Single =get (id=1); b. all = All ()
- Filtering: Filter (name= ' xxx '), filter (name__contains= ");(id__in = [[+]]);
Icontains (case-insensitive like), StartsWith and EndsWith, and range (sqlbetween query) ' GT ', ' in ', ' isnull ', ' endswith ', ' contains ', ' lt ', ' StartsWith ', ' iendswith ', ' icontains ', ' range ', ' istartswith '
- Sort: order_by ("name") =asc; order_by ("-name") =desc
- Return to article n-m: article n [0]; top two [0:2]
- Specify mappings: Values
- Quantity: Count ()
- Aggregation: From django.db.models import Min,max,sum Objects.all (). Aggregate (Max (' guest_id '))
- Raw SQL
| 123 |
cursor =connection.cursor()cursor.execute(‘‘‘SELECT DISTINCT first_name ROM people_person WHERE last_name = %s""", [‘Lennon‘])row =cursor.fetchone() |
Iv. Form (*)
1. User submitted data validation
2. Generate HTML tags
#!/usr/bin/env python#-*-coding:utf-8-*-ImportRe fromDjangoImportForms fromDjango.core.exceptionsImportValidationErrordefmobile_validate (value): Mobile_re= Re.compile (r'^ (13[0-9]|15[012356789]|17[678]|18[0-9]|14[57]) [0-9]{8}$') if notMobile_re.match (value):RaiseValidationError ('cell phone number format error')classPublishForm (forms. Form): User_type_choice=((0, U'Normal User'), (1, U'Advanced users'),) User_type= Forms. Integerfield (Widget=forms.widgets.select (choices=User_type_choice, Attrs={'class':"Form-control"})) title= Forms. Charfield (max_length=20, Min_length=5, Error_messages={'Required': U'title cannot be empty', 'Min_length': U'The title is a minimum of 5 characters', 'Max_length': U'title up to 20 characters'}, Widget=forms. TextInput (attrs={'class':"Form-control", 'placeholder': U'title 5-20 characters'}) Memo= Forms. Charfield (required=False, Max_length=256, Widgets=forms.widgets.textarea (attrs={'class':"Form-control No-radius",'placeholder': U'Detailed Description','rows': 3})) Phone= Forms. Charfield (validators=[Mobile_validate,], error_messages={'Required': U'The phone cannot be empty'}, Widget=forms. TextInput (attrs={'class':"Form-control", 'placeholder': U'Mobile phone number'})) Email= Forms. Emailfield (required=False, Error_messages={'Required': U'The mailbox cannot be empty','Invalid': U'Bad mailbox Format'}, Widget=forms. TextInput (attrs={'class':"Form-control",'placeholder': U'Email'}))defPublish (Request): RET= {'Status': False,'Data':"','Error':"','Summary':"'} ifRequest.method = ='POST': Request_form=PublishForm (Request. POST)ifrequest_form.is_valid (): Request_dict=Request_form.clean ()Printrequest_dict ret['Status'] =TrueElse: Error_msg=Request_form.errors.as_json () ret['Error'] =json.loads (error_msg)returnHttpResponse (Json.dumps (ret))
V. Cookies and Session
First, the operation of cookies
Gets the cookie:request. Cookies[key]
Set Cookie:response.set_cookie (Key,value)
Because cookies are stored on the client's computer, jquery can also manipulate cookies.
| 12 |
<script src=‘/static/js/jquery.cookie.js‘></script>$.cookie("list_pager_num", 30,{ path: ‘/‘}); |
Second, the Operation session
Get Session:request.session[key]
Set Session:reqeust.session[key] = value
Delete Session:del Request[key]
| 12345 |
request.session.set_expiry(value)*如果value是个整数,session会在些秒数后失效。* 如果value是个datatime或timedelta,session就会在这个时间后失效。* 如果value是0,用户关闭浏览器session就会失效。*如果value是None,session会依赖全局session失效策略。 |
See MORE:
https://docs.djangoproject.com/en/1.9/topics/http/sessions/
http://docs.30c.org/djangobook2/chapter14/
https://docs.djangoproject.com/en/1.9/ref/settings/#settings-sessions
Third, the application
| 1234567 |
def login(func): def wrap(request, *args, **kwargs): # 如果未登陆,跳转到指定页面 if request.path == ‘/test/‘: return redirect(‘http://www.baidu.com‘) return func(request, *args, **kwargs) return wrap |
python--18th Day Summary (Django Advanced)