タイトル : Falcon 触ってみよう 2022/08
更新日 : 2022-08-31
カテゴリ : プログラミング
タグ :
python   
falcon   

触ってみる

Python軽量フレームワークFalconでAPI開発 入門(その1) を参考にfalconを触ってみる。

過去記事なのでメッセージ出るけど、以下の対応すれば falcon3.1.0 でOK

  • メッセージ:sys:1: DeprecatedWarning: Call to deprecated function init(...). API class may be removed in a future release,use falcon.App instead.

    app = falcon.API()を app = falcon.App() に

  • メッセージ:DeprecatedWarning: Call to deprecated property body. Please use text instead.self.result = application(self.environ, self.start_response)

    resp.body = json.dumps(msg) を resp.text = json.dumps(msg) に

以下、試した時のソースです。

app.py
import falcon

from middleware import ExampleMiddleware
from apitest1 import ApiTest1

# MiddlewareにExampleMiddlewareを指定
app = falcon.App(middleware=[
    ExampleMiddleware()
])

# ルータ
app.add_route("/", ApiTest1())

# サーバ
if __name__ == "__main__":
    from wsgiref import simple_server
    httpd = simple_server.make_server("127.0.0.1", 8088, app)
    httpd.serve_forever()
apitest1.py
import json
import falcon

import hooks


@falcon.before(hooks.before_resource)
@falcon.after(hooks.after_resource)
class ApiTest1(object):

    def on_get(self, req, resp):

        print("start ApiTest1 onget")
        msg = {
            "message": "Welcome to the Falcon",
            "param": req.params
        }

        resp.status = falcon.HTTP_200  # This is the default status
        # resp.content_type = falcon.MEDIA_TEXT # Default is JSON, so override
        resp.text = json.dumps(msg)
hooks.py
def before_resource(req, resp, resource, params):
    print('hook: before_resource')


def after_resource(req, resp, resource):
    print('hook: after_resource')
middleware.py
class ExampleMiddleware(object):

    def process_request(self, req, resp):
        print('middleware: process_request')

    def process_resource(self, req, resp, resource, params):
        print('middleware: process_resource')

    def process_response(self, req, resp, resource, req_succeeded):
        print('middleware: process_response')

上記を curl -v "127.0.0.1:8088?test=hoge&test=bar" で叩くと以下の感じです。

$ python app.py 
middleware: process_request
middleware: process_resource
hook: before_resource
start ApiTest1 onget
hook: after_resource
middleware: process_response
127.0.0.1 - - [01/Sep/2022 00:18:24] "GET /?test=hoge&test=bar HTTP/1.1" 200 72