Search code examples
pythonhttprequestcherrypy

Make HTTP request with cherrypy


I've searched for a long time but I can't find any documentation on how to create an HTTP request with cherrypy.

I want to achieve something like this:

@cherrypy.expose
def index(self):

    json = http_request("http://somesite/")

    processed = process_json(json)

    tmpl = env.get_template("template.html")
    return tmpl.render(data=processed)

Any idea how I can achieve this?


Solution

  • You want urllib if you're talking about python 3.

    import urllib.request
    
    @cherrypy.tools.json_in() 
    @cherrypy.expose
    def index(self):    
        httpreq = urllib.request.Request(url="http://somesite/")
        response = urllib.request.urlopen(httpreq)
        jsonobject = response.read()
    

    Let me know if you need another version of python.

    Hope this helps!