2014年7月4日金曜日

開発環境

Head First Python (Paul Barry(著)、 O'Reilly Media )のChapter 9(Manage Your data: Handling input)、EXERCISE(p.297)を解いてみる。

EXERCISE(p.297)

コード(BBEdit)

templates/form.html

<form action="cgi-bin/process-time.py" method="POST">
  <label>
    Enter a timing value:
    <input type="text" name="time_value" size="40" />
  </label>
  <input type="submit" value="Send" />
</form>

cgi-bin/yate.py

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

import string

def start_response(resp="text/html"):
    return('Content-type: ' + resp + '\n\n')

def create_inputs(inputs_list):
    html_inputs = ''
    for input in inputs_list:
        html_inputs += '<input type="text" name="{0}" size="40" />'.format(
            input)
    return html_inputs    

def do_form(name, the_inputs, method="POST", text="Submit"):
    with open('templates/form.html') as f:
        template = f.read()
    inputs = create_inputs(the_inputs)
    form = string.Template(template)
    return form.substitute(cgi_name=name, http_method=method,
                           list_of_inputs=inputs, submit_text=text)

cgi-bin/sample285.py

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

import yate

print(yate.start_response())
print(yate.do_form('add_time_to_store.py', ['time_value'],
                   text='Send'))

server

入出力結果(Terminal, IPython)

$ ./simple_httpd.py
Starting simple_httpd on port: 8080
127.0.0.1 - - [04/Jul/2014 19:23:51] "GET /cgi-bin/sample297.py HTTP/1.1" 200 -
127.0.0.1 - - [04/Jul/2014 19:23:52] "GET /cgi-bin/sample297.py HTTP/1.1" 200 -
127.0.0.1 - - [04/Jul/2014 19:23:57] "POST /cgi-bin/add_time_to_store.py HTTP/1.1" 200 -
  C-c C-cTraceback (most recent call last):
  File "./simple_httpd.py", line 10, in <module>
    httpd.serve_forever()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/socketserver.py", line 236, in serve_forever
    poll_interval)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/socketserver.py", line 154, in _eintr_retry
    return func(*args)
KeyboardInterrupt
$

0 コメント:

コメントを投稿