【发布时间】:2011-06-05 17:19:00
【问题描述】:
# /test{.format} no longer seems to work...
config.add_route('test', '/test.{ext}', view='ms.views.test')
views.py:
from pyramid.response import Response
from pyramid.renderers import render
import json
def test(request):
extension = request.matchdict['ext']
variables = {'name' : 'blah', 'asd' : 'sdf'}
if extension == 'html':
output = render('mypackage:templates/blah.pt', variables, request=request)
if extension == 'json':
output = json.dumps(variables)
return Response(output)
有没有更简单的方法来做到这一点?使用 Pylons,这很简单:
def test(self, format='html'):
c.variables = {'a' : '1', 'b' : '2'}
if format == 'json':
return json.dumps(c.variables)
return render('/templates/blah.html')
我怀疑我用错了方法...?
【问题讨论】:
-
您的抱怨是什么?您是否在抱怨金字塔与塔有不同的 API?如果您不喜欢金字塔 API,为什么不回到 Pylons?
-
Pyramid 不使用中间件吗?为什么不能根据用户请求呈现 JSON?在我的书中,直接在视图内部进行操作是一个错误的解决方案。如果可能,请利用中间件。