Django中的测试请求参数(“+”表现不同) [英] Testing request parameters in Django ("+" behaves differently)

查看:166
本文介绍了Django中的测试请求参数(“+”表现不同)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django View,它使用一个查询参数进行一些内容过滤。这样的事情:

I have a Django View that uses a query parameter to do some content filtering. Something like this:

/page/?filter=one+and+two
/page/?filter=one,or,two

我注意到Django转换 + 到一个空格( request.GET.get('filter')返回一个和两个),我可以这样做我只需要调整在视图中使用的 split()函数。

I have noticed that Django converts the + to a space (request.GET.get('filter') returns one and two), and I´m OK with that. I just need to adjust the split() function I use in the View accordingly.

但是。 ..

当我尝试测试这个视图,我打电话:

When I try to test this View, and I call:

from django.test import Client
client = Client()
client.get('/page/', {'filter': 'one+and+two'})

request.GET.get('filter')返回一个+和+两个:加号和空格。为什么是这样?

request.GET.get('filter') returns one+and+two: with plus signs and no spaces. Why is this?

我想认为 Client()。get()模仿浏览器的行为,所以我想要理解的是为什么调用 client.get('/ page /',{'filter':'one + and + two'})不是浏览到 / page /?filter = one +和+ two 为了测试的目的,在我看来应该是一样的,在这两种情况下,视图都应该得到一个一致的过滤值:不管它是否与 + 或空格。

I would like to think that Client().get() mimics the browser behaviour, so what I would like to understand is why calling client.get('/page/', {'filter': 'one+and+two'}) is not like browsing to /page/?filter=one+and+two. For testing purposes it should be the same in my opinion, and in both cases the view should receive a consistent value for filter: be it with + or with spaces.

我不知道为什么有两种不同的行为。

What I don´t get is why there are two different behaviours.

推荐答案

查询字符串中的大写是空格的正常和正确的编码。这是一个历史文物; 网址的表单值编码有所不同稍微从编码URL中的其他元素。

The plusses in a query string are the normal and correct encoding for spaces. This is a historical artifact; the form value encoding for URLs differs ever so slightly from encoding other elements in the URL.

Django负责将查询字符串解码回键值对;该解码包括解码URL百分比编码,其中 + 被解码为空格。

Django is responsible for decoding the query string back to key-value pairs; that decoding includes decoding the URL percent encoding, where a + is decoded to a space.

使用测试客户端,您传递未编码的数据,因此您可以使用:

When using the test client, you pass in unencoded data, so you'd use:

client.get('/page/', {'filter': 'one and two'})

到您的查询字符串,然后在尝试访问参数时再次解码。

This is then encoded to a query string for you, and subsequently decoded again when you try and access the parameters.

这篇关于Django中的测试请求参数(“+”表现不同)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