Django-- routing, view

Routing layer:

A routing matching rules:

Since python is an interpreted language, from top to bottom to load the statement is executed, as is the regular matching rules, the first argument is a regular expression, fuzzy matching case will appear before and after the solution is applied and finally add $ ^ in .

urlpattrens = [
URLs (r'testadd / ', views.testadd)]

Home Routing: r '^ $', views.homepage mismatch return route: R & lt '', views.error
urlpattrens = [
URL (R & lt '^ testeadd / $', views.testadd)]

II. Unknown packets and known packets transmitted parameters

In Python regular expressions, regular expression syntax group name is (? P pattern) Which nameis the name of the group, patternit is the pattern to match.

1560134056788

The packet parentheses :( unknown regular expression matching to the content when the forming parameters corresponding automatically to the route, and then to the view function), can use a plurality of

The known packet parentheses :( regular expression matching to the content as the corresponding keyword parameters automatically to the route, and then to the view function), can use a plurality of

Famous and unknown groups can not be mixed together using a packet!

Three reverse lookup:

In use Django project, a common requirement is to get the final form of the URL for the embedded into the generated content (and views displayed to a user's URL, etc.) or for navigation processing server (redirection). There is a strong wish not to hard-code the URL (laborious, error-prone and not expandable) or design a special URL generation mechanism URLconf irrelevant, because it is easy to lead to a certain extent URL expired.

Reverse analysis by dynamically acquiring a corresponding route: Analytical reverse route acquired name, take different routes of the same alias.

URL where needed, for different levels, Django offers different tools for reverse lookup URL:

  • In the template: Use the url template tag.
  • In Python code: usingfrom django.urls import reverse()函数

urls.py

from django.urls import path,re_path
from app01 import views
urlpatterns = [
    re_path(r'^test/(?P<year>[0-9]{2})/(?P<month>[0-9]{2})/$',views.url_test,name='test'),
]

html

<a href="{% url 'test' 10 23 %}">哈哈</a>

View function:

Copy the code

from django.shortcuts import render, HttpResponse,redirect,reverse
def url_test(request,year,month):
    print(year)
    print(month)
    url=reverse('test',args=(10,20))
    print(url)
    return HttpResponse('ok')

Copy the code

Summary: 1 in the html code {% url "alias" Parameter%}

   2 in view of the function:

2.1 url=reverse('test')
2.2 url=reverse('test',args=(10,20))

When naming your URL patterns, make sure that the name does not use the name conflicts with other applications. If your URL pattern is called comment, and the other applications have a similar name, when you use this name in the template can not guarantee what will insert URL. Add a prefix in the URL name, such as the name of the application, it will reduce the possibility of conflict. We recommend myapp-commentinstead comment.

Four route distribution:

1 urls.py created in different app
2 total routing
-from the include django.conf.urls Import
-url (R & lt 'Blog ^ /', the include ( 'blog.urls')),
-url (R & lt' ^ app01 /',include('app01.urls')),
3 configure a route relationship urls different app's
focus on the total route, not add $ terminator

Five namespace:

- Sub Route: URL (R & lt '^ publish / $', views.publish, name = 'Test'),
- reverse analysis:
- View layer: url = reverse ( 'blog: test')
template layer: {% url 'app01: test'%}
generally do not use
the sub-route: url (r '^ publish / $', views.publish, name = 'app01_test'),

Six pseudo-static:

- Routing: url (r '^ book / (P? \ .html + D) ', views.book),
- Access: http://127.0.0.1:8000/book/4.html

Seven virtual environment:

When you create a virtual environment to create a project of choice

-1 pycharm was created:
-2 Crosstalk with the command:

django1.0 and django2.0 difference:

a first path parameter of 2.0 which does not support regular, precise matching

re_path urls and 1.0 are the same, the module to be imported repath

Django's default converter supports the following five:

  • str, in addition to the matching path separator ( /non-empty string) outside, which is the default.

  • int, matching positive integer, including 0.

  • Slug, matching the string of letters, numbers and bars, the underscore.

  • uuid, matching formatted uuid, as 075194d3-6885-417e-a8a8-6c931e272f00.

  • path, matches any non-empty string, comprising a path separator (/) (not?)

  • Registering Custom converter

    For some complex or require multiplexing, you can define your own converter. Converter is a class or interface, it requires three points:

    1.'regex` class attributes, string type

    2.to_python (Self, value) 方法,value是由类属性regex` matched to a string, it returns a specific Python variable values for the corresponding view 3.Django passed to the function.

    to_url(self, value)Methods, and to_pythoncontrary, value is the value of a specific variable Python, which returns a string, commonly used reverse url reference.

class FourDigitYearConverter:  
    regex = '[0-9]{4}'  
    def to_python(self, value):  
        return int(value)  
    def to_url(self, value):  
        return '%04d' % value  

Eight .FBV and CBV

CBV based view (Function base view) based on a function of view (Class base view) and class FBV

Copy the code

from django.views import View
class AddPublish(View):
    def dispatch(self, request, *args, **kwargs):
        print(request)
        print(args)
        print(kwargs)
        # 可以写类似装饰器的东西,在前后加代码
        obj=super().dispatch(request, *args, **kwargs)
        return obj

    def get(self,request):
        return render(request,'index.html')
    def post(self,request):
        request
        return HttpResponse('post')

Whether or CBV FBV is a view routing function and a correspondence in the routing layer.

IX. File Upload

1 html encoding format specified on page: enctype = "multipart / form-data"

2 view layer: request.FILES (dictionary), according to the name, the document taken out
-myfile = request.FILES.get ( 'file name') ---> to give the object file
3 for cyclic file object saved locally, file name: myfile.name

 print(request.FILES)
        print(type(request.FILES.get('file_name')))

        file_name=request.FILES.get('file_name').name
        from django.core.files.uploadedfile import InMemoryUploadedFile
        with open(file_name,'wb')as f:
            for i in request.FILES.get('file_name').chunks():
                f.write(i)

X. supplementary knowledge

1 Request objects --- GET, POST, method, body , FILES, META, path ( path only), get_full_path (get full path with data),
2 the HttpResponse objects ---> render, redirect, HttpResponse, JsonResponse ( Back json format)
3 reverse analysis ---> in the view layer: the nature of address in order to remove, by redirection; template layer: fetch address, in order to use the requesting
4 jsonResponse: jsonResponse (dic, json_dumps_params = { 'ensure_ascii ': False}) --- display Chinese coding problem

Guess you like

Origin www.cnblogs.com/njzy-yuan/p/11001634.html