Routing control and view layer

Build relationships between tables and tables

  Library management system as an example

    Table books

      Books and publishing houses are built-to-many foreign key field in the books table

      Books and authors are required many-to-many relationship table records a third

 

    Press table (Publish)

    On the table (Author)

    Author details table (AuthorDetail)

    Build relationships between tables and table django orm

    Many ForeignKey (to = 'Publish')

    Many to many ManyToManyField (to = 'Author')

    One OneToOneField (to = 'AuthorDetail')

class Book (models.Model):
     # the above mentioned id created automatically can not write 
    title = models.CharField (64-max_length = )
     # 8-bit fractional part accounted for two 
    . price = models.DecimalField (max_digits = 8, decimal_places = 2 ) 

    # books and many publishers are foreign key relationships 
    publish = models.ForeignKey (to = ' publish ' )   # to indicate is that with which tables is one to many relationship default is to build relationships with the table's primary key field 
    "" " 
    As long as the ForeignKey field django orm will automatically be added after the field name in many _id when creating the table 
    if you add the matter will continue in the future plus 
    " "" 
    # publish = models.ForeignKey (to = Publish) # to be written directly behind the table name but must ensure that the table name in the top 
    # books and authors are many relationships 
    in the authors = models.ManyToManyField (to = 'Author ' )   # does not generate the authors field field in the table is a virtual field is only used to tell django orm automatically help you create books and the author of the third table 

class Publish (models.Model): 
    name = Models. CharField (max_length = 32 ) 
    addr = models.CharField (max_length = 32 ) 

class author (models.Model): 
    name = models.CharField (max_length = 32 ) 
    Age = models.IntegerField ()
     # author and is one of the details foreign key relationships 
    author_detail = models.OneToOneField (to = ' AuthorDetail ' , null = True)
     "" " 
    will automatically re-applied field names behind the _id 
    " "" 


class AuthorDetail(models.Model):
    phone = models.BigIntegerField()
    addr = models.CharField(max_length=32)

note:

  The first two keywords will automatically add _id field behind

  Finally, a keyword does not produce the actual field just tell django orm automatically create a third table

 

Routing layer

  url () method first argument is actually a regular expression

  Once the regular matching front to match the content does not continue on down but directly performs the function corresponding to the view

  Because of the above characteristics when the project is particularly large when the    url before and after the order is to be considered

  The situation is likely to occur url disorder

  

  django matching route in the time when you do not knock the last slash in the browser

  django will first hold a slash to knock you no results to match if the match did not make the browser slash at the end of a match and then resend the request if it is not matched on the incorrect report

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

= False APPEND_SLASH    # The default parameter is True

 

Unknown group

URL (R & lt ' ^ Test / ([0-9] {}. 4) / ' , views.test)
 # when the matching route will be in parentheses to the regular expression matching content as the positional parameters passed to the view function 
test (request , 2019)

Famous grouping

URL (R & lt ' ^ Test / (? P <year> \ + D) / ' , views.test)
 # when the route matching the regular expression parentheses will be matched to the content as the key parameter to the view function 
test (request , year = 2019)

Note: nameless famous not mix !!!!

URL (R & lt ' ^ Test / (\ + D) / (? P <year> \ + D) / ' , views.test) error !!!!!!!

However, with the plurality of A packet may be used

# Unknown support a plurality of packet 
# URL (R & lt 'Test ^ / (\ + D) / (\ + D) /', views.test), 
# known supports a plurality of packet 
# URL (R & lt 'Test ^ / (? P <year > \ d +) / (? P <xx> \ d +) / ', views.test),

Reverse lookup

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

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

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

  2. reverse lookup

    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'%}

Unknown Packet reverse lookup

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

Back-end reverse lookup

Reverse ( ' KKK ' , args = (. 1,))   # back digital data id values are usually

Front-end reverse lookup

URL% { ' KKK ' . 1%}    # behind the digital data are usually values id

Famous grouping reverse lookup

  Unknown group with the same usage reverse analysis

url(r'^index/(?P<year>\d+)/$',views.index,name='kkk')

Back-end reverse lookup

Print (Reverse ( ' KKK ' , args = (. 1,)))   # recommended that you use your mind that the above reduction capacity consumption 
Print (Reverse ( ' KKK ' , kwargs = { ' year ' :}. 1))

Front-end reverse lookup

