【问题标题】:Responding with JSON, XML, or Other, based on .{Type} using web.py使用 web.py 基于 .{Type} 以 JSON、XML 或其他方式响应
【发布时间】:2013-01-25 01:34:27
【问题描述】:

我正在尝试基于 URL 末尾的 .{Type} 为使用 web.py 的 RESTful API 设置响应类型。

如何将 .JSON、.XML、.HTML、.(whatever) 传递给“Assignments”类或将其设置为某处的值,以便 ServerResponse 可以接收它并以正确的格式响应?

我试过了:

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

我正在为我的网址使用以下代码:

urls = (
    '/(.*)/', 'redirect',
    '/', 'Homepage',
    '/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

【问题讨论】:

    标签: python url rest web.py


    【解决方案1】:

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

    另外,https://github.com/martinblech/mimerender 您可能会觉得有用,但它会检查 http 接受标头以确定呈现格式。

    【讨论】:

    • 如果我正确理解您的代码,那么我需要查看的代码是:resources(?:/(?P[0-9]+))?(?: \.(?P[a-z]+))?',特别是 ?(?:\.(?P[a-z]+))?部分...这似乎需要 a 之后的任何内容。并将其发送到可变格式?对吗?
    • 看来这个字符串 dd 正是我需要的:(?:\.(?P[A-Z]+))?谢谢!
    • 是的,web.py 将正则表达式应用于 url,并将捕获组发送到控制器参数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多