2014年5月3日土曜日

Pyramid 1.5 + jinja2-alchemy-starter で MySQL の authentication

前回の「Pyramid 1.5 + jinja2-alchemy-starter で sqlite の authentication」では、sqlite でしたが、今回はデータベースを MySQL にしてみます。
Pyramid 1.5 で、Jinja2 で、MySQL を使う、というパターンです。

  1. development.ini
    普通はこんな感じの接続なのですが、これではつながりませんでした。
    sqlalchemy.url=mysql+mysqldb://root:root123@localhost/test
    

    私の環境は /tmp/mysql.sock で接続するタイプなので、こうなります。
    sqlalchemy.url=mysql+pymysql://pyramid:pyramidpass@localhost/pyramid_myproject?unix_socket=/tmp/mysql.sock
    

    ほかに、mysqldb ではなくて、pymysql にしました。pip install で pymysql をインストールしておいてください。
    データベースの user は pyramid、そのパスワードは pyramidpass にしてあります。
    データベース名は pyramid_myproject です。

    その近辺を抜粋します。
    jinja2.directories = myproject:templates
    
    #SQlalchemy configuration (The prefix `sqlalchemy.` can be changed IF you change it in __init__.py's engine_from_config() call too
    # $ bin/pip install pymysql
    sqlalchemy.url=mysql+pymysql://pyramid:pyramidpass@localhost/pyramid_myproject?unix_socket=/tmp/mysql.sock
    sqlalchemy.pool_recycle = 3600
    sqlalchemy.pool_size = 20
    
    [pipeline:main]
    pipeline =
        MyProject
    
    

  2. models.py
    基本的には変わっていませんが、 Text というところを String にしました。Text のままでも、あるいは VARCHAR でも良いかも。
    def initialize_sql(engine): が __init__.py から使われるところは変わりません。
    #!/usr/bin/env python
    # coding: UTF-8
    from pyramid.security import (
        Allow,
        Everyone,
        )
    from sqlalchemy import (
        Column,
        Integer,
        String,
        create_engine,
        )
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import (
        scoped_session,
        sessionmaker,
        )
    
    DBSession = scoped_session(sessionmaker(autocommit=False,
                                             autoflush=False))
    Base = declarative_base()
    Base.query = DBSession.query_property()
    
    # Table Class
    class User(Base):
        """ The SQLAlchemy declarative model class for a User object. """
        __tablename__ = 'users'
        __table_args__ = {  
            'mysql_engine': 'InnoDB',  
            'mysql_charset': 'utf8'  
        }   
        id = Column('id', Integer, primary_key=True)
        name = Column('name', String(255), unique=True)
        password = Column('password', String(255))
        group = Column('group', String(255))
    
        def __init__(self, name, password, group):
            self.name = name
            self.password = password
            self.group = group
    
    class RootFactory(object):
        __acl__ = [ (Allow, Everyone, 'view'),
                    (Allow, 'group:editors', 'edit') ]
        def __init__(self, request):
            pass
    
    def initialize_sql(engine):
        DBSession.configure(bind=engine)
    

  3. security.py
    テーブルの作成など、前回は SQL 文を書きましたが、今回は sqlalchemy です。
    myproject.my_util はもう使いません。
    #!/usr/bin/env python
    # coding: UTF-8
    import pymysql
    import sqlalchemy
    from myproject.models import (DBSession, User)
    
    class MyProjectDB():
        def __init__(self):
            self.session = DBSession
            try:
                self.session.query(User).all()
            except Exception as ex:
                # テーブルがないので作成する。
                print('@MyProjectDB self.session.query(User).all()')
                print(ex)
                user = User.__table__
                engine = self.session.bind
                try:
                    user.create(engine)
                except Exception as ex:
                    print('@MyProjectDB user.create(engine)')
                    print(ex)
                new_user = User('editor', 'editor', 'editors')
                self.session.add(new_user)
                self.session.commit()
            # group='editors' の存在確認。なければつくる。
            try:
                num = self.session.query(User).filter_by(group='editors').count()
                if num == 0:
                    new_user = User('editor', 'editor', 'editors')
                    self.session.add(new_user)
                    self.session.commit()
            except Exception as ex:
                print('@MyProjectDB self.session.add(new_user)')
                print(ex)
        
        def get_group_and_password_of_user(self, user):
            group = None
            password = None
            if self.session is not None:
                try:
                    records = self.session.query(User).filter_by(name=user)
                    for row in records:
                        group = row.group
                        password = row.password
                except Exception as ex:
                    print('@get_group_and_password_of_user')
                    print(ex)
                    group = None
                    password = None
            return (group, password)
        
        def put_group_and_password_of_user(self, user, group, password):
            stmt = sqlalchemy.update(User).where(User.c.name==user).values(group=group, password=password)
        
    def groupfinder(userid, request):
        db = MyProjectDB()
        (group, password) = db.get_group_and_password_of_user(userid)
        the_str = None
        # ['group:editors']
        if group is not None:
            the_str = 'group:' + group
            return [the_str]
        else:
            return []
    


  4. views.py の def login(request): のところ
    models.py の USERS はもう使えません。
    security.py の get_group_and_password_of_user() を代わりに使います。
    <修正前>
        if 'form.submitted' in request.params:
            login = request.params['login']
            password = request.params['password']
            if USERS.get(login) == password:
                headers = remember(request, login)
                return HTTPFound(location = came_from,
                                 headers = headers)
            message = 'Failed login'
    

    <修正後>
        if 'form.submitted' in request.params:
            login = request.params['login']
            password = request.params['password']
            my_db = myproject.security.MyProjectDB()
            (group, pwd) = my_db.get_group_and_password_of_user(login)
            if pwd == password:
                headers = remember(request, login)
                return HTTPFound(location = came_from,
                                 headers = headers)
            message = 'Failed login'
    



