Django-- routing layer, pseudo-static pages, virtual environment, view layer

 

Routing layer:

  When the route matches, the first argument is a regular expression, which means that according to the rules of regular match to match when the route matching, order routing is matched from top to bottom match, just to match one will execute the corresponding function, will not perform the following functions.

= urlpatterns [ 
    url ( ' ^ $ ' , views.home),   # Home route 
    url (r ' ^ ADMIN / ' , admin.site.urls), 
    url (r ' ^ the Test / ' , views.test), 
    url (R & lt ' ^ test_add / ' , views.test_add), 
    URL (R & lt ' ^ REG / ' , views.reg), 
    URL (R & lt '' , views.error),   # sites do not exist routing 
]
 # Note that the first parameter regular expression matching rules in accordance with the matching sequence from the down ,, after a match, the corresponding view function is executed immediately 

# If the routing particularly the case, to consider the position of the route is placed, so as to match other routes ( either replace the position of the route or the route with the route change)

  Unknown group

    The parenthesized regular expression matching to the content as the positional parameters are automatically passed to the function corresponding to the view 

URL (R & lt ' ^ Test / (\ + D) / ' , views.test), matches one or more digital #
def test(request, a):
print(a)
return HttpResponse("test")

  

  Famous grouping   

    N bracketed expressions match table to the contents as a keyword are automatically passed to the parameter corresponding to the view function 

url(r'^test/(?P<year>\d+)/', views.test),
def test(request, year):
    print(year)
    return HttpResponse("test")

 

   NOTE: unknown packets and known packets can not mix, a plurality of unknown packets may be used, or a plurality of packets known

 

  Reverse analysis: dynamically obtained according to the corresponding path name

    Unknown Packet reverse lookup:

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

      Backend:

        print(reverse('list',args=(10,)))

      Front-end:

        {% url 'list' 10 %}

      

      user_list = models.User.objects.all()


      url(r'^edit/(\d+)/',views.edit,name='edit')

      Front-end template syntax:      

        {%for user_obj in user_list%}
          <a href='edit/{{ user_obj.pk }}/'></a>
        {% endfor %}

      View function:

        from django.shortcuts import reverse
        def edit(request,edit_id):
          url = reverse('edit',args=(edit_id,))

      stencil:

        {% url 'edit' edit_id %}

    Famous grouping reverse lookup:

      Backend:

        # Backend famous groups and unnamed groups can use this form

        print(reverse('list',args=(10,)))

        # The following can understand

        {% url 'list' year=10 %}

    Summary: For reverse lookup famous groups and unnamed groups to adopt a uniform format on it

      rear end:

        reverse ( 'list', args = (10,)) # where digital data are usually primary key values

      front end:

        {% url 'list' 10 %}

    Reverse analysis of the essence: is to get to be able to access a name corresponding to the view function    

Definition: With the increase will be more functional view of possible configurations before the regular expression is not accurate enough, so we must modify regular expressions, regular expressions but once modified, before all the corresponding hyperlink must be modified 
    , that was a very troublesome thing, but there may be some hyperlinks forget to change. At this time there have been reverse analysis, can make connections based on regular expressions dynamically generate Applications: template hyperlink view redirection methods used: to include the definition of the namespace attribute is defined when defining the url url, need name property when in use, use the template url tags, use reverse function in the view, the expression dynamically generated addresses based on the positive and reduce the cost of ongoing maintenance

 

from django.shortcuts import render, HttpResponse, redirect, reverse

 

    You can give each route and view function correspondence between a name, the name that uniquely identifies a corresponding relationship, but be aware that the name can not be repeated, to be unique.

    Obtained according to a corresponding path name

    Front-end:

      { % url 'index'% }

      {% Url 'you to the routing function corresponds to the view from the alias relationship'}%

    Backend:

      Reverse ( 'you to view the routing function from the correspondence relationship alias')

    Anonymous group of reverse analysis:

      Backend:

        stencil:

          {% url 'edit' edit_id %}

      Front-end:

  Route distribution:

    django below each app can have its own urls.py routing layer, templates folder, static folder

    At this time the name of the project following urls.py (total route) do not match with the view of the relationship routing function but do routing distribution

