開発環境
- macOS Mojave - Apple
- Emacs (Text Editor)
- Python 3.7 (プログラミング言語)
Head First Python 第2版 ―頭とからだで覚えるPythonの基本 (Paul Barry (著)、嶋田 健志 (監修)、木下 哲也 (翻訳)、オライリージャパン)の11章(例外処理 - うまくいかないときに行なうこと)、自分で考えてみよう(p. 435)を取り組んでみる。
コード(Emacs)
Python 3
from flask import Flask, render_template, request, escape import vsearch from DBcm import UseDatabase app = Flask(__name__) app.config['dbconfig'] = {'host': '127.0.0.1', 'user': 'vsearch', 'password': 'vsearchpasswd', 'database': 'vsearchlogDB', } def log_request(req: 'flask_request', res: str) -> None: with UseDatabase(app.config['dbconfig']) as cursor: _SQL = ''' create table if not exists log( id integer primary key autoincrement, ts timestamp default current_timestamp, phrase varchar(128) not null, letters varchar(32) not null, ip varchar(16) not null, browser_string varchar(256) not null, results varchar(64) not null) ''' cursor.execute(_SQL) _SQL = ''' insert into log (phrase, letters, ip, browser_string, results) values (%s, %s, %s, %s, %s) ''' cursor.execute( _SQL, (req.form['phrase'], req.form['letters'], req.remote_addr, req.user_agent.browser, res)) @app.route('/search4', methods=['POST']) def do_search() -> 'html': phrase = request.form['phrase'] letters = request.form['letters'] title = '検索結果' results = str(vsearch.search4letters(phrase, letters)) try: log_request(request, results) except Exception as err: print(f'ログリクエストが失敗しました: {err}') return render_template('results.html', the_title=title, the_phrase=phrase, the_letters=letters, the_results=results) @app.route('/') @app.route('/entry') def entry_page() -> 'html': return render_template( 'entry.html', the_title='Web版のsearch4lettersにようこそ!') @app.route('/viewlog') def view_the_log() -> 'html': with UseDatabase(app.config['dbconfig']) as cursor: _SQL = 'select phrase, letters, ip, browser_string, results from log' cursor.execute(_SQL) contents = cursor.fetchall() titles = ('フレーズ', '文字', 'リモートアドレス', 'ユーザーエージェント', '結果') return render_template('viewlog.html', the_title='ログの閲覧', the_row_titles=titles, the_data=contents,) if __name__ == '__main__': app.run(debug=True)
入出力結果(Terminal, Jupyter(IPython))
$ python3 vsearch4web.py * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 873-014-066 127.0.0.1 - - [18/Oct/2018 13:34:24] "GET / HTTP/1.1" 200 - ログリクエストが失敗しました: 2003: Can't connect to MySQL server on '127.0.0.1:3306' (61 Connection refused) 127.0.0.1 - - [18/Oct/2018 13:34:26] "POST /search4 HTTP/1.1" 200 - C-c C-c$
0 コメント:
コメントを投稿