これで MySQL を使ったログインフォームができました。

Pyramid 1.5 + jinja2-alchemy-starter で sqlite の authentication

Pyramid 1.5 で、前回までに行った修正に続けて作業していきます。
今までのものは、これ。
Pyramid 1.5 + jinja2-alchemy-starter で pcreate
Pyramid 1.5 + jinja2-alchemy-starter で @view_config()
Pyramid 1.5 + jinja2-alchemy-starter で authentication

前回はログインするページをつくりました。
ログイン ID とパスワードはソフト埋め込みでしたが、今回はデータベースに格納した ID とパスワードを使うことにします。
データベースはひとまず、標準で入っている sqlite を使います。次回は MySQL にします。

今のところ、development.ini に次の記述があります。sqlite のファイル名を指定しています。
sqlalchemy.url = sqlite:///%(here)s/MyProject.sqlite

あとは、myproject/models.py と myproject/security.py が関係しています。

models.py では・・・
class MyModel(Base) は不要ですね。
class User(Base): これがあれば良いと思われます。テーブルの名称は users で、フィールドは primary key の id と unique な name、それに password です。group も必要?
class RootFactory(object): は、__init__.py の Configurator() で使われていて、非常に重要っぽいものなので、そのままにしておきます。

security.py は・・・
group が editors と viewers があって、editors には editor が、viewers には viewer という名前の user がいます。
def groupfinder(userid, request): では、userid が属す group を返しています。
この部分を、sqlite から持ってくるようにすれば良さそうです。
というわけで、models.py の users テーブルは id、name、password のほかに group フィールドを持たせることにします。

models.py はこうなりました。User に group を追加しました。
#!/usr/bin/env python
# coding: UTF-8
from pyramid.security import (
    Allow,
    Everyone,
    )
from sqlalchemy import (
    Column,
    Integer,
    Text,
    )
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
    scoped_session,
    sessionmaker,
    )
from zope.sqlalchemy import ZopeTransactionExtension

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()

class User(Base):
    """ The SQLAlchemy declarative model class for a User object. """
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(Text, unique=True)
    password = Column(Text)
    group = Column(Text)

    def __init__(self, name, password, group):
        self.name = name
        self.password = password
        self.group = group

class RootFactory(object):
    __acl__ = [ (Allow, Everyone, 'view'),
                (Allow, 'group:editors', 'edit') ]
    def __init__(self, request):
        pass

