dackdive's blog

新米webエンジニアによる技術ブログ。JavaScript(React), Salesforce, Python など

[Google App Engine]静的ファイルをpythonで読み込む時の注意点

ちょっとつまづいた。

こんな感じで、python からファイルの読み込みを行いたい時がある。

# ---------------- views.py の一部 ----------------
from models import PostCard

class MainView(View):

    template_name = 'app/index.html'

    def get(self, request):
        posts = PostCard.query().fetch()
        if not posts:
            posts = PostCard.setup_preset_data()
# ---------------- models.py の一部 ----------------
PRESET_DATA_FILE = '/static/api/posts.json'

class PostCard(ndb.Model):
    uid = ndb.IntegerProperty()
    text = ndb.StringProperty()
    username = ndb.StringProperty()
    # avatar = 

    @classmethod
    def setup_preset_data(cls):
        f = open(PRESET_DATA_FILE, 'r')

        data = json.loads(f)
        (プリセットデータを生成する)

データストアにデータが全く無い場合は json ファイルから初期データを生成するような処理。

また、static ディレクトリ以下は静的リソースになるよう app.yaml で指定している。

handlers:
- url: /static
  static_dir: static

この状態でページを開くと、以下のように IOError: file not accessible と表示される。

f:id:dackdive:20150314225909p:plain

で、調べてみたが、どうやら
静的リソースとして app.yaml で指定したファイルは、python 側からは読み込めない
という仕様のようです。

app.yaml についての公式ドキュメントを読んでいるとそんなようなことが書かれていた。

https://cloud.google.com/appengine/docs/python/config/appconfig#Python_app_yaml_Static_file_handlers

For efficiency, App Engine stores and serves static files separately from application files. Static files are not available in the application's file system. If you have data files that need to be read by the application code, the data files must be application files, and must not be matched by a static file pattern.

リファレンス

あとは、このへんでも言及されてますね。

https://groups.google.com/forum/#!topic/google-appengine-python/jTLJRUCo8U0

http://d.hatena.ne.jp/kwatch/20100415/1271285578