【问题标题】:Python method with multiple response.out.write statements具有多个 response.out.write 语句的 Python 方法
【发布时间】:2021-07-18 13:44:47
【问题描述】:

有人可以帮我确认以下内容是否应该在 Python 中工作吗?有人调用服务器,可以通过多种方式返回响应。而不是使用嵌套的“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))

【问题讨论】:

  • 您将data = fromLocationThree() 缩进得太远了,但除此之外,我认为这会起作用——您真的尝试过吗?请注意,您可以将其大大简化为 data = fromLocationOne() or fromLocationTwo() or fromLocationThree()(假设这些函数除了 None 是 false 之外没有其他可能的返回值,例如空列表或字典)。

标签: python json python-2.7 httpresponse google-app-engine-python


【解决方案1】:

是的,为了简单起见,您可以将 if data is not None: 替换为 if data:

如果是我,我会这样写

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    相关资源
    最近更新 更多