根据 .{Type} 使用 web.py 返回 JSON、XML 或其他格式

1 投票
1 回答
1547 浏览
提问于 2025-04-17 13:36

我正在尝试根据URL末尾的.{Type}来设置RESTful API的响应类型,使用的是web.py。

我该如何将.JSON、.XML、.HTML或者其他格式传递给“Assignments”这个类,或者在某个地方设置一个值,以便ServerResponse能够接收到并以正确的格式进行响应呢?

我尝试过:

'/assignments(\.[:upper:]+)', 'Assignments'

我在我的网址中使用了以下代码:

urls = (
    '/(.*)/', 'redirect',
    '/', 'Homepage',
    '/assignments', 'Assignments'
)

我有一个名为“Assignments”的类:

class Assignments:
    def GET(self,responseType):
        sentData = web.data()
        query = JSON.decode(sentData,'unicode')
        # \/ Replace With Code \/
        data = query 
        # /\ Replace with Code /\
        return ServerResponse.Send(data,responseType)

    def POST(self,responseType):
        sentData = web.data()
        query = JSON.decode(sentData,'unicode')
        # \/ Replace With Code \/
        data = query 
        # /\ Replace with Code /\
        return ServerResponse.Send(data,responseType)

还有我的ServerResponse类:

class ServerResponse:
    @staticmethod
    def Send(data, method):
        return getattr(ServerResponse, method)(data)

    @staticmethod
    def JSON(data):
        web.header('Content-Type', 'application/json')
        response = JSON.encode(data)
        return response

    @staticmethod
    def XML(data):
        pass

    @staticmethod
    def HTML(data):
        web.header('Content-Type', 'text/html')
        response  = "<html>"
        response += "<head></head>"
        response += "<body>"
        response += "{"
        for key in data:
            response += "%s:%s,\n" % (str(key), str(data[key]))
        response += "}"
        response += "</body>"
        response += "</html>"
        return response

1 个回答

2

我尝试为web.py实现一个简单的restful控制器,目前在一个项目中使用它来和backbone.js进行通信,你可以在这里查看:https://gist.github.com/3907294

另外,还有一个你可能会觉得有用的项目,叫做https://github.com/martinblech/mimerender,它主要是通过检查http的接受头来确定渲染格式。

撰写回答