Setting request level cache control

In Flask, we can modify the response headers before we send the response back to the client. This can be done fairly easily. The following example shows a simple view implementing response-specific header control:

from bugzot.application import app, db
from bugzot.models import User
from flask.views import MethodView
from flask import render_template, session, request, make_response

class UserListView(MethodView):
"""User list view for displaying user data in admin panel.

The user list view is responsible for rendering the table of users that are registered
in the application.
"""

def get(self):
"""HTTP GET handler."""

page = request.args.get('next_page', 1) # get the page number to be displayed
users = User.query.paginate(page, 20, False)
total_records = users.total
user_records = users.items

resp = make_response(render_template('admin/user_list.html', users=user_records, next_page=page+1))
resp.cache_control.public = False
return resp

In this example, we first use the make_response() method of Flask to build a response with the render_template call. The next thing we do here is set the cache-control to use the private cache for holding the response data using the resp.cache_control.public property. Once we have the headers set, all we have to return is the modified response back to the client.

Wasn't this quite simple to use while providing a lot of benefits? With this kind of approach, we can set the cache for static files to be maintained for a longer duration, hence providing speedup in terms of page loading while also reducing data usage.

Now, let's take a look at a slightly more sophisticated way of utilizing the client storage to store some frequently accessed data, so that we can avoid making web requests when a user requests the same data again and again.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.172.146