def initialize_sql(engine):
    DBSession.configure(bind=engine)


この辺りを参考にします。
http://wiki.liris.org/article/python_intro/python03
http://seesaawiki.jp/w/kurt0027/d/python%20sqlalchemy%A4%CD%A4%BF
http://bty.sakura.ne.jp/wp/archives/634

development.ini にあるデータベースのファイル名を返す関数を持つ my_util.py を追加します。ちょっといい加減な関数です。
#!/usr/bin/env python
# coding: UTF-8
import pyramid

class MyUtil():
    def get_db_name(self):
        db_name = pyramid.threadlocal.get_current_registry().settings
        db_name = db_name['sqlalchemy.url']
        db_name = db_name[10:]
        return db_name

security.py はこうなりました。
#!/usr/bin/env python
# coding: UTF-8
import sqlite3
import sqlalchemy
import myproject.my_util

class myproject_db():
    def __init__(self, fname):
        self.con = None
        self.fname = fname
        if fname is not None:
            self.con = sqlite3.connect(fname)   # , isolation_level=None
            no_db = True
            try:
                cur = self.con.cursor()
                sql = 'SELECT name, password, user_group FROM users WHERE user_group=?'
                cur.execute(sql, (u'editor',))
                no_db = False
            except Exception as ex:
                print(ex)
            self.con.close()
            
            if no_db:
                # Create table
                self.con = sqlite3.connect(fname)
                cur = self.con.cursor()
                sql = '''create table users (
id integer primary key autoincrement not null,
name text,
password text,
user_group text)'''
                cur.execute(sql)
                tp = ('editor', 'editor', 'editors',)
                cur.execute(''' INSERT INTO users (name, password, user_group) VALUES (?, ?, ?)''', tp)
                self.con.commit()
                cur.close()
    
    
    def connect(self):
        if self.fname is not None:
            self.con = sqlite3.connect(self.fname)
        else:
            self.con = None
        return self.con
    
    
    def get_group_and_password_of_user(self, user):
        group = None
        password = None
        self.connect()
        if self.con is not None:
            try:
                cur = self.con.cursor()
                tp = (user,)
                cur.execute('SELECT user_group, password FROM users WHERE name=?', tp)
                for row in cur:
                    group = row[0]
                    password = row[1]
                cur.close()
            except Exception as ex:
                print(ex)
                group = None
                password = None
            self.con.close()
        return (group, password)
    
    def put_group_and_password_of_user(self, user, group, password):
        sql = 'UPDATE users SET user_group=?, password=? WHERE name=?;'
        self.connect()
        if self.con is not None:
            try:
                cur = self.con.cursor()
                tp = (group, password, user,)
                cur.execute(sql, tp)
                self.con.commit()
                cur.close()
            except Exception as ex:
                print(ex)
            self.con.close()

def groupfinder(userid, request):
    my_util = myproject.my_util.MyUtil()
    db_name = my_util.get_db_name()
    db = myproject_db(db_name)
    (group, password) = db.get_group_and_password_of_user(userid)
    the_str = None
    # ['group:editors']
    if group is not None:
        the_str = 'group:' + group
        return [the_str]
    else:
        return []

    
if __name__ == '__main__':
    db_name = 'MyProject.sqlite'
    db = myproject_db(db_name)
    db.connect()
    if db.con is not None:
        try:
            cur = db.con.cursor()
            sql = 'SELECT name, password, user_group FROM users ORDER BY name;'
            cur.execute(sql)
            for xx in cur.fetchall():
                print(xx[0], xx[1], xx[2])
            cur.close()
        except Exception as ex:
            print(ex)
        db.con.close()

views.py もかなり修正しました。
#!/usr/bin/env python
# coding: UTF-8
from pyramid.i18n import TranslationStringFactory
from myproject.models import DBSession
from pyramid.httpexceptions import HTTPFound
from pyramid.response import Response
from pyramid.view import (
    view_config,
    forbidden_view_config,
    )
from pyramid.security import (
    remember,
    forget,
    authenticated_userid,
    )
import myproject.security
import myproject.my_util

_ = TranslationStringFactory('MyProject')

