简体   繁体   English

具有多个 response.out.write 语句的 Python 方法

[英]Python method with multiple response.out.write statements

Could someone please confirm for me whether the following should work in Python?有人可以帮我确认以下内容是否适用于 Python? Someone calls the server and the response can be return in a number of ways.有人调用服务器,可以通过多种方式返回响应。 Instead of using nested "ifs" I was hoping to do as follows:而不是使用嵌套的“ifs”,我希望这样做如下:

    def get(self):
        self.response.headers['Content-Type'] = 'application/json'
        data = fromLocationOne()
        if data is not None:
            return self.response.out.write(json.dumps(data))
        data = fromLocationTwo()
        if data is not None:
            return self.response.out.write(json.dumps(data))
            data = fromLocationThree()
        if data is not None:
            return self.response.out.write(json.dumps(data))

Yes it will work for simplicity you can replace if data is not None: by if data:是的,为简单起见, if data is not None: if data:

If it was me I would write it as following如果是我,我会写如下

def get(self):
    self.response.headers['Content-Type'] = 'application/json'
    functions = [fromLocationOne, fromLocationTwo, fromLocationThree]
    for f in functions:
      data = f()
      if data:
        return self.response.out.write(json.dumps(data))

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

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