URL Django learning

Django request lifecycle

  • - wsgi, he is the socket server for receiving a user request and the request for the initial package, then the request to the web frame (Flask, Django)

  • - Middleware, help us verify the request or add other relevant data in the request object, for example: csrf, request.session

  • - Route match

  • - a view function, in view of the business logic processing function, may involve: orm, templates => Rendering

  • - middleware for processing data in response.

  • - wsgi, the content of the response sent to the browser.

 

 

 

Establish relationships between tables and tables

Take the library management system as an example

Books table:

  Books and publishing are many, the foreign key field built in the books table (built in multi-party)

  Books and authors is many to many, you need third-many relationship table records

 

Django ORM relationship between tables and table  -to-many - ForeignKey (to = 'Publish' ) ( built in multi-table goes)

  One - OneToOneField (to = 'AuthorDetail') (built in high frequency query that table)

  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

 

models.py file

from django.db Import Models 

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

    # books and publishers is a foreign key to many relationship 
    publish = models.ForeignKey (to = ' publish ' )   # that is, with which tables are represented to-many relationship the default is to establish a relationship with the primary key fields of the table 
    . "" " 
    as long as the ForeignKey field django orm when creating the table will automatically add the field name _id after one to many 
    if you add the matter will continue to increase in the future 
    "" " 
    #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 ' )   # no the field will generate authors 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 the author details is one of the foreign key relationships
    = models.OneToOneField author_detail (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)

 

 

Routing layer

url () method first argument is actually a regular expression
once the previous regular matches to the content will no longer continue down the match but directly executes the corresponding view function

precisely because of the above characteristics especially when large your project order before and after the time of the url you also need to consider that you
most likely will be the case url disorder

urls.py file

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

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/', views.login),
    url(r'^reg/', views.reg),
    url(r'^userlist/', views.user_list),
    url(r'^del_user/', views.del_user),
    url(r'^update_user/', views.update_user),
    url(r'^add/', views.add),
]

 

django在路由的匹配的时候 当你在浏览器中没有敲最后的斜杠
django会先拿着你没有敲斜杠的结果取匹配 如果都没有匹配上 会让浏览器在末尾加斜杠再发一次请求 再匹配一次 如果还匹配不上才会报错
如果你想取消该机制 不想做二次匹配可以在settings配置文件中 指定
APPEND_SLASH = False # 该参数默认是True

 

 

无名分组

url(r'^test/([0-9]{4})/', views.test)
路由匹配的时候 会将括号内正则表达式匹配到的内容 当做位置参数传递给视图函数
test(request,2019)

  

有名分组

url(r'^test/(?P<year>\d+)/', views.test)
路由匹配的时候 会将括号内正则表达式匹配到的内容 当做关键字参数传递给视图函数
test(request,year=2019)

 

# 无名有名不能混合使用 !!!
url(r'^test/(\d+)/(?P<year>\d+)/', views.test),

但是用一种分组下 可以使用多个
# 无名分组支持多个
# url(r'^test/(\d+)/(\d+)/', views.test),
# 有名分组支持多个
# url(r'^test/(?P<year>\d+)/(?P<xx>\d+)/', views.test)

 

 

反向解析

本质:其实就是给你返回一个能够返回对应url的地址

1.先给url和视图函数对应关系起别名
  url(r'^index/$',views.index,name='kkk')

2.反向解析
  后端反向解析
  后端可以在任意位置通过reverse反向解析出对应的url
  from django.shortcuts import render,HttpResponse,redirect,reverse
  reverse('kkk')

  前端反向解析
  {% url 'kkk' %}

 

无名分组反向解析

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

后端反向解析
  reverse('kkk',args=(1,))  # 后面的数字通常都是数据的id值
前端反向解析
  {% url 'kkk' 1%}    # 后面的数字通常都是数据的id值

 

有名分组反向解析

同无名分组反向解析意义的用法

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

