pythoncherrypycheetah

calling a function with cherry.py


So im doing a bit of web development, and due to some restriction set by my employer i need to use cheetah and cherrypy. I have this form that upon submit runs a function, and from said function i call another via HTTPRedirect, and what i want is to call it without redirecting. here is an example

@cherrypy.expose
def onSubmit(**kwargs):
  ##Do something
  ##Do something
  ##Do something

  raise cherrypy.HTTPRedirect("/some_other_location/doSomethingElse?arg1=x&arg2=y")

now i want to do more stuff after running the second function, but i cant because since i redirect the code ends there. So my question is, is there a way to run that other function and not redirect, but still using HTTP. In javascript i would use AJAX and pass it the url, storing the output on the loader variable, but im not sure how to do this with cherrypy


Solution

  • Instead of doing the redirect, use one of the standard Python libraries for fetching HTTP data:

    or other arguably nicer third-party ones:

    Also, don't forget to convert the relative url to an absolute url, even if it's localhost:

    To help you get started, here's an untested code snippet derived from your example, using urllib2:

    import urllib2
    
    @cherrypy.expose
    def onSubmit(**kwargs):
      ##Do something
      ##Do something
      ##Do something
    
      url = "http://localhost/some_other_location/doSomethingElse?arg1=x&arg2=y"
    
      try:
        data = urllib2.urlopen(url).read()
      except urllib2.HTTPError, e:
        raise cherrypy.HTTPError(500, "HTTP error: %d" % e.code)
      except urllib2.URLError, e:
        raise cherrypy.HTTPError(500, "Network error: %s" % e.reason.args[1])
    
      ##Do something with the data