如何使用spyne构建REST层次结构

时间:2014-01-06 19:57:50

标签: rest spyne

我正在尝试使用spyne构建REST Web服务。到目前为止,我已经能够使用ComplexModel来表示我的资源。像这样的非常基本的东西(从例子中借用):

class Meta(ComplexModel):
    version = Unicode
    description = Unicode

class ExampleService(ServiceBase):
    @srpc(_returns=Meta)
    def get_meta():
        m = Meta()
        m.version="2.0"
        m.description="Meta complex class example"
        return m


application = Application([ExampleService],
    tns='sur.factory.webservices',
    in_protocol=HttpRpc(validator='soft'),
    out_protocol=JsonDocument()
)

if __name__ == '__main__':    
    wsgi_app = WsgiApplication(application)
    server = make_server('0.0.0.0', 8000, wsgi_app)
    server.serve_forever()

要运行我使用curl -v“http://example.com:8000/get_meta”,我得到了我期望的结果。

但是,如果我想访问某些资源层次结构,例如http://example.com:8000/resourceA/get_meta ??

,该怎么办?

谢谢你的时间!

1 个答案:

答案 0 :(得分:1)

两个选项:静态和动态。这是静态的:

from spyne.util.wsgi_wrapper import WsgiMounter

app1 = Application([SomeService, ...
app2 = Application([SomeOtherService, ...

wsgi_app = WsgiMounter({
    'resourceA': app1,
    'resourceB': app2,
})

今天有效。请注意,您可以堆叠WsgiMounter

对于动态的,你应该使用HttpPattern()。我认为这仍然是实验性的,因为我不喜欢实现,但这适用于2.10.x,werkzeug,pyparsing< 2和WsgiApplication:

class ExampleService(ServiceBase):
    @rpc(Unicode, _returns=Meta, _patterns=[HttpPattern("/<resource>/get_meta")])
    def get_meta(ctx, resource):
        m = Meta()
        m.version = "2.0" 
        m.description="Meta complex class example with resource %s" % resource
        return m

不要忘记打开验证并对resource类型设置一些限制以防止DoS攻击并抛出TypeError等等。我会这样做:

ResourceType = Unicode(24, min_len=3, nullable=False, 
                       pattern="[a-zA-Z0-9]+", type_name="ResourceType")

请注意,您还可以将http谓词与HttpPattern匹配。 e.g。

HttpPattern("/<resource>/get_meta", verb='GET')

HttpPattern("/<resource>/get_meta", verb='(PUT|PATCH)')

不要使用主机匹配,从2.10开始,它已经坏了。

此外,由于Spyne的这一点被标记为实验性的,它的api可以随时改变。

我希望这会有所帮助

相关问题