Django神装
- HttpResponseDirect #django首选的URL重定向方法
- redirect
- reverse
- HttpResponse
- render
- get_objects_or_404()
1.HttpResponse
它是作用是内部传入一个字符串参数,然后发给浏览器。
例如:
def index(request):
# 业务逻辑代码
return HttpResponse("OK")2、render
render函数的作用是将给定的模板与给定的上下文字典组合起来,并返回指定内容类型的HttpResponse对象。通过它,你可以快速指定模板名称, 上下文字典(context),内容类型(content_type)和返回状态码(默认200)。该函数标准用法如下,其中request和template_name参数为必选,其它为可选参数。
例如:
def index(request):
# 业务逻辑代码
return render(request, "index.html", {"name": "monicx", "hobby":["reading", "blog"]})3、redirect
from django.shortcuts import redirect
from django.urls import reverse
# 案例1
def my_view(request):
...
return redirect('/index/')
# 案例2
def my_view(request):
...
return redirect('https://www.danlan.com/')
# 案例3
def my_view(request):
...
return redirect(reverse('blog:article_detail'))4、reverse
reverse方法的作用是对已命名的URL进行反向解析,还传递相应的参数(args或带key的参数kargs)
reverse方法一般有2种应用场景:
- 在模型中自定义get_absolute_url时使用,传递参数
- 在视图中对命名URL进行解析,传递参数,再使用HttpResponseDirect和redict进行重定向
1. 模型中自定义get_absolute_url,并传递参数args
def get_absolute_url(self):
return reverse('blog:article_detail', args=[str(self.pk), self.slug])2. 在视图中配合URL重定向使用,并传递kargs
from django.urls import reverse
from django.shortcuts import redirect
def my_view(request):
...
return redirect(reverse('admin:app_list', kwargs={'app_label': 'auth'}))5、HttpResponseDirect
def my_view(request):
return HttpResponseRedirect("/index/")
def my_view(request):
return HttpResponseRedirect(reverse('blog:article_list'))#HttpReponseDirect只支持硬编码链接, 不能直接使用命名的URL,如使用HttpResponseDirect('blog:article_list‘)是错误的
def my_view(request):
return HttpResponseRedirect(reverse('blog:article_detail', args=[str(article.pk), article.slug])) # 包含参数6、get_objects_or_404()
该函数作用是查找返回某个对象,如果查找不到,自动返回Http404, 如下所示:
from django.shortcuts import get_object_or_404
def my_view(request):
obj = get_object_or_404(MyModel, pk=1)HttpResponseDirect, redirect,HttpResponse,render,reverse五个方法都非常常用,在使用它们前别忘了import进来。注意它们在不同的模块。
- HttpResponseDirect - django.http
- redirect,render,HttpResponse,get_objects_or_404 - django.shortcuts
- reverse - django.urls
Request对象方法和属性
Request
我们知道当URLconf文件匹配到用户输入的路径后,会调用对应的view函数,并将 HttpRequest对象 作为第一个参数传入该函数。
我们来看一看这个HttpRequest对象有哪些属性或者方法:
属性:
- HttpRequest.scheme 请求的协议,一般为http或者https,字符串格式(以下属性中若无特殊指明,均为字符串格式)
- HttpRequest.body http请求的主体,二进制格式。
- HttpRequest.path 所请求页面的完整路径(但不包括协议以及域名),也就是相对于网站根目录的路径。
- HttpRequest.path_info 获取具有 URL 扩展名的资源的附加路径信息。相对于HttpRequest.path,使用该方法便于移植。
- HttpRequest.method 获取该请求的方法,比如: GET POST
- HttpRequest.encoding 获取请求中表单提交数据的编码
- HttpRequest.content_type 获取请求的MIME类型(从CONTENT_TYPE头部中获取),django1.10的新特性。
- HttpRequest.content_params 获取CONTENT_TYPE中的键值对参数,并以字典的方式表示,django1.10的新特性。
- HttpRequest.GET 返回一个 querydict 对象(类似于字典,本文最后有querydict的介绍),该对象包含了所有的HTTP GET参数
- HttpRequest.POST 返回一个 querydict ,该对象包含了所有的HTTP POST参数,通过表单上传的所有 字符 都会保存在该属性中
- HttpRequest.COOKIES 返回一个包含了所有cookies的字典。
- HttpRequest.FILES 返回一个包含了所有的上传文件的 querydict 对象。通过表单所上传的所有 文件 都会保存在该属性中,key的值是input标签中name属性的值,value的值是一个UploadedFile对象
- HttpRequest.META 返回一个包含了所有http头部信息的字典
- CONTENT_LENGTH – The length of the request body (as a string).
- CONTENT_TYPE – The MIME type of the request body.
- HTTP_ACCEPT – Acceptable content types for the response.
- HTTP_ACCEPT_ENCODING – Acceptable encodings for the response.
- HTTP_ACCEPT_LANGUAGE – Acceptable languages for the response.
- HTTP_HOST – The HTTP Host header sent by the client.
- HTTP_REFERER – The referring page, if any.
- HTTP_USER_AGENT – The client’s user-agent string.
- QUERY_STRING – The query string, as a single (unparsed) string.
- REMOTE_ADDR – The IP address of the client 可获取用户远程IP地址.
- REMOTE_HOST – The hostname of the client.
- REMOTE_USER – The user authenticated by the Web server, if any.
- REQUEST_METHOD – A string such as "GET" or "POST".
- SERVER_NAME – The hostname of the server.
- SERVER_PORT – The port of the server (as a string).
- HttpRequest.session 中间件属性
- HttpRequest.site 中间件属性
- HttpRequest.user 中间件属性,表示当前登录的用户
- HttpRequest.user 实际上是由一个定义在django.contrib.auth.models 中的 user model 类 所创建的对象。
- 该类有许多字段,属性和方法。列举几个常用的: 获取更详细信息-->官方文档。
- 字段
- username 用户名
- first_name
- last_name
- password
- groups
- user_permissions
- is_staff 布尔值,标明用户是否可以访问admin页面
- is_superuser
- last_login 上一次登陆时间
- date_joined 用户创建时间
- 属性
- is_authenticated 布尔值,标志着用户是否已认证。在django1.10之前,没有该属性,但有与该属性同名的方法
- 方法
- HttpRequest.user.get_username() 注意:方法的圆括号在templates标签中必需省略!!获取username。尽量使用该方法来代替使用username字段
- HttpRequest.user.get_full_name() 注意:方法的圆括号在templates标签中必需省略!!获取first_name和last_name
- HttpRequest.user.short_name() 注意:方法的圆括号在templates标签中必需省略!!获取first_name
- HttpRequest.user.set_password(raw_password) 注意:该方法无法在template标签中使用!!设置密码
- HttpRequest.user.check_password(raw_password) 注意:该方法无法在template标签中使用!!如果raw_password与用户密码相等,则返回True
- 字段
方法:
- HttpRequest.get_host() 返回请求的源主机。example: 127.0.0.1:8000
- HttpRequest.get_port() django1.9的新特性。
- HttpRequest.get_full_path() 返回完整路径,并包括附加的查询信息。
- HttpRequest.bulid_absolute_uri(location) 返回location的绝对uri,location默认为request.get_full_path()。
QueryDict
是一个类似于Python中字典的一种对象,他是Python中字典的子类,所以继承了字典的所有方法,
当然QueryDict对字典的某些方法进行了加工,并补充了一些独特的方法。这里列出部分方法。详情请看: 官方文档 。
- QueryDict.get(key,default=None) 返回key所对应的value,若key不存在,则返回default的值
- QueryDict.update(other_dict) 更新
- QueryDict.values() 列出所有的值
- QueryDict.items() 列出所有的键值对,若一个key有多个值,只显示最后一个值。
- QueryDict.pop(key) 删除某个键值对
- QueryDict.getlist(key) 根据输入的key返回一个Python中的list
- QueryDict.dict() 返回QueryDict的字典的表现形式
Django Utils
django.utils.dateparse模块
在日常开发工作中我们经常需要将用户输入的字符串格式的时间和日期转化为日期和时间对象,django.utils.dateparse提供了如下几个方法供我们使用:
parse_date(value)
接收字符串,比如'2020-04-30',返回datetime.date类型的数据。
parse_time(value)
接收字符串,比如'12:35:20'返回datetime.time类型的数据。
parse_datetime(value)
接收字符串,比如'2020-04-40 12:35:20', 返回datetime.datetime类型的数据。
django.utils.decorators模块
给基于类的视图(CBV)使用装饰器时,我们需要借助于该模块的method_decorator方法实现。它还支持decorators列表, 如下所示:
from django.utils.decorators import method_decorator
decorators = [login_required, check_user_permission]
@method_decorator(decorators, name='dispatch')
class ArticleCreateView(CreateView):
model = Article
form_class = ArticleForm
template_name = 'blog/article_manage_form.html'
另外该模块的另外两个有用方法是:
- decorator_from_middleware(middleware_class): 该方法将一个Middleware类转变为一个装饰器,可以用于单个视图函数上。
- decorator_from_middleware_with_args(middleware_class): 与上一方法作用相同,只不过支持传递额外的参数。
我们常用的@cache_page装饰器就是从中间件CacheMiddleware转换过来的。
cache_page = decorator_from_middleware_with_args(CacheMiddleware)
@cache_page(3600)
def my_view(request):
passdjango.utils.encoding模块
smart_str(obj, encoding='utf-8', strings_only=False, errors='strict')
该方法可以将一个obj对象转化为str类型的表示形式。如果strings_only设置为True,意味着不转换非字符串类型的对象obj。如果对象里包含中文字符串,设置encoding="etf-8"可以避免乱码。
django.utils.safestring模块
在前端模板里如果我们希望Django避免对一个字符串进行转义,我们可以|safe模板过滤器或autoescape标签。而在视图里如果我们希望Django避免对一个字符串转义,就需要使用该模块提供的mark_safe方法了。
from django.utils.safestring import mark_safe
def index(request):
content = "<a href='http://www.baidu.com'>百度</a>"
marked_content = mark_safe(content)
return render(request, 'indext.html', {'content': marked_content})django.utils.timezone模块
在现实开发环境中,存在有多个时区,用户之间很有可能存在于不同的时区,所以每个用户当前时间都是不一样的。Django在存储和操作日期时间类型数据的最佳实践是在数据库中统一存储UTC标准时间,在与用户打交道时使用用户所在时区的时间。
datetime.datetime.now()获取的时间是不带任何时区信息的,不便于与数据表中的日期时间类型数据进行直接比对,而借助于timezone模块提供的now方法,我们可以总是可以获取当前UTC标准时间。借助timezone模块提供的localtime方法,我们还以很快获得当地时间。
借助于该模块提供的now方法,你可以获得用户当前时区的时间,非常有用。
# settings.py
TIME_ZONE = 'Asia/Shanghai'
# python manage.py shell
>>> from django.utils import timezone
>>> now1 = timezone.now() # 获得带时区信息的UTC时间
datetime.datetime(2016, 12, 7, 1, 41, 36, 685921, tzinfo=<UTC>)
>>> local_now = timezone.localtime(now1) # 获得上海时区所在时间
datetime.datetime(2016, 12, 7, 9, 41, 36, 685921, tzinfo=<UTC>)django.utils.text模块
该模块提供的最常用的方法莫过于slugify方法了。使用allow_unicode=True选项还允许生成含有中文的slug。
from django.utils.text import slugify
>>> slugify(' Joel is a slug ')
'joel-is-a-slug'
>>> slugify('你好 World', allow_unicode=True)
'你好-world'本文部分内容来自:大江狗





Comments | NOTHING