# Alias to avoid conflict 
from
app01 Import urls AS app01_urls from app02 Import urls AS app02_urls from django.conf.urls Import url, the include urlpatterns = [
  # when the route distribution, the total route do not end with the $ url (r
' ADMIN ^ / ' , admin.site.urls), url (r ' ^ app01 / ' , the include (app01_urls)), # is used to help you do the include distributed url (r ' ^ app02 / ' , the include (app02_urls) ) ]

    Application of the new urls.py file, write the corresponding relation to the view routing function within the file to

from django.conf.urls import url
from app01 import views


urlpatterns = [
    url('^index', views.index)

]

  :( understand namespaces)

  url(r'^app01/', include(app01_urls, namespace="app01")),
    url(r'^app02/', include(app02_urls, namespace="app02"))
    
  app01下的urls:
  urlpatterns = [
      url('^index', views.index, name='index')

  ]
  app01下的views:
  def index(request):
      print('app01:', reverse('app01:index'))
      Return the render (Request, ' index.html ' ) 
  
  : URLs app02 under 
  the urlpatterns = [ 
      URL (R & lt ' ^ index / ' , views.index, = name ' index ' ) 

  ] 
  views app02 under: 
  DEF index (Request ):
      Print ( ' app02: ' , Reverse ( ' app02: index ' ))
      return HttpResponse ( ' this is the index app02 !!! ' )

 

      Questions:

import importlib

importlib.import_module('app01.urls')  # 等价于 from app01 import urls

 

 

Pseudo-static pages:

  Search Optimization: seo

  At the end of the route plus .html

Virtual Environment:

  Different projects configure different python interpreter

The difference between django1.0 and django2.0

  The first parameter path of django2.0 inside does not support regular, what you write will match what precisely match 100%

  django2.0 inside re_path corresponds django1.0 inside url

  Although the inside of the path 2.0 does not support regular expressions, but it provides five default converter :( understand)

    str, non-empty string match (/) except that the path outside the separator, which is the default form
    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?)

 

  Custom converter: 

class FourDigitYearConverter: 
        REGEX = ' [0-9]. 4} { ' 
        DEF to_python (Self, value):
             return int (value)
         DEF to_url (Self, value):
             return  ' % 04D ' % value   # accounted four, not enough 0 filled, super super is to press the number of bits! 
    register_converter (FourDigitYearConverter, ' YYYY ' )

 

  PS: the front end are matched to the contents of the default string

View layer:

  JsonReponse

    White will be the three tricks:

      HttpResponse

      render

      redirect

def index(request):
    return JsonResponse(res, json_dumps_params={'ensure_ascii': False})

 

 

 

  FBV and CBV

    FBV: function-based view

    CBV: class-based view

      The first settings inside 'django.middleware.csrf.CsrfViewMiddleware', commented words,

from django.views Import View 

class MyCls (View):
     DEF GET (Self, Request):
         return the render (Request, ' index.html ' ) 

    DEF POST (Self, Request):
         return HttpResponse ( ' POST ' ) 
, whether or FBV CBV routing layer routes are a function of the memory address corresponding to the view

and then routing layer: url (r '^ mycls / ', views.MyCls.as_view ())

 

 

  File Upload:

   

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="my_file">
    <input type="submit">
</form>

 

 

DEF upload_file (Request):
     IF request.method == ' the POST ' :
         Print ( ' path: ' , request.path)   # acquired is a relative path 
        Print ( ' Full_Path: ' , request.get_full_path ())   # to obtain a complete path is 
        Print (request.FILES) 
        file_obj = request.FILES.get ( ' my_file ' ) 
        with Open (file_obj.name, ' WB ' ) AS F:
             for Line infile_obj.chunks ():   # automatically move the cursor to the first line, line by line read ... 
                f.write (Line)
         return the HttpResponse ( ' the OK ' )
     return the render (Request, ' index.html ' )

 

Guess you like

Origin www.cnblogs.com/tulintao/p/11425696.html