LoginSignup
1
0

More than 5 years have passed since last update.

How to use Tornado as python web framework #2 - tornado-JSON

Posted at

Overview

How to use Tornado as python web frameworkの続き

Tornado を使って INPUT/OUTPUTの validation checkが入ったAPIを作ってみる

Requirements

  • Python 3.4 or Higher
  • Tornado
  • tornado-JSON

Python, Tornado は前述の記事でインストール済みだが、
INPUT/OUTPUT validation を実装するに辺りtornado-JSONを使用する。

前の記事で、requirements.txt に以下の行を追加すれば、Docker Imageの作り直しで
tornado-JSONがインストールされる。

$ ls
Dockerfile  __init__.py  requirements.txt
$ cat requirements.txt
tornado==4.5.3
tornado-JSON==1.3.2
...

なお、Dockerを使わず、Bare-Metalな環境で使っている場合は以下のようにしてインストールする。
CentOSでPython34などを使っている場合は pip3 を使う。

pip install tornado-JSON
```

How to use - tornado-JSON解説

こちらの記事に
tornado-json自体の使い方は記載されているので、tornado-json のデモの使い方などについては割愛する。

Enhanced using

APIドキュメントの自動生成ロジック解説

こちらtornado_json.api_doc_genが呼ばれれば生成する、と記載があるが
具体的に作られるのかはDemoを見ろ、と有るのでどこでやっているのかと思ったが
hello_world.py のgenerate_docs=True の部分だった。

application = Application(routes=routes, settings={}, generate_docs=True)

Applicationを呼ぶ際にこのパラメータを付ける事でtornado_json.api_doc_gentornado_json.api_doc_gen```が呼び出され、
起動ディレクトリにAPI_Documentation.md が作られる。

handler の使い方

同じくDemoを見ると以下のようになっている。
ここをそれぞれapp.py等の起動ディレクトリを起点にディレクトリを指定するようだ。
つまり以下の内容は helloworld ディレクトリを import 及び search 対象とする、ということ。

import helloworld
routes = get_routes(helloworld)

後は、ディレクトリにある.pyファイルに ViewHandler, APIHandler が入っている物を取り出すようになる。

Plain/Text の返し方

ViewHandlerを使えば plain/text がセットされる、とあるが
return をどう書けば良いかというと以下の通り

class ReturnTextHandler(ViewHandler):
    """Return POST body by 'plain/txt' format"""
    def post(self):
        self.write(self.request.body)
        self.flush()

return で単純に request.body を渡したり self.success のような
helloworld等にあるサンプルを貼り付けるだけでは駄目のようだ。

1
0
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
1
0