tipfy - ユーザー認証チュートリアル

ちょっとしたアプリを作るときに、必ず必要になるのがユーザー認証の機能です。tipfy はあらかじめ幾つかの認証方法をサポートしています。

これらの認証機能を組み合わせて使ったり、自前の認証機能を作って使うことができるそうです。

App Engine の Google アカウント認証

config.py で tipfy.ext.user を有効にする

   1 # -*- coding: utf-8 -*-
   2 """
   3     config
   4     ~~~~~~
   5 
   6     Configuration settings.
   7 
   8     :copyright: 2009 by tipfy.org.
   9     :license: BSD, see LICENSE for more details.
  10 """
  11 config = {}
  12 
  13 # Configurations for the 'tipfy' module.
  14 config['tipfy'] = {
  15     # Some extensions enabled by default: interactive debugger,
  16     # internationalization and user accounts.
  17     'extensions': [
  18         'tipfy.ext.debugger',
  19         'tipfy.ext.i18n',
  20         'tipfy.ext.user',          # <<<<<<<<<< この extensions を入れる
  21     ],
  22 }

/apps
  |__ /users
  |     |__ __init__.py
  |     |__ handlers.py
  |     |__ urls.py
  |
  |__ __init__.py

/apps/users/handlers.py

   1 from google.appengine.api import users
   2 
   3 from tipfy import RequestHandler, request, response, redirect
   4 from tipfy.ext.jinja2 import render_response
   5 from tipfy.ext.user import create_login_url, create_logout_url, \
    get_auth_system, get_current_user
   6 
   7 
   8 class SignupHandler(RequestHandler):
   9     error = None
  10 
  11     def get(self, **kwargs):
  12         context = {
  13             'current_url': request.url,
  14             'error': self.error,
  15         }
  16         return render_response('users/signup.html', **context)
  17 
  18     def post(self, **kwargs):
  19         username = request.form.get('username', '').strip()
  20         email = request.form.get('email', '').strip()
  21 
  22         if username and email:
  23             # Create an unique auth id for this user.
  24             # For GAE auth, we use 'gae|' + the gae user id.
  25             auth_id = 'gae|%s' % users.get_current_user().user_id()
  26 
  27             # Set the properties of our user.
  28             kwargs = {
  29                 'email': email,
  30                 'is_admin': users.is_current_user_admin(),
  31             }
  32 
  33             # Save user to datastore.
  34             user = get_auth_system().create_user(username, auth_id, **kwargs)
  35 
  36             if user is None:
  37                 # If no user is returned, the username already exists.
  38                 self.error = 'Username already exists. Please choose a different one.'
  39             else:
  40                 # User was saved: redirect to the previous URL.
  41                 return redirect(request.args.get('redirect', '/'))
  42 
  43         return self.get()
  44 
  45 class HomeHandler(RequestHandler):
  46     def get(self, **kwargs):
  47         context = {
  48             'user':       get_current_user(),
  49             'login_url':  create_login_url(request.url),
  50             'logout_url': create_logout_url(request.url),
  51         }
  52         return render_response('home.html', **context)

templates/users/signup.html

<html>
    <body>
        <h1>Please choose an username and confirm your e-mail:</h1>
        {% if error %}
            <h3>{{ error }}</h3>
        {% endif %}
        <form method="post" action="{{ current_url }}">
            <p><label for="username">Username</label>
            <input type="text" id="username" name="username"><p>

            <p><label for="email">E-mail</label>
            <input type="text" id="email" name="email"></p>

            <p><input type="submit" name="submit" value="save"></p>
        </form>
    </body>
</html>

templates/users/home.html

<html>
    <body>
        {% if user %}
            <p>Logged in as {{ user.username }}. <a href="{{ logout_url }}">Logout</a></p>
        {% else %}
            <p><a href="{{ login_url }}">Login</a></p>
        {% endif %}
    </body>
</html>

apps/users/urls.py

   1 from tipfy import Rule
   2 
   3 def get_rules():
   4     rules = [
   5         Rule('/', endpoint='home', handler='apps.users.handlers.HomeHandler'),
   6         Rule('/accounts/signup', endpoint='users/signup', handler='apps.users.handlers.SignupHandler'),
   7     ]
   8 
   9     return rules

config.py でアプリを有効にする

   1 # -*- coding: utf-8 -*-
   2 """
   3     config
   4     ~~~~~~
   5 
   6     Configuration settings.
   7 
   8     :copyright: 2009 by tipfy.org.
   9     :license: BSD, see LICENSE for more details.
  10 """
  11 config = {}
  12 
  13 # Configurations for the 'tipfy' module.
  14 config['tipfy'] = {
  15     # Some extensions enabled by default: interactive debugger,
  16     # internationalization and user accounts.
  17     'extensions': [
  18         'tipfy.ext.debugger',
  19         'tipfy.ext.i18n',
  20         'tipfy.ext.user',
  21     ],
  22     # ↓↓↓↓↓ 以下を追加してアプリをインストール ↓↓↓↓↓
  23     'apps_installed': [
  24          'apps.users',
  25     ],
  26 }

自分のアプリで認証する


tipfy - small Python framework for App Engine


CategoryTipfy

ボンノウドットコム Wiki: tipfy - ユーザー認証チュートリアル (last edited 2010-03-20 11:16:32 by JunKikuchi)

このサイトに関するお問い合わせは kikuchi@bonnou.com までお願いします