Multifile Support

The file contains all of your view functions and route information, but you don’t have to keep all of your application code in your file.

As your application grows, you may reach out a point where you’d prefer to structure your application in multiple files. You can create a chalicelib/ directory, and anything in that directory is recursively included in the deployment package. This means that you can have files besides just .py files in chalicelib/, including .json files for config, or any kind of binary assets.

Let’s take a look at a few examples.

Consider the following app directory structure layout:

├── chalicelib
│   └──
└── requirements.txt

Where chalicelib/ contains:

MESSAGE = 'world'

and the file contains:

1from chalice import Chalice
2from chalicelib import MESSAGE
4app = Chalice(app_name="multifile")
7def index():
8    return {"hello": MESSAGE}

Note in line 2 we’re importing the MESSAGE variable from the chalicelib package, which is a top level directory in our project. We’ve created a chalicelib/ file which turns the chalicelib directory into a python package.

We can also use this directory to store config data. Consider this app structure layout:

├── chalicelib
│   └── config.json
└── requirements.txt

With chalicelib/config.json containing:

{"message": "world"}

In our code, we can load and use our config file:

 1import os
 2import json
 4from chalice import Chalice
 6app = Chalice(app_name="multifile")
 8filename = os.path.join(
 9    os.path.dirname(__file__), 'chalicelib', 'config.json')
10with open(filename) as f:
11    config = json.load(f)
14def index():
15    # We can access ``config`` here if we want.
16    return {"hello": config['message']}
Logging →