LoginSignup
3
3

More than 5 years have passed since last update.

Python Jinja2

Posted at
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|GET データー取得
    #----------------------------------------------------------
    http_requests = cgi.FieldStorage()

    #----------------------------------------------------------
    # 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=あ">
    <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>
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3