Django网址,不同的正则表达式?

时间:2013-12-08 18:26:41

标签: python regex django url

我的网址:

urlpatterns = patterns('',
    url(r'^$', 'ping.views.services', name='services'),
    url(r'^ajax/status/(?P<id>[-\d]+)', 'ping.views.ajx_status', name='ajx_status'),
    url(r'^ajax/status/(?P<type>[-\w]+)/(?P<id>[-\d]+)(?:\?callback=(?P<callback>[-\w]+)&[_=0-9]+)?$', 'ping.views.ajx_status', name='ajx_status'),
)

链接是:http://127.0.0.1:8000/ajax/status/jsonp/1?callback=jQuery110208076630807481706_1386460596798&_=1386460596799

输出:

def ajx_status(request, id, type,callback):
    print id,type,callback

日志:

1 jsonp None
/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py:903: RuntimeWarning: DateTimeField Ping.timestamp received a naive datetime (2013-12-08 18:12:33.831348) while time zone support is active.
  RuntimeWarning)

[08/Dec/2013 18:12:34] "GET /ajax/status/jsonp/1?callback=jQuery110208076630807481706_1386460596798&_=1386460596799 HTTP/1.1" 200 433

“raw”python中的文本,有效:

import re

regex = re.compile(r"^/ajax/status/(?P<type>[-\w]+)/(?P<id>[-\d]+)(?:\?callback=(?P<callback>[-\w]+)&[_=0-9]+)?")

r = regex.search("/ajax/status/jsonp/1?callback=jQuery110208076630807481706_1386460596798&_=1386460596799")

r.groupdict()

{'callback': 'jQuery110208076630807481706_1386460596798', 'type': 'jsonp', 'id': '1'}

用谷歌搜索了几个关于这个好奇的小说,Django在python中的方式与fyl相同。任何想法如何不起作用和回调总是没有?

2 个答案:

答案 0 :(得分:2)

只有URL的路径部分与urlpattern匹配。查询字符串在request.GET

视图中可用

答案 1 :(得分:0)

在Django url-config中,不需要匹配url中的Query String。您可以查询查询字符串数据,如request.GET.get('query_string_key')

例如:

request.GET.get("page")

urls.py中,您可以写下以下内容:

urlpatterns = patterns('',
    url(r'^ajax/status/(?P<type>[-\w]+)/(?P<id>[-\d]+)/$', 'ping.views.ajx_status', name='ajx_status'),
)