2017年3月22日水曜日

開発環境

Head First Python (Paul Barry (著)、O'Reilly Media)のChapter 6.(Soring & Manipulating Data: Where To Put Your Data) の SHARPEN YOUR PENCIL(No. 5113) を取り組んでみる。

SHARPEN YOUR PENCIL(No. 5113)

コード(Emacs)

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

from flask import Flask, render_template, request, escape

import vsearch

app = Flask(__name__)


def log_request(req: 'flask_request', res: str) -> None:
    with open('vsearch.log', 'a') as f:
        print(req.form, req.remote_addr, req.user_agent, res, file=f, sep='|')


@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))
    log_request(request, results)
    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 open('vsearch.log') as f:
        contents = []
        for content in f:
            contents.append([])
            for x in content.split('|'):
                contents[-1].append(escape(x))

    return str(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 - - [22/Mar/2017 16:47:34] "POST /search4 HTTP/1.1" 200 -
127.0.0.1 - - [22/Mar/2017 16:47:54] "POST /search4 HTTP/1.1" 200 -
127.0.0.1 - - [22/Mar/2017 16:47:57] "GET /viewlog HTTP/1.1" 200 -
  C-c C-c$ cat vsearch.log 
ImmutableMultiDict([('phrase', 'Head First Python'), ('letters', 'aeiou')])|127.0.0.1|Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8|{'i', 'a', 'o', 'e'}
ImmutableMultiDict([('phrase', 'Flask'), ('letters', 'aeiou')])|127.0.0.1|Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8|{'a'}
$ 

HTML5

[[Markup('ImmutableMultiDict([('phrase', 'Head First Python'), ('letters', 'aeiou')])'), Markup('127.0.0.1'), Markup('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8'), Markup('{'i', 'a', 'o', 'e'}\n')], [Markup('ImmutableMultiDict([('phrase', 'Flask'), ('letters', 'aeiou')])'), Markup('127.0.0.1'), Markup('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8'), Markup('{'a'}\n')]]

0 コメント:

コメントを投稿

Comments on Google+: