I'm a beginner and am wondering why we use self.response.out.write instead of print, and why we use classes, instead of functions, for the request handlers in the first place. Are there any special reasons?
Why does GAE use classes and self.response.out.write over functions and print?
775 Views Asked by Han At
1
There are 1 best solutions below
Related Questions in PYTHON
- new thread blocks main thread
- Extracting viewCount & SubscriberCount from YouTube API V3 for a given channel, where channelID does not equal userID
- Display images on Django Template Site
- Difference between list() and dict() with generators
- How can I serialize a numpy array while preserving matrix dimensions?
- Protractor did not run properly when using browser.wait, msg: "Wait timed out after XXXms"
- Why is my program adding int as string (4+7 = 47)?
- store numpy array in mysql
- how to omit the less frequent words from a dictionary in python?
- Update a text file with ( new words+ \n ) after the words is appended into a list
- python how to write list of lists to file
- Removing URL features from tokens in NLTK
- Optimizing for Social Leaderboards
- Python : Get size of string in bytes
- What is the code of the sorted function?
Related Questions in GOOGLE-APP-ENGINE
- AngularJS, Google App Engine and URLrewrite
- Optimizing for Social Leaderboards
- Getting entity with a join table GAE
- Custom exception message from google endpoints exception
- Unable to deploy an application module on AppEngine
- How to use CachedRowSet in Google App Engine?
- How can I create a docker image from the current system?
- Google datastore multiple values for the same property
- Google Cloud Storage sort directory by name
- Adding custom domain for Google App Engine WordPress site
- Arguments to Endpoints method change order
- Could someone bring Google OAuth2 for Cloud DNS via Rest to light?
- DNS_PROBE_FINISHED_NXDOMAIN on Google App Engine website
- GAE python - client_secrets.json 'File not found' - app.yaml error?
- Images not working in Google App Engine email
Related Questions in WEBAPP2
- Sharing webapp2 session between GAE python modules with custom domain?
- GAE webapp2 delete all UserTokens (drop all sessios) for specific user
- Google App Engine: Uploading and serving a blob using webapp2
- Inheritance in webapp2
- "Lost data" while processing data in WTForm
- Save as dialog not showing
- Python Webapp2 GAE email send issue
- How to override the self.request.host in a webapp2 handler unit test?
- My code isn't giving correct output
- Can I modify response content before the formatter processes it?
- Why does GAE use classes and self.response.out.write over functions and print?
- Google App Engine: webapp2 routing not working
- Is it possible to redirect to different domain retaining the trailing endpoint, from a route?
- How to redirect in webapp2
- Dynamic callback URL in Simpleauth
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Using Methods
Each handler class has methods with names like
getandpost, after the HTTP methodsGETandPOSTetc. Those methods are functions that handle requests.Each request to your server will be routed to a request handler object, which is a new instance of some request handler class. So, a request handler instance is created per request, and is garbage collected once its HTTP response is sent.
By inheriting from
webapp2.RequestHandler, your handler classes get a bunch of functionality out the box for free. For example, handler instances will have the data from the HTTP request parsed into dictionaries and bound toselfasself.request.headersandself.request.bodyautomatically.The
webapp2.RequestHandlerclass also providesself.response, which is what you write your response data to.Once the new request handler instance is initialised, the inherited
__init__method calls the method that maps to the HTTP request method, so assuming aGETrequest, it callsself.get. Thewebapp2.RequestHandlerclass doesn't implement those methods; your derived class does.Responding
Neither
printnor the return value of the handler method are used here. You do not 'return a response' with this framework; you write the response to the request handler instance's (inherited)self.responseproperty.Your instance inherits
self.response.out.write(which is aliased toself.response.write), which concatenates its argument to the body of the response, initially an empty string.Note: You can call
self.response.clearto clear the response body.When you return from your handler method -
getorpostetc. - the return value is ignored. The framework uses the state ofself.responseto automatically create and send a HTTP response for you.There's a bunch of subtleties that the framework takes care of behind the scenes too.
Classes Over Functions
The main advantage is in inheritance. Normally, you'll create a single
BaseHandlerclass that derives fromwebapp2.RequestHandler. TheBaseHandlerclass will contain the core functionality for your actual handlers. It might include some logic for converting data into little JSON packages for a Web API, for example. All of the classes that actually handle requests would then be derived from yourBaseHandler.You want a custom base class for your handler classes to derive from mainly so you can edit that base class. You want that base class to inherit from
webapp2.RequestHandlerso that all your handler instances inherit the framework magic.There is enough slight of hand to make the whole thing confusing, but it is easy to make sense of once you get it, and does save a lot of trouble.
Technically, you could achieve all of the above just using functions and dictionaries, but Python is classically object oriented, so it would be painful and weird.