Base code for python3, flask, zappa
- python3
- flask
- postgres
- sqlalchemy
- flask-migrate
- bulma css
- zappa (serverless deployment on aws)
- flask-s3 (static files from aws s3)
- Clone:
git clone https://github.com/tonyin/flask-base.git
- Set up virtualenv:
python3 -m venv venv
&&. venv/bin/activate
- Install libs:
pip install -r requirements.txt
- Create a config.env with required values (see config.py):
touch config.env
- Run:
./run.py
We use three environments:
- Development: Local machine and server development environment
- Production: What everyone sees
In order for zappa deploy
and other AWS command-line functions to work, you need to add your AWS credentials to a known location, usually somewhere like ~/.aws/credentials
. A sample credentials
file would look something like this:
[app-name]
aws_access_key_id = some20characterstring
aws_secret_access_key = SomeOtherLonger40characterstring
profile_name
: Use the app-name
that holds your AWS credentials
The first time, zappa deploy development
Thereafter, zappa update development
- Create a new AWS user to get security credentials. For permissions, add Lambda, API Gateway, RDS, IAM, and CloudFormation policies. At time of writing,
CloudFormation
requires a manual "inline" policy (as opposed to AWS-managed) - Create a public S3 bucket for your app to use for static assets
- Create a PostgreSQL db. Your
DATABASE_URL
will be in the formpostgresql:https://user:[email protected]/dbname
. If you plan to access the db remotely, use a dedicated security group and whitelist the IPs that you will use - Assign a VPC, subnets, and security group to your Lambda handler to enable proper permissions
- Upload Flask static assets with the
upload_assets.py
script, which should run automatically with no additional commands if the environment variables are set correctly - Navigate to your
.css
files and set theContent-Type
metadata totext/css
. Unfortunately this step must be done each time you upload, as there is no programmatic way to set the file metadata currently.
zappa deploy production
- The first deployment requires extra steps. In addition to the environment variables passed via
zappa_settings.json
, navigate to your app's Lambda function and add the following variables:DATABASE_URL
SECRET_KEY
MAIL_USERNAME
MAIL_PASSWORD
- To update,
zappa update
- To view logs,
zappa tail --since 1h
- Initialize:
flask db init
- Migrate:
flask db migrate
- Review code changes:
flask db edit
- Upgrade:
flask db upgrade
Custom css and js modules can be defined in app/static/css/app.css
and app/static/js/app.js
respectively. We already load in bulma, jquery, and fontawesome.
Lambda has a timeout of 30s, so longer-running tasks cannot be synchronously executed. To get around this, we asynchronously execute tasks with zappa's @task
decorator. For an example, see the email.py
function.