開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
- パッケージ
- PostgreSQL (ORDBMS(object-relational database management system))
Head First Python 第2版 ―頭とからだで覚えるPythonの基本 (Paul Barry (著)、嶋田 健志 (監修)、木下 哲也 (翻訳)、オライリージャパン)の11章(例外処理 - うまくいかないときに行うこと)、自分で考えてみよう(p. 445)を取り組んでみる。
コード(Emacs)
DBcm.py
#!/usr/bin/env python3
import psycopg2 as sql
class ConnectionError(Exception):
pass
class UseDatabase:
def __init__(self, dbconfig: dict) -> None:
self.dbconfig = dbconfig
def __enter__(self) -> 'cursor':
try:
self.conn = sql.connect(**self.dbconfig)
self.cursor = self.conn.cursor()
return self.cursor
except sql.OperationalError as err:
raise ConnectionError(err)
except sql.InterfaceError as err:
raise ConnectionError(err)
def __exit__(self, exc_type, exc_value, exc_trace) -> None:
self.conn.commit()
self.cursor.close()
self.conn.close()
if __name__ == '__main__':
dbconfig = {'host': '127.0.0.1',
'database': 'vsearchlogdb'}
with UseDatabase(dbconfig) as db:
print(db)
vsearch4web.py
from flask import Flask, render_template, request, escape
import vsearch
import psycopg2 as sql
from DBcm import UseDatabase, ConnectionError
app = Flask(__name__)
dbconfig = {'host': '127.0.0.1',
'database': 'vsearchlogdb'}
def log_request(req: 'flask_request', res: str) -> None:
try:
with UseDatabase(dbconfig) as cursor:
_sql = '''
select phrase, letters, ip, browser_string, results
from log
'''
cursor.execute(_sql)
contents = cursor.fetchall()
titles = ('phrase', 'letters', 'ユーザーエージェント', '結果')
return render_template('viewlog.html',
the_title='ログの閲覧',
the_row_titles=titles,
the_data=contents,)
except ConnectionError as err:
print(f'データベースが動作していますか?エラー: {err}')
except Exception as err:
print(type(err))
print(f'何か問題が発生しました: {err}')
return 'Error'
@app.route('/')
@app.route('/entry')
def entry_page() -> str:
return render_template(
'entry.html',
the_title='Welcom to search4letters on the web!')
@app.route('/search4', methods=['POST'])
def do_search() -> str:
phrase = request.form['phrase']
letters = request.form['letters']
results = str(vsearch.search4letters(phrase, letters))
try:
log_request(request, results)
except Exception as err:
print(type(err), err)
title = '検索結果'
return render_template(
'results.html',
the_title=title,
the_phrase=phrase,
the_letters=letters,
the_results=results)
@app.route('/viewlog')
def view_the_log() -> str:
with UseDatabase(dbconfig) as cursor:
_sql = '''
select phrase, letters, ip, browser_string, results
from log
'''
cursor.execute(_sql)
contents = cursor.fetchall()
titles = ('phrase', 'letters', 'ユーザーエージェント', '結果')
return render_template('viewlog.html',
the_title='ログの閲覧',
the_row_titles=titles,
the_data=contents,)
if __name__ == '__main__':
app.run(debug=True)
入出力結果(Terminal, cmd(コマンドプロンプト), Jupyter(IPython))
$ python3 vsearch4web.py
* Serving Flask app "vsearch4web" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 178-619-558
127.0.0.1 - - [28/Dec/2018 12:48:48] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [28/Dec/2018 12:48:48] "GET /static/hf.css HTTP/1.1" 404 -
データベースが動作していますか?エラー: could not connect to server: Connection refused
Is the server running on host "127.0.0.1" and accepting
TCP/IP connections on port 5432?
127.0.0.1 - - [28/Dec/2018 12:48:52] "POST /search4 HTTP/1.1" 200 -
127.0.0.1 - - [28/Dec/2018 12:48:52] "GET /static/hf.css HTTP/1.1" 404 -
127.0.0.1 - - [28/Dec/2018 12:49:16] "POST /search4 HTTP/1.1" 200 -
127.0.0.1 - - [28/Dec/2018 12:49:16] "GET /static/hf.css HTTP/1.1" 404 -
* Detected change in '/.../vsearch4web.py', reloading
* Restarting with stat
* Debugger is active!
* Debugger PIN: 178-619-558
<class 'psycopg2.ProgrammingError'>
何か問題が発生しました: column "result" does not exist
LINE 2: select phrase, letters, ip, browser_string, result
^
HINT: Perhaps you meant to reference the column "log.results".
127.0.0.1 - - [28/Dec/2018 12:49:31] "POST /search4 HTTP/1.1" 200 -
127.0.0.1 - - [28/Dec/2018 12:49:31] "GET /static/hf.css HTTP/1.1" 404 -
* Detected change in '/.../vsearch4web.py', reloading
* Restarting with stat
* Debugger is active!
* Debugger PIN: 178-619-558
127.0.0.1 - - [28/Dec/2018 12:49:38] "POST /search4 HTTP/1.1" 200 -
127.0.0.1 - - [28/Dec/2018 12:49:38] "GET /static/hf.css HTTP/1.1" 404 -
C-c C-c$
0 コメント:
コメントを投稿