简体   繁体   English

使用微服务的Python Falcon微服务?

[英]Python Falcon microservice that uses microservice?

I'm just getting started with Falcon and I'm trying to do something that I think should be very simple and basic. 我刚刚开始使用Falcon,我正在尝试做一些我认为应该非常简单和基本的事情。 I simply want one of my services to send a request to another one. 我只希望我的一项服务将请求发送到另一项。

Let me make it even more simple with a tiny code example. 让我用一个很小的代码示例使它更加简单。 Here are two microservices. 这是两个微服务。 Service #1 stores a number, and service #2 increments a stored number. 服务1存储一个号码,服务2增加一个存储的号码。

class NumberResource:
    def on_post(self, req, resp):
        self.value = req.media.get('value')
        resp.media = {'value': self.value}

    def on_get(self, req, resp):
        resp.media = {'value': self.value}

class NextNumberResource:
    def on_get(self, req, resp):
        sibling = {}
        # TODO sibling = get("/number")
        resp.media = {'value': sibling.value+1}

api = falcon.API()
api.add_route('/number', NumberResource())
api.add_route('/next', NextNumberResource())

Now I can store the number 17: 现在我可以存储数字17:

curl http://localhost:8000/number -d '{"value":17}'

And I can retrieve the stored value: 我可以检索存储的值:

curl http://localhost:8000/number
{"value": 17}

I want to fill in the TODO line so that I can retrieve the calculated value: 我想填写TODO行,以便可以检索计算出的值:

curl http://localhost:8000/next
{"value": 18}

What's the best way to do that? 最好的方法是什么?

The best way to do this would be via OOP pattern in Python. 最好的方法是通过Python中的OOP模式。 An example could be like this (Albeit, it needs more defensive programming + serialization/de-serialization) 这样的例子可能是这样(尽管它需要更多防御性编程+序列化/反序列化)

class SomeLogicHandler():

    myValue #Important to have myValue as class variable and not as instance variable.

    def __init__(self):
        super(SomeLogicHandler, self).__init()
        self.updateMyValue = self._updateMyValue
        self.getMyValue = self._getMyValue

    def _updateMyValue(self, value):
        self.myValue+= value

    def _getMyValue(self):
        return {value: self.myValue}

class ApiRouteHandler(SomeLogicHandler):

    def __init__(self):
        super(ApiRouteHandler, self).__init__()

    def on_post(self, req, resp):
        #post implementation.
        self.updateMyValue(req.media.get('value'))


class ApiRouteHandler2(SomeLogicHandler):

    def __init__(self):
        super(ApiRouteHandler2, self).__init__()

    def on_get(self, req, resp):
        #get implementation.
        resp.body = self.getMyValue()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM