How can you determine if webapp2 called your function or if it was another method in Python?

StackOverflow https://stackoverflow.com/questions/21899416

  •  14-10-2022
  •  | 
  •  

Question

I have a a route that is defined like this:

webapp2.Route(r'/test/<var1>', handler="handlers.Test.test", methods="GET")

the handler looks like this:

def test(self, var1=None):

when I call it from a url such as (Case A):

http://localhost:8080/test/helloworld

I get the variable

var1=helloworld 

which is pretty cool. Now lets say instead of calling it from a URL I instead want to call it from another function ala (Case B):

def calltest(self):
    self.test(helloworld)

How can I determine that in case A it's being called from the webapp2 Route and in case B I can tell it's being called from another function with the app itself?

The why of this in case A I want to return JSON since the browser doesn't speak Python and in case B I want to return an object since the calling function is itself in Python so it can understand that return type.

As a possible side note this is my attempt at getting double use of the same method, this is somewhat what I suppose something like Endpoints is trying to achieve, but it seems easy enough this way as well if I can case the return based in the caller.

Thanks!

Shaun

Était-ce utile?

La solution

I'm not familiar with webapp2, but something like the following might work:

def test(var1=None):
    return { var1: var1 }


def calltest():
    d = test()
    print(d['var1'])


def disp(router, request, response):
    rv = router.default_dispatcher(request, response)
    # turn dict into json and craft the response
    return webapp2.Response(json.dumps(rv))
    # alternatively, you could make your handlers return objects with a .json()
    # method and call that


app = webapp2.WSGIApplication([
    webapp2.Route(r'/test/<var1>', handler=test, methods="GET"),
])

app.router.set_dispatcher(disp)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top