Search code examples
pythonweb-applicationscherrypy

Calling the same endpoint more than once in Cherrypy


I have created a simple web server with Cherrypy and my resources are only available the first time I make the call.

For example:

When I put the following on the browser http://127.0.0.1:8080/catalog/about - it displays the Cherrypy version as{"version": "18.1.1"} - which is correct.

However, If I hit enter one more time I get the following "404 Not Found"

Is this a safety feature and how do I change this settings? I don't understand

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

Solution

  • Found the issue - the problem is that I am using the same name for the method and variable inside. I am used to Java where I have no such issues.

    So, instead of

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

    change to

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

    Success!