day53 routing layer - known unknown Packet reverse DNS namespace pseudo-static routing distributed virtual environment view layer views

Brief introduction

/ Index and / index /? Id = 1 is equivalent to only match match when you access to index

There? And & get method is to carry data

Parameter Size get request carries the limited

request.GET get all the data get request to carry on such index back
? id = 1 & username = bitten

Django request lifecycle

Built between tables and table relationships
library management system, for example
books table
books and publishing houses are built-to-many foreign key field in the books table
books and authors are many-to-many relationships require a third record

Press table
of table

Table django orm build relationships between tables and
many ForeignKey (to = 'Publish')

One OneToOneField (to = 'AuthorDetail')

Many to many ManyToManyField (to = 'Author')

Note:
The first two keywords will automatically back again _id field plus
the last key does not produce the actual field just tell django orm automatically create a third table

Layer routing layer url

url()The first parameter method which, in fact, is a regular expression

Once the previous regular matched to the content will not continue down the match but directly performs the function corresponding to the view down

Because of the above characteristics, when your project is particularly large, you need to consider the people writing the order and adjust url, otherwise the situation is likely to arise url disorder

Solution: behind the increase/

Why, when you visit obviously did not enter the final surface /but there will be a behind the address bar /?

Because the order is: first match will not increase /, if not match, the status code returned is 301, plus a second time will /try, if found status code is 200, if it can not find it will complain

If you want to cancel this mechanism, does not want the second match, settings can be specified in the configuration file

APPEND_SLASH = False  # 该参数默认是True

Packet

If you do not add ^, that is not prescribed to the beginning, then your request as long as the end of the test, the test will be able to access

Preceded by ^ is also flawed, because there is no defined end, it took $ prescribed end

Finally turned

url(r'^test/$', views.test),

If you want to have a Home

That is

url(r'^$', views.home),

If you want to do 404 pages, put the following sentence last (to know on the line, generally do not do so)

url(r' ', views.home),

Unknown group

url(r'^test/([0-9](4))$', views.test),

The view itself when the route matches the regular expression parentheses will be matched to the content as the location parameter

test(request,2019)

Famous grouping

url(r'^test/(?P<year>\d+)/', views.test)

Matching the packet will be known in parentheses content, used as a key parameter passed to the view function

test(requesr,year=2019)

Can you mix unnamed famous?

:不能

This is an example, the following will complain

url(r'^test/(\d+)/(?P<year>\d+)/', views.test),  # 这是会出错的

A packet but at the same, a plurality of, for example:

Support for multiple unnamed group

url(r'^test/(\d+)/(\d+)/', views.test),

Support for multiple well-known group

url(r'^test/(?P<year>\d+)/(?P<xx>\d+)/', views.test),

Reverse lookup

Nature: in fact, to give you a return address to return the corresponding url

1. The view function and give a correspondence relationship url aliases

url(r'^index/$',views.index,name='kkk')

Note that in the same app, alias can not be repeated! ! !

2. To achieve the reverse analysis

Back-end reverse lookup

The rear end may be reversed corresponding to the parsed reverse at an arbitrary position by url

from django.shortcuts import render,HttpResponse,redirect,reverse
reverse('kkk')      

Front-end reverse lookup

{% url 'kkk' %}

With the string does not need to directly import import point because the importlib

无名分组反向解析
url(r'^index/(\d+)/$',views.index,name='kkk')
后端反向解析
        reverse('kkk',args=(1,))  # 后面的数字通常都是数据的id值
前端反向解析
        {% url 'kkk' 1%}   # 后面的数字通常都是数据的id值

Route distribution

When your django projects, especially large when the routing function corresponds with a view particularly special relationship
then your total routing code is too long and difficult to maintain urls.py

Each application can have its own urls.py, static folder, templates folder (******)

It is more than the above conditions can be achieved, and many groups developed after the development is completed we just need to create an empty django based project
and then people come in all the registered app developed to achieve a route distribution routes do not match the overall route ( after I came just to give you distribute to the corresponding app in)

Particularly when special view function in your application when you can build a folder views according to which segmentation features to build a different py files (important ------ ------)

    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^app01/',include('app01.urls')),
        url(r'^app02/',include('app02.urls')),
    ]

Namespace (understand)

