Last active
August 29, 2015 14:16
-
-
Save zaki-yama/3287cbd4e417e9de0d26 to your computer and use it in GitHub Desktop.
DjangoのClass-based view用@login_required
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| from django.http import HttpResponsePermanentRedirect | |
| from google.appengine.api import users | |
| def login_required(handler_method): | |
| u"""Django の Class-based view 用デコレータ | |
| Example: | |
| class MyView(View): | |
| @login_required | |
| def get(self, request): | |
| user = users.get_current_user() | |
| ... | |
| """ | |
| def check_login(self, request, *args): | |
| user = users.get_current_user() | |
| if not user: | |
| login_url = users.create_login_url(request.get_full_path())) | |
| return HttpResponsePermanentRedirect(login_url) | |
| else: | |
| return handler_method(self, request, *args) | |
| return check_login |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def login_required(handler_method): | |
| """A decorator to require that a user be logged in to access a handler. | |
| To use it, decorate your get() method like this: | |
| @login_required | |
| def get(self): | |
| user = users.get_current_user(self) | |
| self.response.out.write('Hello, ' + user.nickname()) | |
| We will redirect to a login page if the user is not logged in. We always | |
| redirect to the request URI, and Google Accounts only redirects back as a GET | |
| request, so this should not be used for POSTs. | |
| """ | |
| def check_login(self, *args): | |
| if self.request.method != 'GET': | |
| raise webapp.Error('The check_login decorator can only be used for GET ' | |
| 'requests') | |
| user = users.get_current_user() | |
| if not user: | |
| self.redirect(users.create_login_url(self.request.uri)) | |
| return | |
| else: | |
| handler_method(self, *args) | |
| return check_login |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
util.py は GAE SDK の appengine/ext/webapp/util.py より引用