Python webapp2项目结构配置

Python webapp2项目结构配置,python,python-2.7,webapp2,google-app-engine-python,Python,Python 2.7,Webapp2,Google App Engine Python,我想像下一个结构一样组织我的项目,但是当我尝试测试它时,我遇到了一个问题 在handlers文件夹中,我有一个名为Base.py的文件,其中有一个类: def get_success_reponse(**kwargs): kwargs.update( dict( status="SUCCESS", ) ) return kwargs class BaseHandler(webapp2.RequestHandler)

我想像下一个结构一样组织我的项目,但是当我尝试测试它时,我遇到了一个问题

在handlers文件夹中,我有一个名为Base.py的文件,其中有一个类:

 def get_success_reponse(**kwargs):
     kwargs.update(
       dict(
        status="SUCCESS",
       )
     )
     return kwargs

 class BaseHandler(webapp2.RequestHandler):
       property = 0
在同一个文件夹处理程序中,我有另一个文件名为:EchoHandler.py,其中有一个类

import Base

class EchoHandler(Base.BaseHandler):
    def post(self): 
        logger.info("test")       
        data = json.loads(self.request.body)
        echo = data.get("echo")
    return self.json_data(get_success_reponse(echo))
我的main.py文件看起来像

 import webapp2
 import config

 app = webapp2.WSGIApplication([
      webapp2.Route('/x/v1/echo', handler='handlers.EchoHandler')
 ], debug=True, config=config.WEBAPP2CONFIG)
我的app.yaml

runtime: python27
api_version: 1
threadsafe: false

handlers:
- url: /x/.*
  script: main.py  

libraries:
- name: webapp2
  version: latest
- name: jinja2
  version: latest
- name: ssl
  version: latest
问题

当我发出POST请求以发送此数据时:

  {
    "echo": "Test"
  }
我收到一个响应“200OK”,但我没有得到任何json响应,没有写入日志

如果我将此“”更改为“”,我也会收到200 ok


你能帮我吗?

这是一个很老的问题,但我还是要回答它。在返回之前,确保正在将数据写入处理程序中的响应对象。您没有为
self.json\u data()
方法提供代码,但是我假设您没有将json数据写入响应对象,即使您正在返回它。此外,这可能只是问题中的一个输入错误,但看起来您的
返回self.json\u数据(get\u success\u response(echo))
行未插入。它应该与post()代码的其余部分处于相同的缩进级别

无论如何,请尝试以下方法:

import Base
import json

class EchoHandler(Base.BaseHandler):
    def post(self): 
        logger.info("test")       
        data = json.loads(self.request.body)
        echo = data.get("echo")

        # get the dict you want to convert to JSON
        echo_dict = get_success_response(echo)

        # convert it to a JSON string
        echo_json = json.dumps(echo_dict)

        # set the content type of the Response to JSON
        self.response.content_type = 'application/json'

        # write the JSON to the Response body and return the Response
        return self.response.write(echo_json)
您需要将数据写入响应,以便将该数据发送到客户端。您不需要在写入响应对象后返回它,但我还是喜欢这样做,因为我认为它看起来更清晰

而且,你的路线看起来很混乱。尝试将main.py更改为:

 import webapp2
 import config

 # changed the lazy import line (handler='handlers.EchoHandler.EchoHandler')
 app = webapp2.WSGIApplication([
      webapp2.Route('/x/v1/echo', handler='handlers.EchoHandler.EchoHandler')
 ], debug=True, config=config.WEBAPP2CONFIG)
或者,我可以通过实际将处理程序导入main.py:

 import webapp2
 import config
 from handlers import EchoHandler

 # note: no quotes around EchoHandler.EchoHandler
 app = webapp2.WSGIApplication([
      webapp2.Route('/x/v1/echo', handler=EchoHandler.EchoHandler)
 ], debug=True, config=config.WEBAPP2CONFIG)