@view_config(route_name='home', renderer='home.html', permission='edit', request_method="GET")
def home(request):
    page_name = 'home'
    results = {
        'page_name': page_name,
        'next_uri': '/next',
        'next_name': 'next_page'
    }
    return results

@view_config(route_name='next_page', renderer='home.html', permission='edit', request_method="GET")
def next_page(request):
    page_name = 'next_page'
    results = {
        'page_name': page_name,
        'next_uri': '/',
        'next_name': 'home'
    }
    return results

@view_config(route_name='login', renderer='login.html')
@forbidden_view_config(renderer='login.html')
def login(request):
    login_url = request.route_url('login')
    referrer = request.url
    if referrer == login_url:
        referrer = '/' # never use the login form itself as came_from
    came_from = request.params.get('came_from', referrer)
    message = ''
    login = ''
    password = ''
    if 'form.submitted' in request.params:
        login = request.params['login']
        password = request.params['password']
        # if USERS.get(login) == password:
        my_util = myproject.my_util.MyUtil()
        db_name = my_util.get_db_name()
        my_db = myproject.security.myproject_db(db_name)
        (group, pwd) = my_db.get_group_and_password_of_user(login)
        if pwd == password:
            headers = remember(request, login)
            return HTTPFound(location = came_from,
                             headers = headers)
        message = 'Failed login'

    return dict(
        message = message,
        url = request.application_url + '/login',
        came_from = came_from,
        login = login,
        password = password,
        )

@view_config(route_name='logout')
def logout(request):
    headers = forget(request)
    return HTTPFound(location = request.route_url('home'), headers = headers)

最後にテンプレートの login.html。
ログインエラーなどのメッセージを表示するように修正しました。
<!DOCTYPE html>
<html>
<head>
  <title>Login</title>
  <meta charset="utf-8">
  <link rel="stylesheet" href="{{request.application_url}}/static/pylons.css" type="text/css" media="screen" charset="utf-8" />
</head>
<body>
  <form action="{{ url }}" method="post" id="id_login_form">
    <input type="text" name="login" value="{{ login }}"
        placeholder="login name" autofocus required/><br/>
    <input type="password" name="password" value="{{ password }}"
        placeholder="password" required /><br/>
    <input type="hidden" name="came_from" value="{{ came_from }}" />
    <input type="submit" name="form.submitted" value="Log In" />
  </form>
  {{ message }}
</body>
</html>

これで修正は終了です。
実行すると動きは変わりありませんが、MyProject.sqlite ファイルが作成されているのがわかります。
MyProject.sqlite が置かれているディレクトリで myproject/security.py を実行すると MyProject.sqlite の中を表示します。
$ ../bin/python myproject/security.py
(u'editor', u'editor', u'editors')
$ 

2014年5月1日木曜日

Pyramid 1.5 + jinja2-alchemy-starter で authentication

Pyramid 1.5 で、Pyramid 1.5 + jinja2-alchemy-starter で pcreate と Pyramid 1.5 + jinja2-alchemy-starter で @view_config() で作成したプロジェクトを修正します。

