简体   繁体   中英

How can I generate multiple URL paths with cherrypy?

I feel like I'm running into a brick wall, as I'm not getting anywhere with this, and I believe, simple task.

I'm trying to generate a URL by the likes of '/path/to/url', but upon gazing at multiple StackOverflow Q&A's, the official documentation for cherrypy, I still cannot seem to wrap my head around the issue.

Here's my code so far:

import details
import input_checker as input
import time

import cherrypy

class Index(object):

    @cherrypy.expose
    def input(self):
        return input.check_input()

    @cherrypy.expose
    def stream(self):
        while True:
            return 'Hey'
            #return input.check_input()
            time.sleep(3)

if __name__ == '__main__':
    index = Index()
    cherrypy.tree.mount(index.stream(), '/input/stream', {})
    cherrypy.config.update(
        {'server.socket_host': '0.0.0.0'})
    cherrypy.quickstart(index)

So essentially, I want to be able to visit http://127.0.0.1:8080/input/stream , and I will be returned with the given result.

After executing this code, and multiple variants of it, I'm still being returned with a 404 not found error, and I'm not sure what I need to do, in order to get it working.

Any tips and/or supporting documentation that I may have skimmed over?

Thanks guys.

So there are couple problems here, why do you use MethodDispatcher do you actually need it?

To serve you stream function on /input/stream you have to mount it as such:

cherrypy.tree.mount(index.stream(), '/input/stream', your_config)

note /input/stream instead of /stream .

But because you're using MethodDispatcher this will likely make your endpoint return 405 as GET is not allowed on this endpoint - to fix that just remove the MethodDispatcher bit.

But if you do require MethodDispatcher you will have to refactor a bit to something like that:

class Stream:
    exposed = True # to let cherrypy know that we're exposing all methods in this one

    def GET(self):
        return something

stream = Stream()
cherrypy.tree.mount(stream , '/index/stream',
    {'/':
        {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}
    }
)

Also make sure to not actually call your methods when mounting them into cherrypy tree, just pass in the name of the function/class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM