【问题标题】:Calling the same endpoint more than once in Cherrypy在 Cherrypy 中多次调用同一个端点
【发布时间】:2023-03-12 06:58:02
【问题描述】:

我用Cherrypy 创建了一个简单的网络服务器,我的资源仅在我第一次拨打电话时可用。

例如:

当我将以下内容放在浏览器 http://127.0.0.1:8080/catalog/about 上时 - 它会将 Cherrypy 版本显示为{"version": "18.1.1"} - 这是正确的。

但是,如果我再按一次回车,我会得到以下“404 Not Found

这是一项安全功能吗?如何更改此设置?我不明白

server.py:

import os
import os.path
import random
import string
import json
import cherrypy
from controller import Catalog

class Server(object):

  @cherrypy.expose
  def index(self):
    return open('../cococlient/build/index.html')

def cors():
  cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"

if __name__ == '__main__':
    conf = {
        '/': {
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/catalog': {
            'tools.CORS.on': True,
            'tools.response_headers.on': True
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': '../cococlient/build/static'
        }
    }

    server = Server()
    server.catalog = Catalog()
    cherrypy.tools.CORS = cherrypy.Tool('before_handler', cors)

    # cherrypy.tree.mount(server, '/', conf)
    # cherrypy.engine.start()
    # cherrypy.engine.block()

    cherrypy.quickstart(server, '/', conf)

controller.py:

import cherrypy

class Catalog(object):

  @cherrypy.expose
  @cherrypy.tools.json_out()
  def about(self):
    self.about = {
        "version": cherrypy.__version__
    }
    return self.about

【问题讨论】:

    标签: python web-applications cherrypy


    【解决方案1】:

    找到了问题 - 问题是我对内部的方法和变量使用了相同的名称。我习惯了没有此类问题的 Java。

    所以,而不是

      @cherrypy.expose
      @cherrypy.tools.json_out()
      def about(self):
        self.about = {
            "version": cherrypy.__version__
        }
        return self.about
    

    改成

      @cherrypy.expose
      @cherrypy.tools.json_out()
      def about(self):
        self.someOtherName = {
            "version": cherrypy.__version__
        }
        return self.someOtherName
    

    成功了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2022-01-14
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多