index.cgi
#!/usr/local/bin/python2.7
# -*- coding: utf-8 -*-
import cgi
from jinja2 import Environment, FileSystemLoader
#----------------------------------------------------------
# CONFIG
#----------------------------------------------------------
_ENCODE = 'utf-8'
_HTML_TEMPLATE_FILE = 'index.tmpl'
#----------------------------------------------------------
# Jinja2 Wrapper
#----------------------------------------------------------
class HTTPtemplate(object):
def __init__(self, template_file):
self.endocing = 'utf-8'
self.data = {}
self.template_dir = './'
self.template_file = template_file
def set_encode(self,encode):
self.encode = encode
def set_template_dir(self, template_dir):
self.template_dir = template_dir
def set_data(self, key, value):
try :
value = unicode(value, self.encode)
except :
value = value
self.data[key] = value
def http_output(self):
env = Environment(loader=FileSystemLoader(self.template_dir, encoding=self.encode))
tmpl = env.get_template(self.template_file)
print tmpl.render(data=self.data).encode(self.encode)
#----------------------------------------------------------
# MAIN
#----------------------------------------------------------
def main():
#----------------------------------------------------------
# POST|Obtenez des données GET
#----------------------------------------------------------
http_requests = cgi.FieldStorage()
#----------------------------------------------------------
#Génération HTML
#----------------------------------------------------------
http = HTTPtemplate(_HTML_TEMPLATE_FILE)
http.set_encode(_ENCODE)
http.set_data('charset', _ENCODE)
http.set_data('request_get' , http_requests.getvalue('get' , None))
http.set_data('request_post', http_requests.getvalue('post' , None))
http.http_output()
if __name__ == '__main__' : main()
index.tmpl
Content-Type: text/html
<!DOCTYPE html>
<head>
<meta charset="{{data.charset}}">
<title>INDEX</title>
</head>
<body>
<form method="post" action="./?get=Ah">
<textarea name="post" cols="50" rows="1"></textarea>
<input type="submit" value="submit">
<p>GET :{{data.request_get}}</p>
<p>POST:{{data.request_post}}</p>
</form>
</body>
</html>
Recommended Posts