Skip to main content
 首页 » 编程设计

python之如何在我的 django urls.py 中处理查询 ""

2025年05月04日37davidwang456

我是 Django 的新手。我必须写一个moke。我的服务器将查看特定地址。 像这样:

portal/client_api.ashx?client=SAPRA&key=1234234&func=status&code=99999

我写道:

urls.py
from django.conf.urls import patterns, url 
from rt_moke import views 
urlpatterns = patterns('', 
    url(r'code=(?P<code_id>\w+)/', views.Sapata, name='sapata'), 
    ) 

和views.py
from django.http import HttpResponse 
status = {u"99999": u'{"code": "99999","status": "undelivered"}',\ 
     u"88888": u'{"code": "88888","status": "delivered"}',\ 
     } 
def Sapata(request, code_id): 
    return HttpResponse(status[code_id]) 

当我请求没有 ? 标记的 portal/client_api.ashx?client=SAPRA&key=1234234&func=status&code=99999 时 - 它有效,并且带有 ? - 不是。我知道,它是查询字符串,Django 在正则表达式中跳过它。那我该怎么办?

请您参考如下方法:

这个网址:

portal/client_api.ashx?client=SAPRA&key=1234234&func=status&code=99999 

有两部分,路径:

portal/client_api.ashx 

和查询字符串:

client=SAPRA&key=1234234&func=status&code=99999 

解析为request.GET。

在 views.py 中,您应该从请求中获取参数(例如 request.GET 中的简单字典),例如:

def test(request): 
    code = request.GET.get('code') # here we try to get 'code' key, if not return None 
    ... 

当然,我们不能使用 GET 参数来解析 urls.py 中的 URL。您的 urls.py 应该如下所示:

from django.conf.urls import patterns, url 
from rt_moke import views 
 
urlpatterns = patterns('', 
    url(r'^portal/client_api\.ashx$', views.Sapata, name='sapata'), 
) 

附言请不要在函数名称中使用大写字母。