Multifile Support¶
The app.py
file contains all of your view functions and route
information, but you don’t have to keep all of your application
code in your app.py
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:
.
├── app.py
├── chalicelib
│ └── __init__.py
└── requirements.txt
Where chalicelib/__init__.py
contains:
MESSAGE = 'world'
and the app.py
file contains:
1from chalice import Chalice
2from chalicelib import MESSAGE
3
4app = Chalice(app_name="multifile")
5
6@app.route("/")
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/__init__.py
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:
.
├── app.py
├── chalicelib
│ └── config.json
└── requirements.txt
With chalicelib/config.json
containing:
{"message": "world"}
In our app.py
code, we can load and use our config file:
1import os
2import json
3
4from chalice import Chalice
5
6app = Chalice(app_name="multifile")
7
8filename = os.path.join(
9 os.path.dirname(__file__), 'chalicelib', 'config.json')
10with open(filename) as f:
11 config = json.load(f)
12
13@app.route("/")
14def index():
15 # We can access ``config`` here if we want.
16 return {"hello": config['message']}