I'm building an app using someone else's API allowing the user to browse content from their site. The user can log into my project with their credentials from this other site in order to "favorite" content from their site.
When they log in, I get a user_token for them. To avoid having to create a user file for them, I just store this token as a session variable:
# Set session
request.session.set_expiry(60 * 60)
# Save token in session
request.session['user_token'] = unicode(auth.Message)
I'm also using file caching for the content from the site:
CACHE_BACKEND = 'file:///..../cache/'
And using the @cache_page command before certain views to cache the data:
@cache_page(CACHE_TIME)
def listings_by_cat_page(request, category_id):
# view stuff here
The problem when I'm running into is when a user vie开发者_如何学Gows the home screen (which is cached), clicks log in, logs in, and then returns to the home screen, the Login/Logout button doesn't know to switch. I'm assuming it's because since it's a cached page, it doesn't see the user_token session variable.
{% if not request.session.user_token %}
<a href="/login{% comment %}?next={{ request.path }}{% endcomment %}" class="login">Login</a>
{% else %}
<a href="/logout/" class="login">Logout</a>
{% endif %}
Ideally, I'd like to cache the content, but have the page recognize the change in the request.session variables.
Any ideas?
Modify the Vary
header and django will generate a new cache key.
Update: I think you should go for the cookie method, as the SessionMiddleware
already sets the appropriate Vary headers which is why with Auth, the caching works correctly.
Since you only want to set this once, the cookie method is the way to go I think.
Whichever view handles the logging in of the API method should set a cookie that is a secure hash of the user token and the rest should work, if my thinking is correct.
use {% cache %}
tag to cache only parts of the page that are user-independent.
精彩评论