后端方向解析
  print(reverse('kkk',args=(1,))) # 推荐你使用上面这种 减少你的脑容量消耗
  print(reverse('kkk',kwargs={'year':1}))
前端反向解析
  <a href="{% url 'kkk' 1 %}">1</a> # 推荐你使用上面这种 减少你的脑容量消耗
  <a href="{% url 'kkk' year=1 %}">1</a>

注意:在同一个应用下 别名千万不能重复!!!

 

 

路由分发

当你的django项目特别庞大的时候 路由与视图函数对应关系特别特别多
那么你的总路由urls.py代码太过冗长 不易维护

每一个应用都可以有自己的urls.py,static文件夹,templates文件夹(******)

  正是基于上述条件 可以实现多人分组开发 等多人开发完成之后 我们只需要创建一个空的django项目


  然后将多人开发的app全部注册进来 在总路由实现一个路由分发 而不再做路由匹配(来了之后 我只给你分发到对应的app中)

 

  当你的应用下的视图函数特别特别多的时候  你可以建一个views文件夹 里面根据功能的细分再建不同的py文件(******)

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

    ]

 

 

名称空间(了解)

多个app起了相同的别名 这个时候用反向解析 并不会自动识别应用前缀
如果想避免这种问题的发生
方式1:

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

  后端解析的时候
  reverse('app01:index')
  reverse('app02:index')
  前端解析的时候
  {% url 'app01:index' %}
  {% url 'app02:index' %}

方式2:
  起别名的时候不要冲突即可 一般情况下在起别名的时候通常建议以应用名作为前缀
  name = 'app01_index'
  name = 'app02_index'

 

伪静态

静态网页:数据是写死的 万年不变

伪静态网页的设计是为了增加百度等搜索引擎seo查询力度

所有的搜索引擎其实都是一个巨大的爬虫程序

网站优化相关 通过伪静态确实可以提高你的网站被查询出来的概率
但是再怎么优化也抵不过RMB玩家

 

 

虚拟环境

一般情况下 我们会给每一个项目 配备该项目所需要的模块 不需要的一概不装


虚拟环境 就类似于为每个项目量身定做的解释器环境

每创建一个虚拟环境 就类似于你又下载了一个全新的python解释器

 

 

Django版本的区别

django1.X跟django2.X版本区别
  路由层1.X用的是url
  而2.X用的是path

  2.X中的path第一个参数不再是正则表达式,而是写什么就匹配什么 是精准匹配

  当你使用2.X不习惯的时候 2.X还有一个叫re_path
  2.x中的re_path就是你1.X的url

 

虽然2.X中path不支持正则表达式 但是它提供了五种默认的转换器

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

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

 

还支持自定义转换器

 

        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),  
                ...  
            ]  

 

 

 

 

视图层

1.小白必会三板斧
  1.HttpResponse
  2.render
  3.redirect
  django视图函数必须要给返回一个HttpResponse对象

前后端分离
  前端一个人干(前端转成自定义对象)
    JSON.stringify() json.dumps()
    JSON.parse() json.loads()
  后端另一个干(python后端用字典)
  只要涉及到数据交互,一般情况下都是用的json格式
  后端只负责产生接口,前端调用该接口能拿到一个大字典
  后端只需要写一个接口文档 里面描述字典的详细信息以及参数的传递
2.JsonReponse

  from django.http import JsonResponse
  def index(request):
    data = {'name':'jason好帅哦 我好喜欢','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.上传文件
form表单上传文件需要注意的事项
1.enctype需要由默认的urlencoded变成formdata
2.method需要由默认的get变成post
(目前还需要考虑的是 提交post请求需要将配置文件中的csrf中间件注释)

如果form表单上传文件 后端需要在request.FILES获取文件数据 而不再是POST里面

 

request的方法

 

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

 

Guess you like

Origin www.cnblogs.com/AbrahamChen/p/11536292.html