今回は、MySQLへの接続とWebページの表示を用いて簡単な画面遷移を行うWebアプリケーションを作成したいと思います。
Webページの表示で作成したsimpleweb.pyを下記のように修正します。
MySQLへの接続で作成したaccountdao.pyをsimpleweb.pyと同じディレクトリに配置します。
from wsgiref import simple_server, util
import cgi
import hashlib
import accountdao
_html = '''<html>
<head><title>LogonForm</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
</head>
<body>
<form action="{0}" method="POST" AcceptEncoding="utf-8">
<dl>
<dt>UserID</dt>
<dd><input type="text" name="UserID"/></dd>
<dt>Password</dt>
<dd><input type="text" name="Password"/></dd>
<input type="submit" name="logon" value="LogOn" />
</form>
</body>
</html>
'''
class SimpleWeb(object):
'''簡単なWebアプリケーション'''
def __call__(self, environ, start_response):
''' WSGI アプリケーション '''
method = environ.get('REQUEST_METHOD')
if method == 'POST':
wsgi_input = environ.get('wsgi.input')
length = int(environ.get('CONTENT_LENGTH', 0))
query = dict(cgi.parse_qsl(wsgi_input.read(length)))
account_dao = accountdao.AccountDao('localhost', 'practice', 'paku', 'paku')
rows = account_dao.select(query.get(b'UserID').decode('utf-8'), 'user_passwd')
passwd = hashlib.sha1(query.get(b'Password')).hexdigest()
if passwd == rows[0][0]:
start_response('200 OK', [('Content-Type', 'text/plane; charset=utf-8')])
return [b"LogON OK"]
else:
start_response('200 OK', [('Content-Type', 'text/plane; charset=utf-8')])
return [b"LogON NG"]
else:
start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
return self.logonPage(environ)
def logonPage(self, environ):
'''Logonページの内容を作成'''
return [bytes(_html.format(util.request_uri(environ)), 'utf-8')]
application = SimpleWeb()
if __name__ == '__main__':
''' ユーザーID:test ユーザー名:test パスワード:testのユーザーを作成 '''
account_dao = accountdao.AccountDao('localhost', 'practice', 'paku', 'paku')
rows = account_dao.select('test')
if len(rows) != 0:
''' 既にユーザーID:testが存在する場合は削除 '''
account_dao.delete('test')
account_dao.insert('test', 'test', hashlib.sha1('test'.encode(encoding='utf_8', errors='strict')).hexdigest())
server = simple_server.make_server('', 8080, application)
server.serve_forever()
行が塗りつぶされている部分が修正箇所です。
簡単に説明をします。
・28行目で、environからリクエストメソッドを取得します。
・リクエストメソッドがPOSTであった場合は、POSTデータの解析を行います。
・30行目でPOSTデータを読み出すためのストリームを取得します。
・31行目でPOSTデータのサイズを取得します。
・33行目でストリームからPOSTデータを読み出し、辞書型に変換します。
・35~37行目でUserIDに入力されたデータのパスワードを検索します。
・39~44行目でPasswordに入力されたデータと検索でヒットしたパスワードを比較し、
結果を出力します。
・58~65行目では今回のアプリ用のテストデータを生成しています。
では、実際に動かしてみましょう。
simpleweb.pyを保存したディレクトリ上で、
下記コマンドを実行します。
>python simpleweb.py
これでWebアプリケーションが起動しますので、http://localhost:8080にアクセスします。
アクセスしたWebページのFormのUserID欄にtest、Password欄にtestを入力し、
LogOnボタンを押下した際に、LogON OKと表示されれば成功です。
また、上記以外の情報を入力した場合は、LogON NGと表示されます。
終了する際は、シェル上でCTRL+Cを押下すればWebアプリケーションは終了します。
これでMySQLに接続する簡単な画面遷移を行うWebアプリケーションの作成が出来ました。