LoginSignup
1
3

More than 5 years have passed since last update.

mod_wsgiでhugを使い、APIを作る

Posted at

hugはPythonでAPIを簡単に作るモジュールです。
mod_wsgiはPythonコードをApacheで動かすためのパッケージです。
これらを組み合わせて、Apacheで動くAPIを簡単に作ります。

hugアプリケーションをmod_wsgiで読み込む

PythonコードにWSGIに対応したapplicationを用意する必要があります。
hugにはapplicationが用意されており、以下ように読み込めます。

  • application = __hug_wsgi__
  • from hoge_hoge import __hug__wsgi__ as application

サンプルコード

# -*- coding:utf-8 -*-

import hug

@hug.get("/", examples="text=Hello World!")
def keyword_extraction_api(text: hug.types.text):
    return {'text': text}

application = __hug_wsgi__

これで、http://hoge-server.com/text=Hello%20World!とリクエストを送れば、{"text": "Hello World!"}が返ってきます。

ちょっとハマったところ

なかなかコードが実行できずハマった。
原因は__hug_wsgi__を最初に書いていたことである。
(おそらく、デコレータを書くと、メソッドが__hug_wsgi__に追加される?ため、最後に__hug_wsgi__を書くと良さそう。)

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