[英]What's a good way to handle url parameters types?
Imagine an app with the following url.py
: 想象一下具有以下
url.py
的应用:
urlpatterns = patterns('',
url(r'^$', views.index),
url(r'^double/(?P<number>\d+)/$', views.double),
)
And this views.py
: 这个
views.py
:
def double(request, number=42):
return HttpResponse(2*number)
Obviously, I want number
to be always taken as an int. 显然,我希望
number
始终被视为int。 When querying /double/5/
, I'll always expect to get 10
, not 55
. 当查询
/double/5/
,我总是期望得到10
,而不是55
。
Are there any good way to handle the parameters typing within Django urls? 有没有什么好办法处理Django网址中的参数输入?
Here's a decorator-based solution: 这是一个基于装饰的解决方案:
def param_type(**type_spec):
def deco(f):
def view(request, **kwargs):
for k, type_ in type_spec.items():
kwargs[k] = type_(kwargs[k])
return f(request, **kwargs)
return view
return deco
@param_type(number=int)
def double(request, number=42):
return HttpResponse(2*number)
This thread says that auto-conversion isn't a good solution: 这个帖子说自动转换不是一个好的解决方案:
Note that automatic conversion wouldn't be a good plan, either.
请注意,自动转换也不是一个好的计划。 For example, the next version of my blog converts URLs like 2008/2/25/ to 2008/02/25/ because I want a canonical form.
例如,我的博客的下一个版本会将像2008/2/25 /到2008 / 02/25 /的网址转换为因为我想要一个规范的表单。 So I need to know if \\d{1,2} matches one of two digits, even if the first one is 0. Auto-conversion to an integer would remove that capability (and it's not hard to think of other cases like this).
所以我需要知道\\ d {1,2}是否匹配两个数字中的一个,即使第一个是0.自动转换为整数会删除该功能(并且不难想到像这样的其他情况) 。 So you'd need configurabiliy.
所以你需要configurabiliy。
It also suggests a solution based on a decorator, but I'm not really convinced, it sounds a bit burdensome: 它还提出了一个基于装饰器的解决方案,但我并不是真的相信,这听起来有点麻烦:
One solution to your problem could be to write a decorator that takes a list of types (plus something like None for "don't care") and automatically converts argument N to the type in the N-th element of the list before calling your function
你的问题的一个解决方案可能是编写一个装饰器,它接受一个类型列表(加上“不关心”的类似于None)并自动将参数N转换为列表第N个元素中的类型,然后再调用功能
Anto, 安托,
I think your question is more related to the url. 我认为你的问题与网址更相关。
(?P<number>\\d+)
is a regular expression stating \\d
only allowing digits it's the same as [0-9]
. (?P<number>\\d+)
是一个正则表达式,表示\\d
只允许数字与[0-9]
相同。 The +
symbol tells it need 1 or more digits. +
符号表示需要1位或更多位数。 So if you would try to insert something like double/notanumber/
it will not work. 因此,如果您尝试插入像
double/notanumber/
这样的东西,它将无效。
Knowing this you can safely assume that: 知道这一点你可以安全地假设:
1: number will always have a value
1:数字总是有一个值
2: number will always be a integer (even that django gives it back as a unicode)
2:数字将始终为整数(即使django将其作为unicode返回)
I made a small change to your function: 我对你的功能做了一些小改动:
def double(request, number): # removed the =42 because number can never be empty
return HttpResponse(2 * int(number)) # Converted your number to an integer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.