今回は、ログインしないと表示できないページにしてみます。
まず、データベースは使わないで、ソースの中に ID と password を持つようにします。
  1. myproject/__init__.py の修正
    インポート部分にいくつか追加します。
    #!/usr/bin/env python
    # coding: UTF-8
    from pyramid.config import Configurator
    from pyramid_jinja2 import renderer_factory
    from sqlalchemy import engine_from_config
    from pyramid.session import UnencryptedCookieSessionFactoryConfig
    from pyramid.authentication import AuthTktAuthenticationPolicy
    from pyramid.authorization import ACLAuthorizationPolicy
    from myproject.security import groupfinder
    from myproject.models import (
        initialize_sql,
        DBSession,
        Base,
        )
    

  2. myproject/__init__.py の修正
    UnencryptedCookieSessionFactoryConfig をインポートの次に追加します。
    'something_so_secret_strings' はそれなりの文字列にしておいてください。
    my_session_factory = UnencryptedCookieSessionFactoryConfig('something_so_secret_strings')
    

  3. myproject/__init__.py の修正
    main() の修正
    <修正前>
        #SQLAlchemy engine config for main DB 
        #Any setting that begins with 'sqlalchemy.' will be picked up
        db_engine = engine_from_config(settings,'sqlalchemy.')
        #Binding engine to the model
        initialize_sql(db_engine)
        
        config = Configurator(settings=settings)
        
        config.include('pyramid_jinja2')
        config.add_renderer(".html", "pyramid_jinja2.renderer_factory")
    
        #The views/routes are added here
        config.add_static_view('static', 'static')
        
        config.add_route('home', '/')
        config.add_route('next_page', '/next')
        config.scan()
        
        return config.make_wsgi_app()
    

    <修正後>
    'sosecret' はそれなりの文字列にしておいてください。
        #SQLAlchemy engine config for main DB 
        #Any setting that begins with 'sqlalchemy.' will be picked up
        db_engine = engine_from_config(settings, 'sqlalchemy.')
        #Binding engine to the model
        initialize_sql(db_engine)
        
    
        authn_policy = AuthTktAuthenticationPolicy(
            'sosecret', callback=groupfinder, hashalg='sha512')
        authz_policy = ACLAuthorizationPolicy()
    
        config = Configurator(settings=settings,
                              root_factory='myproject.models.RootFactory',
                              session_factory=my_session_factory)
    
        
        config.include('pyramid_jinja2')
        config.add_renderer(".html", "pyramid_jinja2.renderer_factory")
    
    
        config.set_authentication_policy(authn_policy)
        config.set_authorization_policy(authz_policy)
    
        
        #The views/routes are added here
        config.add_static_view('static', 'static')
        
        config.add_route('home', '/')
        config.add_route('next_page', '/next')
    
        config.add_route('login', '/login')
        config.add_route('logout', '/logout')
    
        config.scan()
        
        return config.make_wsgi_app()
    

  4. pypwm/views.py の修正
    <修正前>
    #!/usr/bin/env python
    # coding: UTF-8
    from pyramid.i18n import TranslationStringFactory
    from myproject.models import DBSession
    from pyramid.view import view_config
    
    _ = TranslationStringFactory('MyProject')
    
    @view_config(route_name='home', renderer='home.html')
    def home(request):
        page_name = 'home'
        return {'page_name':page_name, 'next_uri':'/next', 'next_name':'next_page'}
    
    @view_config(route_name='next_page', renderer='home.html')
    def next_page(request):
        page_name = 'next_page'
        return {'page_name':'page_name', 'next_uri':'/', 'next_name':'home'}
    

    <修正後>ほとんど全面的に修正。
    #!/usr/bin/env python
    # coding: UTF-8
    from pyramid.i18n import TranslationStringFactory
    from myproject.models import DBSession
    from pyramid.httpexceptions import HTTPFound
    from pyramid.response import Response
    from pyramid.view import (
        view_config,
        forbidden_view_config,
        )
    from pyramid.security import (
        remember,
        forget,
        authenticated_userid,
        )
    from .security import USERS
    
    _ = TranslationStringFactory('MyProject')
    
    @view_config(route_name='home', renderer='home.html', permission='edit', request_method="GET")
    def home(request):
        page_name = 'home'
        return {'page_name':page_name, 'next_uri':'/next', 'next_name':'next_page'}
    
    @view_config(route_name='next_page', renderer='home.html', permission='edit', request_method="GET")
    def next_page(request):
        page_name = 'next_page'
        return {'page_name':'page_name', 'next_uri':'/', 'next_name':'home'}
    
    @view_config(route_name='login', renderer='login.html')
    @forbidden_view_config(renderer='login.html')
    def login(request):
        login_url = request.route_url('login')
        referrer = request.url
        if referrer == login_url:
            referrer = '/' # never use the login form itself as came_from
        came_from = request.params.get('came_from', referrer)
        message = ''
        login = ''
        password = ''
        if 'form.submitted' in request.params:
            login = request.params['login']
            password = request.params['password']
            if USERS.get(login) == password:
                headers = remember(request, login)
                return HTTPFound(location = came_from,
                                 headers = headers)
            message = 'Failed login'
    
        return dict(
            message = message,
            url = request.application_url + '/login',
            came_from = came_from,
            login = login,
            password = password,
            )
    
    @view_config(route_name='logout')
    def logout(request):
        headers = forget(request)
        return HTTPFound(location = request.route_url('home'), headers = headers)
    

  5. myproject/security.py を追加
    #!/usr/bin/env python
    # coding: UTF-8
    USERS = {
             'editor':'editor',
             'viewer':'viewer'
             }
    GROUPS = {
              'editor':['group:editors'],
              'viewer':['group:viewers'],
              }
    
    def groupfinder(userid, request):
        if userid in USERS:
            return GROUPS.get(userid, [])
    

  6. myproject/models.py の修正
    <修正前>
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker,scoped_session
    from zope.sqlalchemy import ZopeTransactionExtension
    
    DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
    Base = declarative_base()
    
    #Define your models here
    #class MyModel(Base):
    #    pass
    
    def initialize_sql(engine):
        DBSession.configure(bind=engine)
    

    <修正後>
    #!/usr/bin/env python
    # coding: UTF-8
    from pyramid.security import (
        Allow,
        Everyone,
        )
    from sqlalchemy import (
        Column,
        Integer,
        Text,
        )
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import (
        scoped_session,
        sessionmaker,
        )
    from zope.sqlalchemy import ZopeTransactionExtension
    
    DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
    Base = declarative_base()
    
    class MyModel(Base):
        __tablename__ = 'models'
        id = Column(Integer, primary_key=True)
        name = Column(Text, unique=True)
        value = Column(Integer)
    
        def __init__(self, name, value):
            self.name = name
            self.value = value
    
    class User(Base):
        """ The SQLAlchemy declarative model class for a User object. """
        __tablename__ = 'users'
        id = Column(Integer, primary_key=True)
        name = Column(Text, unique=True)
        password = Column(Text)
    
        def __init__(self, name, password):
            self.name = name
            self.password = password
    
    class RootFactory(object):
        __acl__ = [ (Allow, Everyone, 'view'),
                    (Allow, 'group:editors', 'edit') ]
        def __init__(self, request):
            pass
    
    def initialize_sql(engine):
        DBSession.configure(bind=engine)
    

  7. テンプレート home.html の修正
    <br /><a href="{{ request.application_url }}/logout">Logout</a> を body 内に追加します。
    <html>
    <head>
        <title>{{ page_name }}</title>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
        <link rel="shortcut icon" href="{{request.application_url}}/static/favicon.ico" />
        <link rel="stylesheet" href="{{request.application_url}}/static/pylons.css" type="text/css" media="screen" charset="utf-8" />
    </head>
    <body>
      This page name is '{{ page_name }}'.<br />
      <a href="{{ request.application_url }}{{ next_uri }}">{{ next_name }}</a>
      <br />
      <a href="{{ request.application_url }}/logout">Logout</a>
    </body>
    </html>
    

  8. テンプレートの追加
    myproject/templates/login.html を追加します。
    <!DOCTYPE html>
    <html>
    <head>
      <title>Login</title>
      <meta charset="utf-8">
      <link rel="stylesheet" href="{{request.application_url}}/static/pylons.css" type="text/css" media="screen" charset="utf-8" />
    </head>
    <body>
      <form action="{{ url }}" method="post" id="id_login_form">
        <input type="text" name="login" value="{{ login }}"
            placeholder="login name" autofocus required/><br/>
        <input type="password" name="password" value="{{ password }}"
            placeholder="password" required /><br/>
        <input type="hidden" name="came_from" value="{{ came_from }}" />
        <input type="submit" name="form.submitted" value="Log In" />
      </form>
    </body>
    </html>

  9. おしまい
これで実行するとログインフォームが表示されます。
ログイン前に localhost:6543/next を表示しようとしても、ログインフォームが表示されます。
localhost:6543/next からログインフォームでログインすると、ちゃんと localhost:6543/next のページになります。
どこかのサイトを参考にしたのですが、その URL はわからなくなってしまいました。

次回は、ひとまず sqlite にしてみます。それから mysql ですね。