我想要匹配的网址是:
http://domain/games/getdata/genres/
此请求是通过ajax从外部api获取一些JSON数据。我不能得到它来匹配;继续我已经设置的中间件处理程序。我确定这个修复是非常明显的,但我一直盯着这个方式太久了。
urls.py:
from django.conf import settings
from django.conf.urls.defaults import patterns, include
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^$', 'blog.views.index'),
(r'^games/$', 'giantbomb_games.views.index'),
(r'^games/getdata/(?P<resource>\w+)/$', 'giantbomb_games.views.getdata'),
(r'^grappelli/', include('grappelli.urls')),
(r'^admin/filebrowser/', include('filebrowser.urls')),
(r'^admin/', include(admin.site.urls)),
)
views.py:
def getdata(request, resource):
url = '%s/%s/?api_key=%s&format=%s' % (api_url, resource , api_key, request_format)
print url
r = requests.get(url)
return r.content
页/ middleware.py:
from django.http import Http404
from django.conf import settings
from page.views import site_page
class SitePageFallbackMiddleware(object):
def process_response(self, request, response):
if response.status_code != 404:
return response # No need to check for a flatpage for non-404 responses.
try:
return site_page(request, request.path_info)
# Return the original response if any errors happened. Because this
# is a middleware, we can't assume the errors will be caught elsewhere.
except Http404:
return response
except:
if settings.DEBUG:
raise
return response
django错误:
Traceback (most recent call last):
File "/var/www/html/top10/top10/../ext/django/core/servers/basehttp.py", line 280, in run
self.result = application(self.environ, self.start_response)
File "/var/www/html/top10/top10/../ext/django/core/servers/basehttp.py", line 674, in __call__
return self.application(environ, start_response)
File "/var/www/html/top10/top10/../ext/django/core/handlers/wsgi.py", line 245, in __call__
response = middleware_method(request, response)
File "/var/www/html/top10/top10/page/middleware.py", line 8, in process_response
if response.status_code != 404:
AttributeError: 'str' object has no attribute 'status_code'
提前谢谢。
答案 0 :(得分:1)
我不确定我是否理解正确...你是说你的观点没有被称呼?
如果您已经设置了一些中间件类,那么处理请求的流在之前(和之后)通过中间件是正常的,它会到达您的视图。
以下是一些文档:
https://docs.djangoproject.com/en/dev/topics/http/middleware/?from=olddocs
在你的中间件类中,当它到达方法时,你应该能够看到url解析器将调用哪个视图函数: process_view(self,request,view_func,view_args,view_kwargs)
如果我不太明白你的问题,请告诉我。
答案 1 :(得分:1)
getdata
视图返回字符串作为响应而不是HttpResponse对象,因此中间件中的process_response
获取字符串而字符串没有status_code
方法。将您的观点更改为:
def getdata(request, resource):
#...
return HttpResponse(r.content, mimetype="text/plain")
答案 2 :(得分:0)
想出来。 Django实际上正确地击中了视图。由于在getdata视图中发出了格式错误的url请求,因此api抛出了一个错误。我非常愚蠢。