href= <a "{% URL'kkk' %}. 1"> . 1 </a>   # recommended that you use your mind that the above reduction capacity consumption 
<A the href = " {% URL 'KKK' year =%}. 1 " > 1 </a>

Note: In the same application alias must not be repeated !!!

 

Route distribution (*****)

  When your django project particularly large especially when a particularly large correspondence between routing and view function

  So 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 (******)

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

        ]

Namespace (understanding)
  more app from the same alias at this time does not automatically identify applications with the prefix reverse lookup
  If you want to avoid this problem
    way 1:
      total routing     behind the total route is not a route ten million plus $ symbol

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' %}

Option 2:
Since when do not conflict alias can be played under normal circumstances at the time generally recommended to use an alias name as a prefix

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

name = 'app01_index'
name = 'app02_index'

 print(reverse('app01_index'))

 

Pseudo-static
  static pages: the data is written in the same years dead

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

  all search engines are in fact a giant crawler

  website optimization related by pseudo-static can indeed improve the probability of your website being queried out
  but then how to optimize the RMB players also arrived, but

 

Virtual environment
  under normal circumstances we will give each project module with the required items not needed and will not install
  virtual environment is similar tailor-made for each project interpreter environment

  how to create a virtual environment
  for each to create a virtual environment you're like downloading a new python interpreter

 

django version difference 
    django1.X with django2.X version differences 
        routing layer using a url 1.X 
        and 2.X use the path
            
     2 .X the path is no longer the first argument is a regular expression, but to write What is the precise matching to match what 
        if you are not accustomed to when using the 2.X   2 .X also called re_path
         2 .x in re_path the url that you 1.X     
            
    although 2.X the path does not support regular expressions but it provides five default converter
        
     1 a .0 version of the 2.0 version of re_path url and packet data are out of the string type 
    default there are five converters, class interest they can go on to try 
    str, in addition to matching path delimiters ( / non-empty string outside), 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 ( / ) (can not?) 
            
path ( 'index / <int: id> / ' , index)   # will match the content id automatically converted to integer
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 accounting four, not enough to fill 0, then to press the ultra-super number of bits! 
    register_converter (FourDigitYearConverter, ' YYYY ' )   
            
    the urlpatterns = [   
            path ( ' Articles / 2003 / ' , views.special_case_2003),   
            path ( 'articles/<yyyy:year>/', views.year_archive),  
            ...  
        ]  
            

View layer

1. White will be three tricks
  1.HttpResponse

  2.render

  3.redirect

  django view function must return an HttpResponse

 

Separate front and rear ends

  A human stem front end (the front end turn to custom object)

    JSON.stringify()          json.dumps()

    JSON.parse()              json.loads()

  The rear end of another human stem (python backend dictionary)

  As far as the data exchange, it is generally used format json

  Only responsible for generating back-end interface to call the front-end interface to be able to get a big dictionary

  Simply write back-end transfer described in the dictionary as well as details of a parameter interface documentation which

2.JsonResponse

from django.utils.httpwrappers Import jsonResponse
     DEF index (Request): 
        Data = { ' name ' : ' Jason Good Shuaio I love ' , ' password ' : 123 } 
        L = [1,2,3,4,5,6, 7, 8 ]
         # RES = json.dumps (Data, ensure_ascii = False) 
        # return the HttpResponse (RES) 
        # return jsonResponse (Data, json_dumps_params = { 'ensure_ascii': False}) 
        return jsonResponse (L, Safe = False)   # If return not only need to modify the dictionary safe parameter to false

3. Upload file

  form matters form to upload files Note:

    1.enctype need to become the default urlencoded formdata

    2.method need to become the default get post

    (There is a need to consider the need to submit a request to post profiles of csrf middleware comment)

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

DEF upload_file (Request):
     IF request.method == ' the POST ' :
         # Print (of request.POST) 
        file_obj = request.FILES.get ( ' myfile ' )
         # Print (file_obj) # file_obj file object is 
        Print (file_obj.name )   # filename 
        # file operations uploaded files are written to the back-end 
        with Open (file_obj.name, ' wb ' ) AS f:
             for Line in file_obj.chunks ():   # file_obj also an iterable 
                f.write (line )
         returnThe HttpResponse ( ' received ' )
     return the render (Request, ' file.html ' )

  request.method
  request.GET
  request.POST
  request.FILES
  request.path # url suffix not only get to go back? parameters behind
  request.get_full_path () # suffix and get all the parameters

 

Guess you like

Origin www.cnblogs.com/KrisYzy/p/11537091.html