万年素人からHackerへの道

万年素人がHackerになれるまで殴り書きするぜ。

  • ・資産運用おすすめ
    10万円は1000円くらい利益
    資産運用ブログ アセマネ
    • ・寄付お願いします
      YENTEN:YYzNPzdsZWqr5THWAdMrKDj7GT8ietDc2W
      BitZenny:ZfpUbVya8MWQkjjGJMjA7P9pPkqaLnwPWH
      c0ban:8KG95GXdEquNpPW8xJAJf7nn5kbimQ5wj1
      Skycoin:KMqcn7x8REwwzMHPi9fV9fbNwdofYAWKRo

    TornadoでJSONを返す Python

    オライリー本のサンプルをいじった

    Michael Dory の Introduction to Tornado を Amazon でチェック! http://www.amazon.co.jp/gp/product/B007NHKVL6?ie=UTF8&camp=1207&creative=8411&creativeASIN=B007NHKVL6&linkCode=shr&tag=noctushinrsdi-22
    json_test.py

    import os.path
    
    import tornado.httpserver
    import tornado.ioloop
    import tornado.options
    import tornado.web
    import json 
    
    from tornado.options import define, options
    define("port", default=8000, help="run on the given port", type=int)
    
    class IndexHandler(tornado.web.RequestHandler):
        def get(self):
            self.render('index.html')
    
    class JsonPageHandler(tornado.web.RequestHandler):
        def post(self):
    
            noun1 = self.get_argument('noun1')
            noun2 = self.get_argument('noun2')
            noun3 = self.get_argument('noun3')
            verb = self.get_argument('verb')
    
            obj = { 
               'noun1': noun1,
               'noun2': noun2,
               'verb': verb,
               'noun3': noun3,
            }
    
            # self.write(json.JSONEncoder().encode(obj))
            my_json = json.dumps(obj, ensure_ascii=False)
            self.write(my_json)
    
    if __name__ == '__main__':
        tornado.options.parse_command_line()
        app = tornado.web.Application(
            handlers=[(r'/', IndexHandler), (r'/poem', JsonPageHandler)],
            template_path=os.path.join(os.path.dirname(__file__), "templates")
        )
        http_server = tornado.httpserver.HTTPServer(app)
        http_server.listen(options.port)
        tornado.ioloop.IOLoop.instance().start()
    

    ・index.html

    <!DOCTYPE html>
    <html>
        <head><title>Poem Maker Pro</title></head>
        <body>
            <h1>Enter terms below.</h1>
            <form method="post" action="/poem">
            <p>Plural noun<br><input type="text" name="noun1"></p>
            <p>Singular noun<br><input type="text" name="noun2"></p>
            <p>Verb (past tense)<br><input type="text" name="verb"></p>
            <p>Noun<br><input type="text" name="noun3"></p>
            <input type="submit">
            </form>
        </body>
    </html>
    

    ・フォーム

    ・結果

    {"noun1": "noun1だお", "noun2": "noun2だお", "noun3": "noun3だお", "verb": "Verbだす"}

    ※こうなった。


    注意

    self.write(json.JSONEncoder().encode(obj))
    

    上のようにやると、
    ↓のように日本語がエスケープされたので、

    {"verb": "Verb\u3060\u3059", "noun1": "noun1\u3060\u304a", "noun2": "noun2\u3060\u304a", "noun3": "noun3\u3060\u304a"}

    このサイトを参考にした。
    URL: http://iyukki.blog56.fc2.com/blog-entry-137.html