LoginSignup
18
12

More than 5 years have passed since last update.

Cloud Functions(Python)でコードファイルを分割する

Posted at

概要

Cloud FunctionsでPython(Bata)を利用する場合、関数のエントリーポイントは必ずmain.py ファイルである必要があります。

Cloud Functions The Python Runtime
https://cloud.google.com/functions/docs/concepts/python-runtime

Your function's entrypoint must be contained in a Python source file named main.py.

素直にmain.py に関数を追加していくと、きっと肥大化して悲しくなります。

なので、ファイル分割できないか試してみました。

実装

デプロイするファイルを準備します。

> mkdir 任意のディレクトリ
> cd 任意のディレクトリ
> mkdir src
> touch main.py
> touch hoge.py
> touch src/huge.py
main.py
from hoge import *
from src.huge import huge_huge

hoge.py
from flask import make_response


def hoge_hoge(request):
  return make_response('hoge!', 200)

src/huge.py
from flask import make_response


def huge_huge(request):
  return make_response('huge!', 200)

はい。
見てのとおりで、import ファイル名 from * とインポートすることで、実現できました。
import ファイル名 from 関数名 とすることも可能です。

検証

実際にデプロイして実行できるか、試してみます。

デプロイ
> gcloud functions deploy hoge_hoge --runtime=python37 --trigger-http
> gcloud functions deploy huge_huge --runtime=python37 --trigger-http

デプロイできたら実行してみます。

> gcloud functions call hoge_hoge --data "{}"

executionId: m10cogh13tx8
result: hoge!

> gcloud functions call huge_huge --data "{}"

executionId: 2adly82qzlts
result: huge!

やったぜ。
これで、main.py には実装を含めず、エントリーポイントとしての役割に特化させることができます。

まだ試していませんが、おそらくは規模が大きくなった場合、パッケージ化することで、さらにすっきりさせることができそうです。

参考

Cloud Functions The Python Runtime
https://cloud.google.com/functions/docs/concepts/python-runtime

簡単なPythonのパッケージを作る方法
https://qiita.com/himenoglyph/items/77f2534bc32eaad494dc

18
12
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
18
12