More app from the same alias at this time does not automatically identify applications with the prefix reverse lookup
occurs if you want to avoid this problem

Mode 1 (which is relatively cumbersome, but may clear logic?):

The total route

url(r'^app01/',include('app01.urls',namespace='app01'))
url(r'^app02/',include('app02.urls',namespace='app02'))

When the back-end analytic

reverse('app01:index')
reverse('app02:index')

When the front end parsed

{% url 'app01:index' %}
{% url 'app02:index' %}

Mode 2 (this time to stay simple dessert named):

Since when do not conflict alias when you can play in general it is generally recommended to use an alias name as a prefix

name = 'app01_index'
name = 'app02_index'

Pseudo-static

Method: In the url matched in the index / index.html into the

Static pages: the data is written to die the same years

Pseudo-static pages designed to increase Baidu and other search engine seo efforts query

All search engines are actually a huge crawler

Website optimization related by pseudo-static can really increase the probability of your website being queried out
but then how to optimize the RMB players also arrived, but (the most effective thing to Baidu advertising costs)

Virtual Environment

Under normal circumstances we will give each project module with the required items not needed and will not install
a virtual environment tailored for each project is similar to the interpreter environment

Each create a virtual environment, and you would like to download a new python interpreter

Django version differences

Django 1.X and Django 2.X difference

        路由层1.X用的是url
        而2.X用的是path

Django 2.X the default path, path that precisely matches the received

Django 1.X using the first parameter is received url regex

When you use 2.X not used, 2.X also called re_path, re_path 1.X and usage of consistent url

Although 2.X the path does not support regular expressions, but it provides five default converter

        1.X版本的url和2.X版本的re_path分组出来的数据都是字符串类型
        默认有五个转换器,感兴趣的自己可以课下去试一下
        str,匹配除了路径分隔符(/)之外的非空字符串,这是默认的形式
        int,匹配正整数,包含0。
        slug,匹配字母、数字以及横杠、下划线组成的字符串。
        uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。
        path,匹配任何非空字符串,包含了路径分隔符(/)(不能用?)

path Usage example

        path('index/<int:id>/',index)  # 会将id匹配到的内容自动转换成整型

Also supports custom converter

        class FourDigitYearConverter:  
        regex = '[0-9]{4}'  
        def to_python(self, value):  
            return int(value)  
        def to_url(self, value):  
            return '%04d' % value  占四位,不够用0填满,超了则就按超了的位数来!
        register_converter(FourDigitYearConverter, 'yyyy')  
        
        urlpatterns = [  
                path('articles/2003/', views.special_case_2003),  
                path('articles/<yyyy:year>/', views.year_archive),  
                ...  
            ]  

View views layer

1. White will be three axes
① HttpResponse
② the render
③ the redirect
Django view function must give returns an HttpResponse

In fact, render and redirect are inherited from HttpResponse

Separate front and rear ends
a front end a human stem (distal turn into a customized objects)
the JSON.stringify () json.dumps ()
the JSON.parse () json.loads ()
the rear end of another dry (rear end with Python Dictionary)
As far as the data exchange, json format generally are used in
the back-end is only responsible for generating the interface front-end interface to call the dictionary to get a big
backend interfaces just need to write a document which describes in detail dictionary transmission of information and arguments

2.JsonReponse

from django.http import JsonResponse
def index(request):
        data = {'name':'我从未见过如此厚颜无耻之人','password':123}
        l = [1,2,3,4,5,6,7,8]
        # res = json.dumps(data,ensure_ascii=False)
        # return HttpResponse(res)
        # return JsonResponse(data,json_dumps_params={'ensure_ascii':False})
        return JsonResponse(l,safe=False)  # 如果返回的不是字典 只需要修改safe参数为false即可

3. Upload file

Matters form form to upload files Note
1.enctype need FormData changed from the default urlencoded
2.method needs changed from the default post GET
(yet to be considered is the need to submit a request to post comments csrf middleware configuration file )

If the form form to upload the file back-end data file need to get in there request.FILES rather POST

request.method
request.GET
request.POST
request.FILES
request.path  # 只回去url后缀 不获取?后面的参数
request.get_full_path()  # 后缀和参数全部获取

FBV and CBV (--- Important ---)

Guess you like

Origin www.cnblogs.com/PowerTips/p/11536573.html