2017年4月15日土曜日

開発環境

Head First Python (Paul Barry (著)、O'Reilly Media)のChapter 12.(113/4 A Little Bit of Threading: Dealing With Waiting) の SHARPEN YOUR PENCIL(No. 8630) を取り組んでみる。

SHARPEN YOUR PENCIL(No. 8630)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# cursor.execute('''create table log (
# id int auto_increment primary key,
# 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 )''')

from flask import Flask, render_template, request, escape
from DBcm import UseDatabase, CustomException
from threading import Thread
import sqlite3

import vsearch

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:
    with UseDatabase(app.config['dbconfig']) as cursor:
        _SQL = '''insert into log
                  (phrase, letters, ip, browser_string, results)
                  values
                  (?, ?, ?, ?, ?)'''
        cursor.execute(_SQL, (req.form['phrase'],
                              req.form['letters'],
                              req.remote_addr,
                              req.user_agent.browser,
                              res))


@app.route('/')
@app.route('/entry')
def entr_page() -> 'html':
    return render_template('entry.html',
                           the_title='Welcome to search4letters on the web!')


@app.route('/search4', methods=['POST'])
def do_search() -> 'html':
    phrase = request.form['phrase']
    letters = request.form['letters']
    title = 'Here are your result:'
    results = str(vsearch.search4letters(phrase, letters))
    try:
        t = Thread(target=log_request, args=(request, results))
        t.start()
    except CustomException as err:
        print(err)
    except Exception as err:
        print(err)
    return render_template('results.html',
                           the_title=title,
                           the_phrase=phrase,
                           the_letters=letters,
                           the_results=results)


@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 = ('Phrase', 'Letters', 'Remote_addr', 'User_agent', 'Results')
    return render_template('viewlog.html',
                           the_title='View Log',
                           the_row_titles=titles,
                           the_data=contents,)

if __name__ == '__main__':
    app.run(debug=True)

入出力結果(Terminal, IPython)

$ ./vsearch4log.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 - - [15/Apr/2017 16:45:34] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [15/Apr/2017 16:45:34] "GET /static/hf.css HTTP/1.1" 304 -
127.0.0.1 - - [15/Apr/2017 16:45:39] "POST /search4 HTTP/1.1" 200 -
Exception in thread Thread-2:
Traceback (most recent call last):
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "./vsearch4log.py", line 35, in log_request
    cursor.execute(_SQL, (req.form['phrase'],
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/werkzeug/local.py", line 347, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/werkzeug/local.py", line 306, in _get_current_object
    return self.__local()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/globals.py", line 37, in _lookup_req_object
    raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

  C-c C-c$

0 コメント:

コメントを投稿

Comments on Google+: