码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习之路—2018/6/19

时间:2018-06-19 22:49:54      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:self   odi   组成   list   path   reg   value   解析   convert   

Python学习之路—2018/6/19

1.注册自定义转化器

converts.py

class Birthday:
    regex = ‘[0-9]{8}  # 匹配规则

    def to_python(self, value):  # 匹配的字符串返回具体的变量值,传递到对应的视图函数中
        return int(value)

    def to_url(self,value):  # 反向解析
        return "%04d" % value

urls.py

from django.urls import path, register_converter
from app01 import views, urls, converts


register_converter(converts.Birthday, "birth")  
urlpatterns = [
    path(‘gyq/<birth:year>‘, views.birthday)
]

views.py

def birthday(request, date):
    return HttpResponse(date)

2.HttpRequest对象

url组成:协议/IP/端口/path/请求数据

request常用属性

HttpRequest.GET 包含了HTTP GET的所有参数

HttpRequest.POST 如果请求中包含表单数据,将这些数据包装成QueryList对象

HttpRequest.method Http请求的方法(get/post)

HttpRequest.encoding 提交的数据编码

request常用方法

HttpRequest.get_full_path() 返回path ,包括查询字符串。

HttpRequest.get_full_path() 判断请求是否为XMLHttpRequest发起的

视图响应对象

响应对象主要有三种形式:

  • HttpResponse()
  • render()
  • redirect()

HttpResponse()括号内直接跟一个具体的字符串作为响应体

render()

render(request, template_name[, context])

request: 用于生成响应的请求对象。

template_name:要使用的模板的完整名称,例如index.html

context:添加到模板上下文的一个字典。默认是一个空字典。如果字典中的某个值是可调用的,视图将在渲染模板之前调用它。

Python学习之路—2018/6/19

标签:self   odi   组成   list   path   reg   value   解析   convert   

原文地址:https://www.cnblogs.com/ExBurner/p/9201273.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!