我想创建一个函数来判断url中的数字是奇数还是偶数。这是关于法官的代码:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from django.http import HttpResponse,Http404
import datetime
def judge(reqest, number):
try:
number = int(number)
except ValueError:
raise Http404()
if number % 2 == 0:
html = "<html><body>%d is even!</body></html>" % (number)
else:
html = "<html><body>%d is odd!</body></html>" % (number)
return HttpResponse(html)
现在,我陷入了url.py
,我不知道这样的编辑是否有效:
from django.conf.urls.defaults import *
from views import *
urlpatterns = patterns('',
#(r'^$', time_now),
(r'^number/(.+)$', judge), # we just want the number in the url, not more or less
)
但我也想处理空输入,但每次尝试时页面都会显示"Nothing input"
:
def judge(reqest, number):
if number is None:
html = "nothing input!"
return HttpResponse(html)
try:
number = int(number)
except ValueError:
raise Http404()
if number % 2 == 0:
html = "<html><body>%d is even!</body></html>" % (number)
else:
html = "<html><body>%d is odd!</body></html>" % (number)
return HttpResponse(html)
我该如何解决这个问题?
答案 0 :(得分:1)
定义两个这样的网址
urls.py
from views import *
urlpatterns = patterns('',
#(r'^$', time_now),
(r'^number/(.+)/$', judge),
(r'^number/$', judge),
)
设置默认值
views.py
def judge(reqest, number=None):
...