2018年12月31日月曜日

開発環境

Head First Python 第2版 ―頭とからだで覚えるPythonの基本 (Paul Barry (著)、嶋田 健志 (監修)、木下 哲也 (翻訳)、オライリージャパン)の11 3/4章(スレッド入門 - 待ち時間を処理する)、自分で考えてみよう(p. 467)を取り組んでみる。

コード(Emacs)

Python 3

from flask import Flask, render_template, request, escape
from threading import Thread
import time
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:
    time.sleep(15)
    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:
        t = Thread(target=log_request, args=(request, results))
        t.start()
    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 - - [31/Dec/2018 19:22:11] "GET /search4 HTTP/1.1" 405 -
127.0.0.1 - - [31/Dec/2018 19:22:12] "GET /static/hf.css HTTP/1.1" 404 -
127.0.0.1 - - [31/Dec/2018 19:22:12] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [31/Dec/2018 19:22:14] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [31/Dec/2018 19:22:14] "GET /static/hf.css HTTP/1.1" 404 -
127.0.0.1 - - [31/Dec/2018 19:22:17] "POST /search4 HTTP/1.1" 200 -
データベースが動作していますか?エラー: 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 - - [31/Dec/2018 19:22:17] "GET /static/hf.css HTTP/1.1" 404 -
127.0.0.1 - - [31/Dec/2018 19:22:33] "POST /search4 HTTP/1.1" 200 -
<class 'AttributeError'>
何か問題が発生しました: 'NoneType' object has no attribute 'app'
127.0.0.1 - - [31/Dec/2018 19:22:33] "GET /static/hf.css HTTP/1.1" 404 -
 * Detected change in '/.../webapp/vsearch4web.py', reloading
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 178-619-558
 * Detected change in '/.../webapp/vsearch4web.py', reloading
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 178-619-558
 * Detected change in '/.../webapp/vsearch4web.py', reloading
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 178-619-558
127.0.0.1 - - [31/Dec/2018 19:23:37] "POST /search4 HTTP/1.1" 200 -
Exception in thread Thread-3:
Traceback (most recent call last):
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "vsearch4web.py", line 14, in log_request
    time.sleep(15)
NameError: name 'time' is not defined

127.0.0.1 - - [31/Dec/2018 19:23:37] "GET /static/hf.css HTTP/1.1" 404 -
 * Detected change in '/.../webapp/vsearch4web.py', reloading
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 178-619-558
127.0.0.1 - - [31/Dec/2018 19:23:47] "POST /search4 HTTP/1.1" 200 -
127.0.0.1 - - [31/Dec/2018 19:23:47] "GET /static/hf.css HTTP/1.1" 404 -
<class 'AttributeError'>
何か問題が発生しました: 'NoneType' object has no attribute 'app'
  C-c C-c$

0 コメント:

コメントを投稿

関連コンテンツ