Time for another installment of "how do python imports work please god help me"
I am creating a REST API to consume a request, validate it, write some data to DynamoDb, and send a message to SQS, and another python application to serve as a worker to listen for SQS events, consume messages, and make a bunch of different API calls to a 3rd party service, and write updates to the same DDB instance.
My hope is to contain all of this logic in a single repository, dockerize both python apps, and use CDK to deploy all of the infrastructure to AWS.
My problem is that I have models and utility functions that I would like to share between both services to make it easy to handle the data transferred to SQS and do the database read/writes - but I cant seem to figure out a way to easily share the models between my applications.
Desired repository structure
.
├── README.md
├── app
│ ├── Dockerfile.api
│ ├── Dockerfile.worker
│ ├── Pipfile
│ ├── Pipfile.lock
│ ├── __init__.py
│ ├── api
│ │ ├── __init__.py
│ │ ├── main.py
│ │ ├── routers
│ │ │ ├── __init__.py
│ │ │ ├── accounts.py
│ │ │ └── health.py
│ │ └── utils
│ │ ├── __init__.py
│ │ ├── database.py
│ │ └── settings.py
│ ├── shared
│ │ ├── __init__.py
│ │ ├── models
│ │ │ ├── __init__.py
│ │ │ ├── api_response.py
│ │ │ └── provisioning_request.py
│ │ └── utils
│ │ ├── __init__.py
│ │ ├── database.py
│ │ └── settings.py
│ └── worker
│ ├── __init__.py
│ ├── main.py
│ └── routers
│ ├── __init__.py
│ └── health.py
└── operations
└── all the CDK Stuff
What I want to be able to do:
# ./app/api/routers/account.py
from shared.models import ProvisioningRequest
# ./app/worker/main.py
from shared.models import ProvisioningRequest
I also need to be able to run this locally and bundle the shared + api/worker in my deploy to ECR (which i can manage in the respective dockerfiles once I get these imports sorted)
The problem:
❯ pipenv run python main.py
Traceback (most recent call last):
File "/Users/user/Documents/GitHub/project/app/api/main.py", line 7, in <module>
from routers import health, accounts
File "/Users/user/Documents/GitHub/project/app/api/routers/accounts.py", line 9, in <module>
from ..shared.models import ProvisioningRequest
ImportError: attempted relative import beyond top-level package
I keep getting import errors
I've Tried:
- Using a
setup.py
file in the top-levelapp
directory - Using syspath hacks (which i hope to avoid entirely)
- Using relative
..
imports