Search code examples
pythoncherrypy

Cherrypy handling requests differently


I am trying to figure out a way where I need to have two different pages calling one function and the function will handle the requests accordingly based on which function called.

The flow can be either the predict function handles based on the calling function or that it will return a value to the calling function and then the calling function page reloads to show the result as it has to be shown.

Class GSpam:

    @cherrypy.expose
    def main(self,contents=""):
        return call predict

    @cherrypy.expose
    def alt(self):
        return """<html>
        <div align=center>
          <body>
        <br>
        <br>
            <form method="post" action="predict">
              <input type="text" value="Enter post to check" name="text" />
              <button type="submit">Predict!</button>
            </form>
        </div>
          </body>
        </html>"""

    @cherrpy.expose
    def predict(self,text):
        do some stuff
        check which function called and return accordingly
        return result

if __name__ == '__main__':
    port = 80
    api = cherrypy.dispatch.RoutesDispatcher()
    api.connect('home','/',controller=GSpam,action='main')
    conf = {'/': {'request.dispatch': api}}
    cherrypy.config.update({
        'server.socket_host' : "0.0.0.0",
        'server.socket_port' : int(port),
        'server.thread_pool' : 10,
        'engine.autoreload.on' : False,
        'response.timeout' : 10
    })
    app=cherrypy.tree.mount(root=None,config=conf)

I haven't used cherrypy before. Any help is appreciated.


Solution

  • How about creating a private method:

    class GSpam:
    
       def _predict(self, text, from_='original'):
           if from_ == 'original':
              return "Something very different"
           else:
              return "Content for %s" % from_
    
       @cherrypy.expose
       def main(self,contents=""):
           return self._predict(contents, 'main')
    
       @cherrypy.expose
       def alt(self):
           return """<html>
           <div align=center>
             <body>
           <br>
           <br>
               <form method="post" action="predict">
                <input type="text" value="Enter post to check" name="text" />
                <button type="submit">Predict!</button>
               </form>
           </div>
             </body>
           </html>"""
    
       @cherrypy.expose
       def predict(self, text):
           #do some stuff
           result = self._predict(text)
           return result