app-engine: Request Data
-
13-03-2021 - |
Domanda
in my webapp2.RequestHandler method:
I want to find out which uri the requester want to get. for example, if the user wants to get "http://www.mysite.com/products/table" I want to get into a variable the value "table" (in this case)
when I print "self.request" I see all the values of RequestHandler class but I didn't managed to find out what is the right attribute in my case.
I'm sure the question is an easy-one for you, but I'm just a starter in python and app-engine framework.
Soluzione
Looked into how URLs should be handled, and wildcard URLs. Try this:
class ProductsHandler(webapp.RequestHandler):
def get(self, resource):
self.response.headers['Content-Type'] = 'text/plain'
table = self.request.url
self.response.out.write(table)
self.response.out.write("\n")
self.response.out.write(resource)
def main():
application = webapp.WSGIApplication([
('/products/(.*)', ProductsHandler)
],
debug=True)
util.run_wsgi_app(application)
When I go to the URL http://localhost:8080/products/table
, I get this result:
The resource
parameter of the get
function is passed in automatically by the WSGIApplication
url_mapping
, because it is mapped to:
('/products/(.*)', ProductsHandler)
The (.*)
is a wildcard, and gets passed in as a method parameter.
You could name the parameter in the get
method anything you want instead of resource
, such as table
. It wouldn't make a lot of sense though, because if you pass in a url like http://localhost:8080/products/fish
, it would no longer contain the word "table".
Earlier attempt (before edits):
Try something like this:
class MainHandler(webapp.RequestHandler):
def get(self):
table = self.request.url
self.response.out.write(table)
For my test, I went to http://localhost:8080/
, and it printed out: