開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- Python 3.6 (プログラミング言語)
Head First Python (Paul Barry (著)、O'Reilly Media)のChapter 6.(Storing and Manipulating Data: Where to Put Your Data)の SHARPEN YOUR PENCIL(No. 5252) を取り組んでみる。
SHARPEN YOUR PENCIL(No. 5252)
コード(Emacs)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import Flask, render_template, request, escape from vsearch import search4letters app = Flask(__name__) @app.route('/search4', methods=['POST']) def do_search() -> 'html': phrase = request.form['phrase'] letters = request.form['letters'] title = 'Here are your results:' results = str(search4letters(phrase, letters)) log_request(request, results) return render_template('results.html', the_title=title, the_phrase=phrase, the_results=results, the_letters=letters) @app.route('/') @app.route('/entry') def entry_page() -> 'html': return render_template('entry.html', the_title='Welcome to search4letters on the web!') @app.route('/viewlog') def view_the_log() -> str: contents = [] with open('vsearch.log') as f: for line in f: content = [] for elem in line.split('|'): content.append(escape(elem)) contents.append(content) return str(contents) 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='|') if __name__ == '__main__': app.run(debug=True)
入出力結果(Terminal, IPython)
$ ./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 - - [30/Jul/2017 18:16:47] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [30/Jul/2017 18:16:47] "GET /static/hf.css HTTP/1.1" 404 - 127.0.0.1 - - [30/Jul/2017 18:17:03] "POST /search4 HTTP/1.1" 200 - 127.0.0.1 - - [30/Jul/2017 18:17:03] "GET /static/hf.css HTTP/1.1" 404 - 127.0.0.1 - - [30/Jul/2017 18:17:06] "POST /search4 HTTP/1.1" 200 - 127.0.0.1 - - [30/Jul/2017 18:17:06] "GET /static/hf.css HTTP/1.1" 404 - 127.0.0.1 - - [30/Jul/2017 18:17:09] "POST /search4 HTTP/1.1" 200 - 127.0.0.1 - - [30/Jul/2017 18:17:09] "GET /static/hf.css HTTP/1.1" 404 - 127.0.0.1 - - [30/Jul/2017 18:17:14] "GET /viewlog HTTP/1.1" 200 - 127.0.0.1 - - [30/Jul/2017 18:17:15] "GET /viewlog HTTP/1.1" 200 - C-c C-c$ cat vsearch.log ImmutableMultiDict([('phrase', ''), ('letters', 'aeiou')])|127.0.0.1|Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8|set() ImmutableMultiDict([('phrase', 'Python'), ('letters', 'aeiou')])|127.0.0.1|Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8|{'o'} ImmutableMultiDict([('phrase', 'Flask'), ('letters', 'aeiou')])|127.0.0.1|Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8|{'a'} $
0 コメント:
コメントを投稿