├── .github
└── workflows
│ ├── ci.yml
│ ├── publish.yml
│ └── publish_docs.yml
├── .gitignore
├── LICENSE
├── README.md
├── bridge
├── __init__.py
├── cli
│ ├── __init__.py
│ ├── bridge.py
│ ├── db
│ │ └── __init__.py
│ ├── errors.py
│ ├── init
│ │ ├── __init__.py
│ │ ├── install_deps.py
│ │ ├── render.py
│ │ └── templates
│ │ │ ├── __init__.py
│ │ │ ├── build__sh.py
│ │ │ ├── build_worker__sh.py
│ │ │ ├── deploy_to_render_button.py
│ │ │ ├── render__yaml.py
│ │ │ ├── start__sh.py
│ │ │ └── start_worker__sh.py
│ ├── package.yml
│ ├── redis
│ │ └── __init__.py
│ └── stop.py
├── config.py
├── console.py
├── framework
│ ├── __init__.py
│ ├── base.py
│ ├── django.py
│ └── package.yml
├── package.yml
├── platform
│ ├── __init__.py
│ ├── base.py
│ ├── package.yml
│ ├── postgres.py
│ ├── redis.py
│ └── render
│ │ ├── __init__.py
│ │ ├── postgres.py
│ │ └── redis.py
├── service
│ ├── __init__.py
│ ├── django_celery.py
│ ├── docker.py
│ ├── package.yml
│ ├── postgres.py
│ └── redis.py
└── utils
│ ├── __init__.py
│ ├── filesystem.py
│ ├── package.yml
│ ├── pydantic.py
│ └── sanitize.py
├── dev-requirements.txt
├── docs
├── bridge_init_render.gif
├── faq.md
├── favicon.ico
├── getting-started.md
├── index.md
├── runserver_demo.gif
└── runserver_noreload_cat_bridge_yaml.gif
├── mkdocs.yml
├── pyproject.toml
├── ruff.toml
├── tach.yml
└── tests
├── configuration
├── __init__.py
├── test_django_local.py
└── test_django_render.py
└── django
├── __init__.py
└── django_bridge
├── README.md
├── bridge-django-render
├── build-worker.sh
├── build.sh
├── install_deps.py
├── start-worker.sh
└── start.sh
├── bridge.yaml
├── django_bridge
├── __init__.py
├── custom_asgi.py
├── custom_wsgi.py
├── settings.py
└── urls.py
├── manage.py
├── polls
├── __init__.py
├── admin.py
├── apps.py
├── migrations
│ └── __init__.py
├── models.py
├── tasks.py
├── tests.py
└── views.py
├── render.yaml
└── requirements.txt
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python
3 |
4 | name: ci
5 |
6 | on:
7 | push:
8 | branches: [ "main" ]
9 | pull_request:
10 | branches: [ "main" ]
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 | strategy:
17 | fail-fast: false
18 | matrix:
19 | python-version: ["3.9", "3.10", "3.11", "3.12"]
20 |
21 | steps:
22 | # - uses: actions/checkout@v4 # for ssh, enable these 3 lines
23 | # - name: Setup upterm session
24 | # uses: lhotari/action-upterm@v1
25 | - uses: actions/checkout@v4
26 | - name: Set up Python ${{ matrix.python-version }}
27 | uses: actions/setup-python@v5
28 | with:
29 | python-version: ${{ matrix.python-version }}
30 | - name: Install dependencies
31 | run: |
32 | python -m pip install uv
33 | uv venv
34 | uv pip install -r dev-requirements.txt
35 | uv pip install .
36 | - name: Check ruff
37 | run: |
38 | source .venv/bin/activate
39 | ruff check .
40 | ruff format --check .
41 | - name: Check types with pyright
42 | run: |
43 | source .venv/bin/activate
44 | pyright bridge
45 | - name: Test django install
46 | run: |
47 | source .venv/bin/activate
48 | cd tests/django/django_bridge
49 | coverage run --branch --source=../../../ ./manage.py check
50 | coverage report
51 | cd ../../../
52 | - name: Run tests
53 | run: |
54 | source .venv/bin/activate
55 | pytest -s -vv
56 | - name: Run tach
57 | run: |
58 | source .venv/bin/activate
59 | tach check
60 |
61 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | # This workflow will upload a Python Package using Twine when a release is created
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries
3 |
4 | name: Publish python-bridge
5 |
6 | on:
7 | release:
8 | types: [published]
9 |
10 | permissions:
11 | contents: read
12 |
13 | jobs:
14 | publish:
15 | runs-on: ubuntu-latest
16 | steps:
17 | - uses: actions/checkout@v4
18 | - name: Set up Python
19 | uses: actions/setup-python@v5
20 | with:
21 | python-version: '3.x'
22 | - name: Install dependencies
23 | run: |
24 | python -m pip install --upgrade pip
25 | pip install build
26 | - name: Build package
27 | run: python -m build
28 | - name: Publish package
29 | uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
30 | with:
31 | password: ${{ secrets.PYPI_API_TOKEN }}
32 |
--------------------------------------------------------------------------------
/.github/workflows/publish_docs.yml:
--------------------------------------------------------------------------------
1 | name: publish_docs
2 | on:
3 | push:
4 | branches: [ "main" ]
5 | permissions:
6 | contents: write
7 | jobs:
8 | deploy:
9 | runs-on: ubuntu-latest
10 | steps:
11 | - uses: actions/checkout@v4
12 | - name: Configure Git Credentials
13 | run: |
14 | git config user.name github-actions[bot]
15 | git config user.email 41898282+github-actions[bot]@users.noreply.github.com
16 | - uses: actions/setup-python@v5
17 | with:
18 | python-version: 3.x
19 | - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
20 | - uses: actions/cache@v4
21 | with:
22 | key: mkdocs-material-${{ env.cache_id }}
23 | path: .cache
24 | restore-keys: |
25 | mkdocs-material-
26 | - run: pip install mkdocs-material
27 | - run: mkdocs gh-deploy --force
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/#use-with-ide
110 | .pdm.toml
111 |
112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113 | __pypackages__/
114 |
115 | # Celery stuff
116 | celerybeat-schedule
117 | celerybeat.pid
118 |
119 | # SageMath parsed files
120 | *.sage.py
121 |
122 | # Environments
123 | .env
124 | .venv
125 | env/
126 | venv/
127 | ENV/
128 | env.bak/
129 | venv.bak/
130 |
131 | # Spyder project settings
132 | .spyderproject
133 | .spyproject
134 |
135 | # Rope project settings
136 | .ropeproject
137 |
138 | # mkdocs documentation
139 | /site
140 |
141 | # mypy
142 | .mypy_cache/
143 | .dmypy.json
144 | dmypy.json
145 |
146 | # Pyre type checker
147 | .pyre/
148 |
149 | # pytype static type analyzer
150 | .pytype/
151 |
152 | # Cython debug symbols
153 | cython_debug/
154 |
155 | # PyCharm
156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158 | # and can be added to the global gitignore or merged into this file. For a more nuclear
159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160 | .idea/
161 | .python-version
162 | .env.leave
163 | bridge/service/pgdata/
164 |
165 |
166 | # Bridge configuration
167 | .bridge/
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://pypi.python.org/pypi/python-bridge)
2 | [](https://pypi.python.org/pypi/python-bridge)
3 | [](https://pypi.python.org/pypi/python-bridge)
4 | [](https://github.com/gauge-sh/bridge/actions/workflows/ci.yml)
5 | [](https://microsoft.github.io/pyright/)
6 | [](https://github.com/astral-sh/ruff)
7 | # bridge
8 | Fully automate your infrastructure for Django.
9 |
10 | 
11 |
12 | [Full Documentation](https://gauge-sh.github.io/bridge/)
13 |
14 | ### What is bridge?
15 | Bridge enables you to seamlessly run and deploy all the infrastructure you need for a complete Django project.
16 |
17 | - Two lines of copy-paste configuration
18 | - Local Postgres database automatically configured and connected
19 | - Local Redis instance automatically configured and connected
20 | - Local Celery and Celery Flower instance automatically configured and connected
21 | - Easy one-command deploy configuration to Render
22 |
23 | ### Installation
24 | Install [Docker](https://docs.docker.com/get-docker/) and verify it's running:
25 | ```bash
26 | > docker version
27 | Client: ...
28 | ```
29 | Install bridge:
30 | ```bash
31 | pip install python-bridge
32 | ```
33 | ### Usage
34 | Add the following code to the end of your `settings.py` file (or `DJANGO_SETTINGS_MODULE`):
35 | ```python
36 | from bridge import django
37 |
38 | django.configure(locals())
39 | ```
40 |
41 |
42 | The next time you start up your application, bridge will create and configure local infrastructure for you:
43 | ```bash
44 | > ./manage.py runserver
45 |
46 | Setting up service bridge_postgres...
47 | [12:00:00] ✓ Image postgres:12 pulled
48 | [12:00:00] ✓ Container bridge_postgres started
49 | [12:00:00] ✓ bridge_postgres is ready
50 | Service bridge_postgres started!
51 | Setting up service bridge_redis...
52 | [12:00:00] ✓ Image redis:7.2.4 pulled
53 | [12:00:00] ✓ Container bridge_redis started
54 | [12:00:00] ✓ bridge_redis is ready
55 | Service bridge_redis started!
56 | Setting up service bridge_celery...
57 | [12:00:00] ✓ Local worker started
58 | Service bridge_celery started!
59 | Setting up service bridge_flower...
60 | [12:00:00] ✓ Flower started
61 | Service bridge_flower started!
62 | Performing system checks...
63 |
64 | System check identified no issues (0 silenced).
65 | Starting development server at http://127.0.0.1:8000/
66 | Quit the server with CONTROL-C.
67 | ```
68 | That's it! You now have all the local infrastructure you need to run your django application.
69 |
70 | ### Deploys
71 | Bridge can also handle deployed configuration for your app as well! Simply run:
72 | ```bash
73 | bridge init render
74 | ```
75 | You may be prompted for the entrypoint of your application and settings file if bridge cannot detect them.
76 | Bridge will create all the configuration necessary for you to immediately deploy to [Render](https://render.com/). This includes a Blueprint `render.yaml` as well as build scripts and start scripts for your Django application.
77 | After running `bridge init render`, commit the changes and visit your project on github. You will see the following button at the end of your README in the root of your repository:
78 |
79 | 
80 |
81 | To deploy your application to the world, simply click the button! Bridge will configure everything needed for Render to deploy and host your app.
82 |
83 | In the future, we'll look into supporting more deployment runtimes such as Heroku, AWS, GCP, Azure, and more.
84 |
85 | ### FAQ
86 |
87 | How does bridge work?
88 | - Bridge spins up and runs all the services needed for your infrastructure in the background. Postgres and Redis run in docker containers, while Celery and Celery Flower (which need to understand your application code) run as background processes.
89 |
90 | What if I don't need all the services that bridge provides?
91 | - Bridge is designed to be modular. You can configure only the services you need by editing the `bridge.yaml` file that bridge creates in your project root. By default, `enable_postgres: true` and `enable_worker: true` are set, but you can change these to `false` to prevent bridge from configuring Postgres and Celery respectively.
92 |
93 | How can I stop the services that bridge spins up?
94 | - `bridge stop` will stop all running services.
95 |
96 | How can I access the database directly?
97 | - Locally, bridge provides access to a psql shell through `bridge db shell`. Remotely, [Render has instructions for connecting](https://docs.render.com/databases#connecting-with-the-external-url).
98 |
99 | How can I access redis directly?
100 | - Bridge provides access to redis-cli through `bridge redis shell`. Remotely, [Render has instructions for connecting](https://docs.render.com/redis#connecting-using-redis-cli).
101 |
102 | How can I access Celery?
103 | - Flower is a web interface into all the information you need to debug and work with Celery. By default, bridge will run Flower on http://localhost:5555.
104 |
--------------------------------------------------------------------------------
/bridge/__init__.py:
--------------------------------------------------------------------------------
1 | from bridge.framework import django
2 |
3 | __all__ = ["django"]
4 |
--------------------------------------------------------------------------------
/bridge/cli/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gauge-sh/bridge/8b34304e7db5ac888b26b4aebdb9102ea282f874/bridge/cli/__init__.py
--------------------------------------------------------------------------------
/bridge/cli/bridge.py:
--------------------------------------------------------------------------------
1 | import argparse
2 |
3 | from bridge.cli.db import open_database_shell
4 | from bridge.cli.init import initialize
5 | from bridge.cli.redis import open_redis_shell
6 | from bridge.cli.stop import stop
7 | from bridge.config import get_config
8 | from bridge.framework import Framework
9 |
10 |
11 | def detect_framework() -> Framework:
12 | # TODO: auto-detect framework (assuming Django)
13 | return Framework.DJANGO
14 |
15 |
16 | def main():
17 | # Create the top-level parser for the 'bridge' command
18 | parser = argparse.ArgumentParser(prog="bridge")
19 | # TODO: tie this version output to the version in pyproject.toml
20 | parser.add_argument("--version", action="version", version="%(prog)s 0.1.0")
21 | subparsers = parser.add_subparsers(dest="command")
22 |
23 | # Parser for 'stop'
24 | subparsers.add_parser("stop", help="Stop all running local services")
25 |
26 | # Parser for 'init' command
27 | init_parser = subparsers.add_parser(
28 | "init", help="Initialize configuration for a given platform (Render, Heroku)"
29 | )
30 | init_parser.add_argument(
31 | "init_platform",
32 | help="Platform where you want to deploy this app",
33 | choices=["render", "railway", "heroku"],
34 | )
35 |
36 | # Parser for db
37 | db_parser = subparsers.add_parser("db", help="Interact with the database")
38 | db_subparsers = db_parser.add_subparsers(dest="db_command")
39 | db_subparsers.add_parser("shell", help="Open a database shell (psql)")
40 |
41 | # Parser for redis
42 | redis_parser = subparsers.add_parser("redis", help="Interact with Redis")
43 | redis_subparsers = redis_parser.add_subparsers(dest="redis_command")
44 | redis_subparsers.add_parser("shell", help="Open a Redis shell (redis-cli)")
45 |
46 | # Parse the arguments
47 | args = parser.parse_args()
48 | framework = detect_framework()
49 | bridge_config = get_config()
50 |
51 | if args.command == "stop":
52 | stop()
53 | elif args.command == "init":
54 | initialize(
55 | framework=framework,
56 | platform=args.init_platform,
57 | bridge_config=bridge_config,
58 | )
59 | elif args.command == "db":
60 | if args.db_command == "shell":
61 | open_database_shell()
62 | else:
63 | db_parser.print_help()
64 | elif args.command == "redis":
65 | if args.redis_command == "shell":
66 | open_redis_shell()
67 | else:
68 | redis_parser.print_help()
69 | else:
70 | parser.print_help()
71 |
72 |
73 | if __name__ == "__main__":
74 | main()
75 |
--------------------------------------------------------------------------------
/bridge/cli/db/__init__.py:
--------------------------------------------------------------------------------
1 | import docker
2 |
3 | from bridge.service.postgres import PostgresService
4 |
5 |
6 | def open_database_shell():
7 | client = docker.from_env()
8 | postgres_service = PostgresService(client=client)
9 | postgres_service.start()
10 | postgres_service.shell()
11 |
--------------------------------------------------------------------------------
/bridge/cli/errors.py:
--------------------------------------------------------------------------------
1 | class CLIError(Exception): ...
2 |
3 |
4 | class ActionCancelledError(CLIError): ...
5 |
--------------------------------------------------------------------------------
/bridge/cli/init/__init__.py:
--------------------------------------------------------------------------------
1 | from bridge.cli.errors import ActionCancelledError
2 | from bridge.cli.init.render import build_render_init_config, initialize_render_platform
3 | from bridge.config import BridgeConfig
4 | from bridge.console import log_info, log_task
5 | from bridge.framework import Framework
6 |
7 |
8 | def initialize(framework: Framework, platform: str, bridge_config: BridgeConfig):
9 | if platform == "render":
10 | # Build config outside of log_task to avoid TUI interaction with status spinner
11 | try:
12 | config = build_render_init_config(
13 | framework=framework, bridge_config=bridge_config
14 | )
15 | except ActionCancelledError as e:
16 | log_info(str(e))
17 | return
18 | with log_task(
19 | "Initializing configuration for render...",
20 | "Configuration initialized for render",
21 | ):
22 | initialize_render_platform(config=config)
23 | elif platform in ["railway", "heroku"]:
24 | log_info(f"Platform '{platform}' is not supported yet")
25 | else:
26 | raise ValueError(
27 | "Unknown platform provided."
28 | " Known platforms: ['render', 'railway', 'heroku']"
29 | )
30 |
--------------------------------------------------------------------------------
/bridge/cli/init/install_deps.py:
--------------------------------------------------------------------------------
1 | # [Generated by Bridge]
2 | import os
3 | import subprocess
4 |
5 |
6 | def install_dependencies():
7 | # Check for requirements.txt and install using pip
8 | if os.path.exists("requirements.txt"):
9 | print("requirements.txt found. Installing dependencies...")
10 | subprocess.run(["pip", "install", "-r", "requirements.txt"], check=True)
11 |
12 | # Check for Pipfile.lock and install using Pipenv
13 | elif os.path.exists("Pipfile.lock"):
14 | print("Pipfile.lock found. Installing Pipenv and dependencies...")
15 | subprocess.run(["pip", "install", "pipx"], check=True)
16 | subprocess.run(["pipx", "install", "pipenv"], check=True)
17 | subprocess.run(["pipenv", "sync"], check=True)
18 |
19 | # Check for poetry.lock and install using Poetry
20 | elif os.path.exists("poetry.lock"):
21 | print("poetry.lock found. Installing Poetry and dependencies...")
22 | subprocess.run(["pip", "install", "pipx"], check=True)
23 | subprocess.run(["pipx", "install", "poetry"], check=True)
24 | subprocess.run(["poetry", "install"], check=True)
25 |
26 | else:
27 | print(
28 | "No dependency file found."
29 | " Please make sure you have a"
30 | " requirements.txt, Pipfile.lock, or poetry.lock file in the root of your project"
31 | )
32 |
33 |
34 | if __name__ == "__main__":
35 | install_dependencies()
36 |
--------------------------------------------------------------------------------
/bridge/cli/init/render.py:
--------------------------------------------------------------------------------
1 | import os
2 | import shutil
3 | from abc import ABC, abstractmethod
4 | from importlib.util import find_spec
5 | from pathlib import Path
6 | from typing import Optional
7 |
8 | from pydantic import BaseModel
9 | from rich.prompt import Confirm
10 |
11 | from bridge.cli.errors import ActionCancelledError
12 | from bridge.cli.init.templates import (
13 | build_sh_template,
14 | build_worker_sh_template,
15 | deploy_to_render_button_template,
16 | render_yaml_template,
17 | start_sh_template,
18 | start_worker_sh_template,
19 | )
20 | from bridge.cli.init.templates.deploy_to_render_button import button_exists_in_content
21 | from bridge.config import BridgeConfig
22 | from bridge.console import console, log_warning
23 | from bridge.framework import Framework
24 | from bridge.utils.filesystem import (
25 | resolve_dot_bridge,
26 | resolve_project_dir,
27 | set_executable,
28 | )
29 |
30 |
31 | def detect_django_settings_module(project_name: str = "") -> str:
32 | settings_path = Path(project_name) / "settings.py"
33 | if os.path.exists(settings_path):
34 | return f"{project_name}.settings"
35 | else:
36 | while True:
37 | module_path = console.input(
38 | "Please provide the path to your"
39 | " Django settings module (ex: myapp.settings):\n> "
40 | )
41 | if find_spec(module_path) is not None:
42 | # The module exists and can be imported
43 | return module_path
44 | else:
45 | console.print(
46 | f"The module {module_path} could not be found. Please try again."
47 | )
48 |
49 |
50 | class ApplicationCallable(BaseModel):
51 | path: str
52 | is_asgi: bool = False
53 |
54 |
55 | def detect_application_callable(project_name: str = "") -> ApplicationCallable:
56 | project_path = Path(project_name)
57 | wsgi_path = project_path / "wsgi.py"
58 | asgi_path = project_path / "asgi.py"
59 | if os.path.exists(wsgi_path):
60 | return ApplicationCallable(path=f"{project_name}.wsgi:application")
61 | elif os.path.exists(asgi_path):
62 | return ApplicationCallable(
63 | path=f"{project_name}.asgi:application", is_asgi=True
64 | )
65 |
66 | # If we haven't returned yet, it means we could not auto-detect the callable
67 | application_callable: Optional[ApplicationCallable] = None
68 | while True:
69 | user_input = console.input(
70 | "Please provide the path to your WSGI or ASGI application callable "
71 | "(ex: myapp.wsgi:application):\n> "
72 | )
73 | module_path, _, callable_name = user_input.partition(":")
74 | if not callable_name:
75 | callable_name = "application" # Default to 'application' if not provided
76 | try:
77 | if find_spec(module_path) is not None:
78 | application_callable = ApplicationCallable(
79 | path=f"{module_path}:{callable_name}"
80 | )
81 | break
82 | else:
83 | console.print(
84 | f"The module '{module_path}' could not be found or imported."
85 | " Please try again."
86 | )
87 | except ImportError:
88 | console.print(
89 | f"The module '{module_path}' could not be found or imported."
90 | " Please try again."
91 | )
92 |
93 | # If we have gotten here, it is because we have a valid application callable from user input
94 | application_callable.is_asgi = Confirm.ask(
95 | "Is this an ASGI application?", console=console
96 | )
97 | return application_callable
98 |
99 |
100 | class DjangoConfig(BaseModel):
101 | settings_module: str
102 |
103 |
104 | class RenderPlatformInitConfig(BaseModel):
105 | framework: Framework = Framework.DJANGO
106 | project_name: str
107 | app_path: str
108 | is_asgi: bool = False
109 | bridge_path: str
110 | enable_postgres: bool = True
111 | enable_worker: bool = True
112 | django_config: Optional[DjangoConfig] = None
113 |
114 | @property
115 | def script_dir(self) -> str:
116 | return f"bridge-{self.framework.value}-render"
117 |
118 |
119 | def build_render_init_config(
120 | framework: Framework, bridge_config: BridgeConfig
121 | ) -> RenderPlatformInitConfig:
122 | # NOTE: this method may request user input directly on the CLI
123 | # to determine configuration when it cannot be auto-detected
124 | project_name = resolve_project_dir().name
125 | app_path = detect_application_callable(project_name=project_name)
126 | bridge_path = resolve_dot_bridge()
127 | init_config = RenderPlatformInitConfig(
128 | project_name=project_name,
129 | app_path=app_path.path,
130 | is_asgi=app_path.is_asgi,
131 | bridge_path=str(bridge_path),
132 | enable_postgres=bridge_config.enable_postgres,
133 | enable_worker=bridge_config.enable_worker,
134 | )
135 |
136 | # Provide framework-specific configuration
137 | if framework == Framework.DJANGO:
138 | settings_module = detect_django_settings_module(project_name=project_name)
139 | init_config.django_config = DjangoConfig(settings_module=settings_module)
140 |
141 | os.makedirs(init_config.script_dir, exist_ok=True)
142 | if any(os.path.exists(file.PATH) for file in TEMPLATED_FILES):
143 | log_warning("Configuration files already exist.")
144 | if not Confirm.ask("Do you want to overwrite them? [y/N]", console=console):
145 | raise ActionCancelledError("Not overwriting existing configuration files.")
146 |
147 | return init_config
148 |
149 |
150 | class TemplatedFile(ABC):
151 | PATH: Path
152 | EXECUTABLE: bool = False
153 |
154 | @classmethod
155 | @abstractmethod
156 | def build(cls, config: RenderPlatformInitConfig) -> str: ...
157 |
158 | @classmethod
159 | def write(cls, config: RenderPlatformInitConfig):
160 | # For now, assume executables always belong in the script_dir
161 | prefix_path = Path(config.script_dir) if cls.EXECUTABLE else None
162 | path = prefix_path / cls.PATH if prefix_path else cls.PATH
163 | content = cls.build(config=config)
164 | if not content:
165 | # Empty or falsy content signals no file should be written
166 | return
167 |
168 | with path.open(mode="w") as f:
169 | f.write(content)
170 | if cls.EXECUTABLE:
171 | set_executable(path)
172 |
173 |
174 | class BuildSh(TemplatedFile):
175 | PATH = Path("build.sh")
176 | EXECUTABLE = True
177 |
178 | @classmethod
179 | def build(cls, config: RenderPlatformInitConfig) -> str:
180 | return build_sh_template(framework=config.framework)
181 |
182 |
183 | class BuildWorkerSh(TemplatedFile):
184 | PATH = Path("build-worker.sh")
185 | EXECUTABLE = True
186 |
187 | @classmethod
188 | def build(cls, config: RenderPlatformInitConfig) -> str:
189 | if config.enable_worker:
190 | return build_worker_sh_template(framework=config.framework)
191 | return ""
192 |
193 |
194 | class StartSh(TemplatedFile):
195 | PATH = Path("start.sh")
196 | EXECUTABLE = True
197 |
198 | @classmethod
199 | def build(cls, config: RenderPlatformInitConfig) -> str:
200 | return start_sh_template(app_path=config.app_path, is_asgi=config.is_asgi)
201 |
202 |
203 | class StartWorkerSh(TemplatedFile):
204 | PATH = Path("start-worker.sh")
205 | EXECUTABLE = True
206 |
207 | @classmethod
208 | def build(cls, config: RenderPlatformInitConfig) -> str:
209 | if config.enable_worker:
210 | return start_worker_sh_template(framework=config.framework)
211 | return ""
212 |
213 |
214 | class RenderYaml(TemplatedFile):
215 | PATH = Path("render.yaml")
216 |
217 | @classmethod
218 | def build(cls, config: RenderPlatformInitConfig) -> str:
219 | return render_yaml_template(
220 | framework=config.framework,
221 | script_dir=config.script_dir,
222 | service_name=config.project_name,
223 | database_name=f"{config.project_name}_db",
224 | enable_postgres=config.enable_postgres,
225 | enable_worker=config.enable_worker,
226 | django_settings_module=config.django_config.settings_module
227 | if config.django_config
228 | else "",
229 | )
230 |
231 |
232 | TEMPLATED_FILES = [
233 | BuildSh,
234 | BuildWorkerSh,
235 | StartSh,
236 | StartWorkerSh,
237 | RenderYaml,
238 | ]
239 |
240 |
241 | def add_deploy_render_button_to_readme():
242 | # NOTE: assumes we are in the project dir
243 | if os.path.exists("README.md"):
244 | with open("README.md") as f:
245 | if button_exists_in_content(f.read()):
246 | # Button already in README, don't write anything to the file
247 | return
248 | with open("README.md", "a") as f:
249 | f.write(deploy_to_render_button_template())
250 | else:
251 | with open("README.md", "w") as f:
252 | f.write(deploy_to_render_button_template())
253 |
254 |
255 | def add_install_deps_script(config: RenderPlatformInitConfig):
256 | # Assuming 'install_deps.py' is in the same directory as this file
257 | src_path = Path(__file__).parent / "install_deps.py"
258 | if not src_path.exists():
259 | raise FileNotFoundError("install_deps.py not found in the expected location.")
260 | dst_path = Path(config.script_dir) / "install_deps.py"
261 | shutil.copyfile(src_path, dst_path)
262 |
263 |
264 | def initialize_render_platform(config: RenderPlatformInitConfig):
265 | add_deploy_render_button_to_readme()
266 | add_install_deps_script(config)
267 | for file in TEMPLATED_FILES:
268 | file.write(config)
269 |
--------------------------------------------------------------------------------
/bridge/cli/init/templates/__init__.py:
--------------------------------------------------------------------------------
1 | from bridge.cli.init.templates.build__sh import build_sh_template
2 | from bridge.cli.init.templates.build_worker__sh import build_worker_sh_template
3 | from bridge.cli.init.templates.deploy_to_render_button import (
4 | deploy_to_render_button_template,
5 | )
6 | from bridge.cli.init.templates.render__yaml import render_yaml_template
7 | from bridge.cli.init.templates.start__sh import start_sh_template
8 | from bridge.cli.init.templates.start_worker__sh import start_worker_sh_template
9 |
10 | __all__ = (
11 | "build_sh_template",
12 | "build_worker_sh_template",
13 | "deploy_to_render_button_template",
14 | "render_yaml_template",
15 | "start_sh_template",
16 | "start_worker_sh_template",
17 | )
18 |
--------------------------------------------------------------------------------
/bridge/cli/init/templates/build__sh.py:
--------------------------------------------------------------------------------
1 | from bridge.framework.base import Framework
2 |
3 | template = """#!/usr/bin/env bash
4 | # Exit on error
5 | set -o errexit
6 |
7 | # Get the directory of the current script.
8 | DIR="$(dirname "$0")"
9 |
10 | # Use our Python script to install dependencies
11 | INSTALL_DEPS_SCRIPT="$DIR/install_deps.py"
12 | python "$INSTALL_DEPS_SCRIPT"
13 |
14 | # Install additional dependencies
15 | pip install gunicorn uvicorn psycopg-binary whitenoise[brotli]
16 |
17 | # Collect static asset files
18 | python manage.py collectstatic --no-input
19 |
20 | # Apply any outstanding database migrations
21 | python manage.py migrate
22 | """
23 |
24 |
25 | def build_sh_template(framework: Framework) -> str:
26 | if framework != Framework.DJANGO:
27 | raise NotImplementedError(
28 | f"Unsupported framework for Render platform: {framework}"
29 | )
30 | return template.format()
31 |
--------------------------------------------------------------------------------
/bridge/cli/init/templates/build_worker__sh.py:
--------------------------------------------------------------------------------
1 | from bridge.framework.base import Framework
2 |
3 | template = """#!/usr/bin/env bash
4 | # Exit on error
5 | set -o errexit
6 |
7 | # Modify this line as needed for your package manager (pip, poetry, etc.)
8 | pip install -r requirements.txt
9 |
10 | # Install additional dependencies
11 | pip install psycopg-binary
12 | """
13 |
14 |
15 | def build_worker_sh_template(framework: Framework) -> str:
16 | if framework != Framework.DJANGO:
17 | raise NotImplementedError(
18 | f"Unsupported framework for Render platform: {framework}"
19 | )
20 | return template.format()
21 |
--------------------------------------------------------------------------------
/bridge/cli/init/templates/deploy_to_render_button.py:
--------------------------------------------------------------------------------
1 | RENDER_BUTTON_TAG = "DEPLOY_TO_RENDER_BUTTON"
2 |
3 |
4 | def as_html_comment(tag: str) -> str:
5 | return f""
6 |
7 |
8 | template = f"""# Bridge Deployment
9 |
10 | {as_html_comment(RENDER_BUTTON_TAG)}
11 | [](https://render.com/deploy)
12 | """
13 |
14 |
15 | def deploy_to_render_button_template():
16 | # No args for now, but we can templatize the github repo URL in the future
17 | return template
18 |
19 |
20 | def button_exists_in_content(content: str) -> bool:
21 | return as_html_comment(RENDER_BUTTON_TAG) in content
22 |
--------------------------------------------------------------------------------
/bridge/cli/init/templates/render__yaml.py:
--------------------------------------------------------------------------------
1 | from bridge.framework.base import Framework
2 | from bridge.utils.sanitize import sanitize_postgresql_identifier
3 |
4 | postgres_template = """
5 | databases:
6 | - name: {service_name}-db
7 | plan: free
8 | databaseName: {database_name}
9 | user: {database_user}
10 | """
11 |
12 | postgres_app_env_template = """ - key: DATABASE_URL
13 | fromDatabase:
14 | name: {service_name}-db
15 | property: connectionString"""
16 |
17 |
18 | worker_template = """
19 | - type: redis
20 | name: {service_name}-redis
21 | plan: free
22 | ipAllowList: []
23 | - type: worker
24 | name: {service_name}-worker
25 | runtime: python
26 | buildCommand: ./{script_dir}/build-worker.sh
27 | startCommand: ./{script_dir}/start-worker.sh
28 | envVars:
29 | - key: BRIDGE_PLATFORM
30 | value: render
31 | - key: DJANGO_SETTINGS_MODULE
32 | value: {django_settings_module}
33 | - key: SECRET_KEY
34 | generateValue: true
35 | - key: TASK_CONCURRENCY
36 | value: 4
37 | - key: DEBUG
38 | value: "False"
39 | - key: DATABASE_URL
40 | fromDatabase:
41 | name: {service_name}-db
42 | property: connectionString
43 | - key: REDIS_URL
44 | fromService:
45 | name: {service_name}-redis
46 | type: redis
47 | property: connectionString
48 | """
49 |
50 | worker_app_env_template = """ - key: REDIS_URL
51 | fromService:
52 | name: {service_name}-redis
53 | type: redis
54 | property: connectionString"""
55 |
56 |
57 | template = """services:
58 | - type: web
59 | plan: starter
60 | runtime: python
61 | name: {service_name}
62 | buildCommand: ./{script_dir}/build.sh
63 | startCommand: ./{script_dir}/start.sh
64 | envVars:
65 | - key: BRIDGE_PLATFORM
66 | value: render
67 | - key: SECRET_KEY
68 | generateValue: true
69 | - key: WEB_CONCURRENCY
70 | value: 4
71 | - key: DEBUG
72 | value: "False"
73 | {postgres_app_env}
74 | {worker_app_env}
75 | {worker_service}
76 | {postgres_service}
77 | """
78 |
79 |
80 | def render_yaml_template(
81 | framework: Framework,
82 | script_dir: str,
83 | service_name: str,
84 | enable_postgres: bool = True,
85 | enable_worker: bool = True,
86 | database_name: str = "",
87 | database_user: str = "",
88 | django_settings_module: str = "",
89 | ) -> str:
90 | # TODO: use a real templating engine
91 | if framework != Framework.DJANGO:
92 | raise NotImplementedError(
93 | f"Unsupported framework for Render platform: {framework}"
94 | )
95 |
96 | if not django_settings_module:
97 | raise ValueError(
98 | "Failed to template render.yaml:"
99 | " DJANGO_SETTINGS_MODULE is required for Django projects"
100 | )
101 |
102 | if enable_postgres:
103 | database_name = database_name or service_name
104 | database_user = database_user or service_name
105 | postgres_service = postgres_template.format(
106 | service_name=service_name,
107 | database_name=sanitize_postgresql_identifier(database_name),
108 | database_user=sanitize_postgresql_identifier(database_user),
109 | )
110 | postgres_app_env = postgres_app_env_template.format(service_name=service_name)
111 | else:
112 | postgres_service = ""
113 | postgres_app_env = ""
114 |
115 | if enable_worker:
116 | worker_service = worker_template.format(
117 | service_name=service_name,
118 | script_dir=script_dir,
119 | django_settings_module=django_settings_module,
120 | )
121 | worker_app_env = worker_app_env_template.format(service_name=service_name)
122 | else:
123 | worker_service = ""
124 | worker_app_env = ""
125 |
126 | return (
127 | template.format(
128 | script_dir=script_dir,
129 | service_name=service_name,
130 | postgres_app_env=postgres_app_env,
131 | worker_app_env=worker_app_env,
132 | worker_service=worker_service,
133 | postgres_service=postgres_service,
134 | ).rstrip()
135 | + "\n"
136 | )
137 |
--------------------------------------------------------------------------------
/bridge/cli/init/templates/start__sh.py:
--------------------------------------------------------------------------------
1 | uvicorn_worker_string = "-k uvicorn.workers.UvicornWorker"
2 |
3 | template = """#!/usr/bin/env bash
4 | gunicorn {app_path} -w "${{WEB_CONCURRENCY:-4}}" -b 0.0.0.0:"$PORT" {worker_string}
5 | """
6 |
7 |
8 | def start_sh_template(app_path: str, is_asgi: bool = False) -> str:
9 | return template.format(
10 | app_path=app_path, worker_string=uvicorn_worker_string if is_asgi else ""
11 | )
12 |
--------------------------------------------------------------------------------
/bridge/cli/init/templates/start_worker__sh.py:
--------------------------------------------------------------------------------
1 | from bridge.framework.base import Framework
2 |
3 | template = """#!/usr/bin/env bash
4 | celery -A bridge.service.django_celery worker -l INFO --concurrency="${{TASK_CONCURRENCY:-4}}"
5 | """
6 |
7 |
8 | def start_worker_sh_template(framework: Framework) -> str:
9 | if framework != Framework.DJANGO:
10 | raise NotImplementedError(
11 | f"Unsupported framework for Render platform: {framework}"
12 | )
13 | return template.format()
14 |
--------------------------------------------------------------------------------
/bridge/cli/package.yml:
--------------------------------------------------------------------------------
1 | tags: ['bridge.cli']
2 |
--------------------------------------------------------------------------------
/bridge/cli/redis/__init__.py:
--------------------------------------------------------------------------------
1 | import docker
2 |
3 | from bridge.service.redis import RedisService
4 |
5 |
6 | def open_redis_shell():
7 | client = docker.from_env()
8 | postgres_service = RedisService(client=client)
9 | postgres_service.start()
10 | postgres_service.shell()
11 |
--------------------------------------------------------------------------------
/bridge/cli/stop.py:
--------------------------------------------------------------------------------
1 | import os
2 | import signal
3 | from typing import cast
4 |
5 | import docker
6 | import psutil
7 | from docker.errors import NotFound
8 | from docker.models.containers import Container
9 |
10 | from bridge.console import log_task
11 | from bridge.utils.filesystem import resolve_dot_bridge
12 |
13 |
14 | def stop():
15 | with log_task("Stopping bridge services...", "All bridge services stopped"):
16 | bridge_path = resolve_dot_bridge()
17 | # Docker - postgres, redis
18 | cid_path = bridge_path / "cid"
19 | if os.path.exists(cid_path):
20 | docker_client = docker.from_env()
21 | with open(cid_path) as f:
22 | for cid in f.readlines():
23 | cid = cid.strip()
24 | try:
25 | container = docker_client.containers.get(cid)
26 | container = cast(Container, container)
27 | container.stop()
28 | except NotFound:
29 | pass
30 | os.remove(cid_path)
31 | # Processes - celery, flower
32 | # TODO make this a helper method
33 | for proc in psutil.process_iter(["pid", "name", "cmdline"]):
34 | try:
35 | # Check if the name fragment is in the command line; this field is a list
36 | proc_name = proc.info["cmdline"]
37 | if proc_name and "bridge.service.django_celery" in proc_name:
38 | proc.send_signal(signal.SIGTERM)
39 | except (psutil.NoSuchProcess, psutil.AccessDenied):
40 | pass
41 |
--------------------------------------------------------------------------------
/bridge/config.py:
--------------------------------------------------------------------------------
1 | from pathlib import Path
2 | from typing import Optional
3 |
4 | import yaml
5 | from pydantic import BaseModel
6 | from yaml import CDumper as Dumper
7 | from yaml import CLoader as Loader
8 | from yaml import dump, load
9 |
10 | from bridge.console import log_warning
11 |
12 |
13 | class BridgeConfig(BaseModel):
14 | enable_postgres: bool = True
15 | enable_worker: bool = True
16 |
17 | def to_yaml(self) -> str:
18 | return dump(self.model_dump(), Dumper=Dumper)
19 |
20 | @classmethod
21 | def from_yaml(cls, data: str) -> "BridgeConfig":
22 | return cls.model_validate(load(data, Loader=Loader))
23 |
24 |
25 | CONFIG_PATH = Path("bridge.yaml")
26 |
27 |
28 | def ensure_config_file():
29 | if not CONFIG_PATH.exists():
30 | with CONFIG_PATH.open(mode="w") as f:
31 | f.write(BridgeConfig().to_yaml())
32 |
33 |
34 | __CONFIG: Optional[BridgeConfig] = None
35 |
36 |
37 | def get_config() -> BridgeConfig:
38 | # NOTE: not thread-safe
39 | global __CONFIG
40 | if __CONFIG is not None:
41 | return __CONFIG
42 |
43 | ensure_config_file()
44 | try:
45 | with CONFIG_PATH.open(mode="r") as f:
46 | __CONFIG = BridgeConfig.from_yaml(f.read())
47 | except yaml.YAMLError:
48 | log_warning("Failed to read configuration file. Using default configuration.")
49 | __CONFIG = BridgeConfig()
50 |
51 | return __CONFIG
52 |
--------------------------------------------------------------------------------
/bridge/console.py:
--------------------------------------------------------------------------------
1 | from contextlib import contextmanager
2 | from datetime import datetime
3 |
4 | from rich.console import Console
5 |
6 | console = Console()
7 |
8 |
9 | @contextmanager
10 | def log_task(start_message: str, end_message: str):
11 | with console.status(
12 | f" {start_message}", spinner="aesthetic", spinner_style="blue"
13 | ):
14 | try:
15 | # Before entering the block
16 | yield
17 | finally:
18 | # After exiting the block
19 |
20 | # Format the current time to include leading zeros (HH:MM:SS)
21 | timestamp_str = datetime.now().strftime("[%H:%M:%S]")
22 | console.print(
23 | f"{timestamp_str} [bright_green]✓[/bright_green] {end_message}",
24 | highlight=False,
25 | )
26 |
27 |
28 | def log_error(message: str) -> None:
29 | console.print(f"[bright_red]✗ Bridge Error[/bright_red]: {message}")
30 |
31 |
32 | def log_warning(message: str) -> None:
33 | console.print(f"[yellow]Bridge Warning[/yellow]: {message}")
34 |
35 |
36 | def log_info(message: str) -> None:
37 | console.print(f"[cyan]Bridge Info[/cyan]: {message}")
38 |
--------------------------------------------------------------------------------
/bridge/framework/__init__.py:
--------------------------------------------------------------------------------
1 | from bridge.framework.base import Framework
2 |
3 | __all__ = ["Framework"]
4 |
--------------------------------------------------------------------------------
/bridge/framework/base.py:
--------------------------------------------------------------------------------
1 | import os
2 | from abc import ABC, abstractmethod
3 | from enum import Enum
4 | from typing import Any
5 |
6 | import docker
7 |
8 | from bridge.config import BridgeConfig
9 | from bridge.platform import Platform, detect_platform
10 | from bridge.service.postgres import PostgresService
11 | from bridge.service.redis import RedisService
12 |
13 |
14 | class Framework(Enum):
15 | DJANGO = "django"
16 | FLASK = "flask"
17 | FASTAPI = "fastapi"
18 |
19 |
20 | class FrameWorkHandler(ABC):
21 | FRAMEWORK: Framework = NotImplemented
22 |
23 | def __init__(
24 | self,
25 | project_name: str,
26 | framework_locals: dict[Any, Any],
27 | bridge_config: BridgeConfig,
28 | ):
29 | self.project_name = project_name
30 | self.framework_locals = framework_locals
31 | self.enable_postgres = bridge_config.enable_postgres
32 | self.enable_worker = bridge_config.enable_worker
33 |
34 | def is_remote(self) -> bool:
35 | """
36 | Check if the application seems to be running on a remote platform.
37 | Specific frameworks may be able to detect this more accurately and
38 | should override this method.
39 | """
40 | return bool(os.environ.get("BRIDGE_PLATFORM"))
41 |
42 | def run(self) -> None:
43 | """Start services."""
44 | platform = detect_platform() if self.is_remote() else Platform.LOCAL
45 | self.configure_services(platform)
46 | if platform == Platform.LOCAL:
47 | self.start_local_services()
48 |
49 | def configure_services(self, platform: Platform) -> None:
50 | if self.enable_postgres:
51 | self.configure_postgres(platform=platform)
52 | if self.enable_worker:
53 | # NOTE: worker and flower MUST be configured last, since they
54 | # will read the framework locals immediately
55 | self.configure_worker(platform=platform)
56 |
57 | def start_local_services(self):
58 | """Start local services if necessary"""
59 | client = docker.from_env()
60 | if self.enable_postgres:
61 | self.start_local_postgres(client)
62 | if self.enable_worker:
63 | self.start_local_redis(client)
64 | self.start_local_worker()
65 | self.start_local_flower()
66 |
67 | def start_local_postgres(self, client: docker.DockerClient) -> None:
68 | service = PostgresService(client=client)
69 | service.start()
70 |
71 | def start_local_redis(self, client: docker.DockerClient) -> None:
72 | service = RedisService(client=client)
73 | service.start()
74 |
75 | @abstractmethod
76 | def start_local_worker(self) -> None:
77 | """start a local celery instance configured for the correct framework"""
78 | pass
79 |
80 | @abstractmethod
81 | def start_local_flower(self) -> None:
82 | """start a local celery flower instance configured for the correct framework"""
83 |
84 | @abstractmethod
85 | def configure_postgres(self, platform: Platform) -> None:
86 | """Update framework_locals with the correct configuration for postgres"""
87 | pass
88 |
89 | @abstractmethod
90 | def configure_worker(self, platform: Platform) -> None:
91 | """Update framework_locals with the correct configuration for celery"""
92 | pass
93 |
--------------------------------------------------------------------------------
/bridge/framework/django.py:
--------------------------------------------------------------------------------
1 | import os
2 | import signal
3 | import socket
4 | import subprocess
5 | import sys
6 | from time import sleep
7 | from typing import Any
8 |
9 | import psutil
10 | from rich.console import Console
11 |
12 | from bridge.config import get_config
13 | from bridge.console import log_info, log_task, log_warning
14 | from bridge.framework.base import Framework, FrameWorkHandler
15 | from bridge.platform import Platform
16 | from bridge.platform.postgres import build_postgres_environment
17 | from bridge.platform.redis import build_redis_environment
18 | from bridge.utils.filesystem import resolve_dot_bridge
19 |
20 |
21 | class DjangoHandler(FrameWorkHandler):
22 | FRAMEWORK = Framework.DJANGO
23 |
24 | def is_remote(self) -> bool:
25 | # Django's DEBUG mode should be disabled in production,
26 | # so we use it to differentiate between running locally
27 | # and running on an unknown remote platform.
28 | is_debug_mode = bool(self.framework_locals.get("DEBUG"))
29 | return super().is_remote() or not is_debug_mode
30 |
31 | def configure_services(self, platform: Platform) -> None:
32 | super().configure_services(platform)
33 | # Additional Django-specific configuration
34 | self.configure_staticfiles(platform)
35 | self.configure_allowed_hosts(platform)
36 | self.configure_debug(platform)
37 | self.configure_secret_key(platform)
38 |
39 | def configure_postgres(self, platform: Platform) -> None:
40 | if "DATABASES" in self.framework_locals:
41 | log_info(
42 | "Overwriting existing DATABASES configuration with Postgres configuration."
43 | )
44 |
45 | environment = build_postgres_environment(platform=platform)
46 | self.framework_locals["DATABASES"] = {
47 | "default": {
48 | "ENGINE": "django.db.backends.postgresql",
49 | "NAME": environment.db,
50 | "USER": environment.user,
51 | "PASSWORD": environment.password,
52 | "HOST": environment.host,
53 | "PORT": environment.port,
54 | }
55 | }
56 |
57 | def configure_allowed_hosts(self, platform: Platform) -> None:
58 | if platform == Platform.RENDER:
59 | if (
60 | "ALLOWED_HOSTS" in self.framework_locals
61 | and self.framework_locals["ALLOWED_HOSTS"]
62 | ):
63 | log_info(
64 | "Overwriting ALLOWED_HOSTS configuration with Render configuration."
65 | )
66 | self.framework_locals["ALLOWED_HOSTS"] = [".onrender.com", "localhost"]
67 |
68 | def configure_debug(self, platform: Platform) -> None:
69 | if platform != Platform.LOCAL:
70 | if "DEBUG" in self.framework_locals and self.framework_locals["DEBUG"]:
71 | log_warning(
72 | "DEBUG is truthy in remote environment; overwriting configuration to False."
73 | )
74 | self.framework_locals["DEBUG"] = False
75 |
76 | def configure_secret_key(self, platform: Platform) -> None:
77 | if platform != Platform.LOCAL:
78 | if (
79 | "SECRET_KEY" in self.framework_locals
80 | and "SECRET_KEY" in os.environ
81 | and self.framework_locals["SECRET_KEY"]
82 | and self.framework_locals != os.environ.get("SECRET_KEY")
83 | ):
84 | # If the SECRET_KEY from the current remote environment is different
85 | # from an explicitly set SECRET_KEY in the framework locals, we should
86 | # log this to the console.
87 | log_info("Overwriting SECRET_KEY configuration in remote environment.")
88 | self.framework_locals["SECRET_KEY"] = os.environ.get(
89 | "SECRET_KEY", self.framework_locals.get("SECRET_KEY", "")
90 | )
91 |
92 | def configure_staticfiles(self, platform: Platform):
93 | if platform == Platform.RENDER:
94 | if (
95 | "STATIC_URL" in self.framework_locals
96 | or "STATIC_ROOT" in self.framework_locals
97 | or "STATICFILES_DIRS" in self.framework_locals
98 | or "STATICFILES_STORAGE" in self.framework_locals
99 | ):
100 | log_info(
101 | "Overwriting existing staticfiles configuration with Render configuration."
102 | )
103 | self.framework_locals["STATIC_URL"] = "/static/"
104 | self.framework_locals["STATIC_ROOT"] = os.path.join(
105 | self.framework_locals["BASE_DIR"], "staticfiles"
106 | )
107 | self.framework_locals["STATICFILES_STORAGE"] = (
108 | "whitenoise.storage.CompressedManifestStaticFilesStorage"
109 | )
110 | middleware: list[str] = self.framework_locals.get("MIDDLEWARE", [])
111 | if "whitenoise.middleware.WhiteNoiseMiddleware" not in middleware:
112 | security_middleware_idx = next(
113 | (
114 | i
115 | for i, middleware in enumerate(middleware)
116 | if middleware == "django.middleware.security.SecurityMiddleware"
117 | ),
118 | None,
119 | )
120 | if security_middleware_idx is not None:
121 | middleware.insert( # TODO this won't work with a tuple, we may want to modify
122 | security_middleware_idx + 1,
123 | "whitenoise.middleware.WhiteNoiseMiddleware",
124 | )
125 | else:
126 | middleware.insert(0, "whitenoise.middleware.WhiteNoiseMiddleware")
127 | self.framework_locals["MIDDLEWARE"] = middleware
128 |
129 | def configure_worker(self, platform: Platform) -> None:
130 | environment = build_redis_environment(platform)
131 | self.framework_locals["CELERY_BROKER_URL"] = environment.url
132 | self.framework_locals["CELERY_RESULT_BACKEND"] = environment.url
133 |
134 | # This will make sure the app is always imported when
135 | # Django starts so that shared_task will use this app.
136 | from bridge.service.django_celery import app # noqa: F401 type: ignore
137 |
138 | def start_local_worker(self) -> None:
139 | # Confirm we are in a command which expects Celery to be available
140 | expected_command_args = {"runserver", "runserver_plus", "shell", "shell_plus"}
141 | if set(sys.argv) & expected_command_args:
142 | console = Console()
143 | console.print(
144 | "[bold bright_green]Setting up service "
145 | "[white]bridge_celery[/white]..."
146 | )
147 | with log_task("Starting local worker", "Local worker started"):
148 | from bridge.service.django_celery import app
149 |
150 | # Kill any active celery processes
151 | for proc in psutil.process_iter(["pid", "name", "cmdline"]):
152 | try:
153 | proc_name = proc.info["cmdline"]
154 | if (
155 | proc_name
156 | and "bridge.service.django_celery" in proc_name
157 | and "worker" in proc_name
158 | ):
159 | proc.send_signal(signal.SIGTERM)
160 | except (psutil.NoSuchProcess, psutil.AccessDenied):
161 | pass
162 | subprocess.Popen(
163 | "nohup "
164 | "celery -A bridge.service.django_celery worker -c 1 -l INFO"
165 | " > /dev/null 2>&1 &",
166 | shell=True,
167 | stdin=subprocess.DEVNULL,
168 | stdout=subprocess.DEVNULL,
169 | stderr=subprocess.STDOUT,
170 | start_new_session=True,
171 | )
172 | while not app.control.inspect().ping():
173 | # Wait for celery to start
174 | sleep(0.1)
175 | console.print(
176 | "[bold bright_green]Service [white]bridge_celery[/white] started!"
177 | )
178 |
179 | def start_local_flower(self) -> None:
180 | # Confirm we are in a command which expects flower to be available
181 | expected_command_args = {"runserver", "runserver_plus", "shell", "shell_plus"}
182 | if set(sys.argv) & expected_command_args:
183 | console = Console()
184 | console.print(
185 | "[bold bright_green]Setting up service "
186 | "[white]bridge_flower[/white]..."
187 | )
188 | with log_task("Starting flower", "Flower started"):
189 | # Kill any active flower process
190 | for proc in psutil.process_iter(["pid", "name", "cmdline"]):
191 | try:
192 | proc_name = proc.info["cmdline"]
193 | if (
194 | proc_name
195 | and "bridge.service.django_celery" in proc_name
196 | and "flower" in proc_name
197 | ):
198 | proc.send_signal(signal.SIGTERM)
199 | except (psutil.NoSuchProcess, psutil.AccessDenied):
200 | pass
201 | dot_bridge_path = resolve_dot_bridge() / "flower_db"
202 | subprocess.Popen(
203 | "nohup "
204 | "celery -A bridge.service.django_celery flower "
205 | f"--persistent=True --db='{dot_bridge_path}'"
206 | " > /dev/null 2>&1 &",
207 | shell=True,
208 | stdin=subprocess.DEVNULL,
209 | stdout=subprocess.DEVNULL,
210 | stderr=subprocess.STDOUT,
211 | start_new_session=True,
212 | )
213 | port_bound = False
214 | while not port_bound:
215 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
216 | port_bound = s.connect_ex(("localhost", 5555)) == 0
217 | sleep(0.1)
218 |
219 | console.print(
220 | "[bold bright_green]Service [white]bridge_flower[/white] started!"
221 | )
222 |
223 |
224 | def configure(settings_locals: dict[Any, Any]) -> None:
225 | project_name = os.path.basename(settings_locals["BASE_DIR"])
226 | handler = DjangoHandler(
227 | project_name=project_name,
228 | framework_locals=settings_locals,
229 | bridge_config=get_config(),
230 | )
231 | handler.run()
232 |
--------------------------------------------------------------------------------
/bridge/framework/package.yml:
--------------------------------------------------------------------------------
1 | tags: ['bridge.framework']
2 |
--------------------------------------------------------------------------------
/bridge/package.yml:
--------------------------------------------------------------------------------
1 | tags: ['bridge']
2 |
--------------------------------------------------------------------------------
/bridge/platform/__init__.py:
--------------------------------------------------------------------------------
1 | from bridge.platform.base import Platform, detect_platform
2 |
3 | __all__ = ["Platform", "detect_platform"]
4 |
--------------------------------------------------------------------------------
/bridge/platform/base.py:
--------------------------------------------------------------------------------
1 | import os
2 | from enum import Enum
3 |
4 |
5 | class Platform(Enum):
6 | """Enumeration of supported platforms."""
7 |
8 | LOCAL = "local"
9 | UNKNOWN_REMOTE = "unknown_remote"
10 | HEROKU = "heroku"
11 | RENDER = "render"
12 | RAILWAY = "railway"
13 |
14 |
15 | def detect_platform():
16 | """
17 | Detect the platform based on environment variables.
18 |
19 | NOTE: Assumes that the application is running in some kind of remote environment,
20 | since each framework may define a local/debug environment differently
21 | and should be checked individually, before calling this method to disambiguate.
22 | """
23 | platform = os.environ.get("BRIDGE_PLATFORM")
24 | if platform:
25 | try:
26 | return Platform(platform)
27 | except ValueError:
28 | return Platform.UNKNOWN_REMOTE
29 | return Platform.UNKNOWN_REMOTE
30 |
--------------------------------------------------------------------------------
/bridge/platform/package.yml:
--------------------------------------------------------------------------------
1 | tags: ['bridge.platform']
2 |
--------------------------------------------------------------------------------
/bridge/platform/postgres.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | from pydantic import BaseModel
4 |
5 | from bridge.console import log_warning
6 | from bridge.platform.base import Platform
7 |
8 |
9 | class PostgresEnvironment(BaseModel):
10 | user: str = "postgres"
11 | password: str = "postgres"
12 | db: str = "postgres"
13 | host: str = "localhost"
14 | port: int = 5432
15 |
16 | @classmethod
17 | def from_env(cls):
18 | try:
19 | port = int(os.environ.get("POSTGRES_PORT", 5432))
20 | except ValueError:
21 | log_warning("Invalid POSTGRES_PORT; using default value.")
22 | port = 5432
23 | return cls(
24 | user=os.environ.get("POSTGRES_USER", "postgres"),
25 | password=os.environ.get("POSTGRES_PASSWORD", "postgres"),
26 | db=os.environ.get("POSTGRES_DB", "postgres"),
27 | host=os.environ.get("POSTGRES_HOST", "localhost"),
28 | port=port,
29 | )
30 |
31 |
32 | def build_postgres_environment(platform: Platform) -> PostgresEnvironment:
33 | if platform == Platform.LOCAL:
34 | # This uses hardcoded default values,
35 | # and must match the values used in the PostgresService class
36 | # which runs locally.
37 | return PostgresEnvironment()
38 | elif platform == Platform.RENDER:
39 | from bridge.platform.render import build_render_postgres_environment
40 |
41 | return build_render_postgres_environment()
42 | elif platform == Platform.UNKNOWN_REMOTE:
43 | # This will pull from environment variables like POSTGRES_USER, etc.
44 | return PostgresEnvironment.from_env()
45 | else:
46 | raise ValueError(f"Unsupported platform for configuring Postgres: {platform}")
47 |
--------------------------------------------------------------------------------
/bridge/platform/redis.py:
--------------------------------------------------------------------------------
1 | from pydantic import BaseModel
2 |
3 | from bridge.platform.base import Platform
4 |
5 |
6 | class RedisEnvironment(BaseModel):
7 | host: str = "localhost"
8 | port: int = 6379
9 | db: int = 0
10 |
11 | @property
12 | def url(self) -> str:
13 | return f"redis://{self.host}:{self.port}/{self.db}"
14 |
15 |
16 | def build_redis_environment(platform: Platform) -> RedisEnvironment:
17 | if platform == Platform.LOCAL:
18 | return RedisEnvironment()
19 | elif platform == Platform.RENDER:
20 | from bridge.platform.render import build_render_redis_environment
21 |
22 | return build_render_redis_environment()
23 | else:
24 | raise NotImplementedError(f"Unsupported platform for Redis: {platform}")
25 |
--------------------------------------------------------------------------------
/bridge/platform/render/__init__.py:
--------------------------------------------------------------------------------
1 | from bridge.platform.render.postgres import build_render_postgres_environment
2 | from bridge.platform.render.redis import build_render_redis_environment
3 |
4 | __all__ = ["build_render_postgres_environment", "build_render_redis_environment"]
5 |
--------------------------------------------------------------------------------
/bridge/platform/render/postgres.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import dj_database_url
4 |
5 | from bridge.platform.postgres import PostgresEnvironment
6 |
7 |
8 | def build_render_postgres_environment() -> PostgresEnvironment:
9 | try:
10 | database_url = os.environ["DATABASE_URL"]
11 | except KeyError as e:
12 | raise ValueError("DATABASE_URL is required for Render Postgres") from e
13 | config: dj_database_url.DBConfig = dj_database_url.config(
14 | default=database_url,
15 | )
16 | # Assertion here satisfies pyright
17 | assert (
18 | "HOST" in config
19 | and "PORT" in config
20 | and "NAME" in config
21 | and "USER" in config
22 | and "PASSWORD" in config
23 | ), "DATABASE_URL configuration is missing required keys"
24 |
25 | port = 5432 if not config["PORT"] else int(config["PORT"])
26 | return PostgresEnvironment( # key presence checked above
27 | host=config["HOST"],
28 | port=port,
29 | db=config["NAME"],
30 | user=config["USER"],
31 | password=config["PASSWORD"],
32 | )
33 |
--------------------------------------------------------------------------------
/bridge/platform/render/redis.py:
--------------------------------------------------------------------------------
1 | import os
2 | import re
3 |
4 | from bridge.service.redis import RedisEnvironment
5 |
6 |
7 | def build_render_redis_environment() -> RedisEnvironment:
8 | # REDIS_URL contains the entire connection string, so we need to parse it
9 | # Regex to match the connection string components
10 | conn_string = os.environ.get("REDIS_URL")
11 | if not conn_string:
12 | raise ValueError("REDIS_URL environment variable must be set on Render.")
13 | redis_env = RedisEnvironment()
14 | # Optional password terminated with '@'
15 | # Hostname that does not contain ':' or '/'
16 | # Optional port number preceded by ':'
17 | # Optional database number preceded by '/'
18 | regex = (
19 | r"^redis:\/\/(?:(?P[^@]+)@)?(?P[^:\/]+)"
20 | r"(?::(?P\d+))?(?:\/(?P\d+))?$"
21 | )
22 | match = re.match(regex, conn_string)
23 |
24 | if match:
25 | components = match.groupdict()
26 | redis_env.host = components["host"] or "localhost"
27 | redis_env.port = int(components["port"] or 6379)
28 | redis_env.db = int(components["db"] or 0)
29 | else:
30 | raise ValueError("Invalid Redis connection string format in REDIS_URL.")
31 |
32 | return redis_env
33 |
--------------------------------------------------------------------------------
/bridge/service/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gauge-sh/bridge/8b34304e7db5ac888b26b4aebdb9102ea282f874/bridge/service/__init__.py
--------------------------------------------------------------------------------
/bridge/service/django_celery.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | from celery import Celery
4 |
5 | if "DJANGO_SETTINGS_MODULE" not in os.environ:
6 | raise ValueError(
7 | "DJANGO_SETTINGS_MODULE must be set in the environment to run Celery"
8 | )
9 |
10 | project_name = os.environ["DJANGO_SETTINGS_MODULE"].split(".")[0]
11 | app = Celery(project_name)
12 |
13 | # Using a string here means the worker doesn't have to serialize
14 | # the configuration object to child processes.
15 | # - namespace='CELERY' means all celery-related configuration keys
16 | # should have a `CELERY_` prefix.
17 | app.config_from_object("django.conf:settings", namespace="CELERY", force=True)
18 |
19 | # Load task modules from all registered Django apps.
20 | app.autodiscover_tasks()
21 |
22 |
23 | @app.task(bind=True)
24 | def debug_task(self):
25 | print(f"Request: {self.request!r}")
26 |
--------------------------------------------------------------------------------
/bridge/service/docker.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from abc import ABC, abstractmethod
3 | from typing import TYPE_CHECKING, Generic, TypeVar, Union, cast
4 |
5 | import docker
6 | from docker.models.containers import Container
7 | from pydantic import BaseModel, Field
8 | from rich.console import Console
9 |
10 | from bridge.console import log_error, log_task
11 | from bridge.utils.filesystem import resolve_dot_bridge
12 | from bridge.utils.pydantic import Empty
13 |
14 | if TYPE_CHECKING:
15 | import docker.errors
16 |
17 |
18 | def get_docker_client() -> docker.DockerClient:
19 | try:
20 | client = docker.from_env()
21 | except docker.errors.DockerException:
22 | log_error("Make sure docker is installed and running")
23 | sys.exit(1)
24 |
25 | return client
26 |
27 |
28 | T_BaseModel = TypeVar("T_BaseModel", bound=BaseModel)
29 |
30 |
31 | class ContainerConfig(BaseModel, Generic[T_BaseModel]):
32 | """
33 | Container configuration information.
34 |
35 | All the data needed to start a container.
36 | """
37 |
38 | image: str
39 | name: str
40 | ports: dict[str, int] = Field(default_factory=dict)
41 | volumes: dict[str, Union[list[str], dict[str, str]]] = Field(default_factory=dict)
42 | restart_policy: dict[str, str] = {"Name": "always"}
43 | environment: T_BaseModel = Field(default_factory=Empty)
44 |
45 |
46 | T_ContainerConfig = TypeVar("T_ContainerConfig", bound=ContainerConfig)
47 |
48 |
49 | class DockerService(ABC, Generic[T_ContainerConfig]):
50 | def __init__(self, client: docker.DockerClient, config: T_ContainerConfig) -> None:
51 | self.client = client
52 | self.config = config
53 | self.container_id = None
54 | # todo add self.container - should we start or fetch the container on startup?
55 |
56 | def start(self):
57 | console = Console()
58 | console.print(
59 | f"[bold bright_green]Setting up service "
60 | f"[white]{self.config.name}[/white]..."
61 | )
62 | self.pull_image()
63 | self.start_container()
64 | self.ensure_ready()
65 | self.register()
66 | console.print(
67 | f"[bold bright_green]Service [white]{self.config.name}[/white] started!"
68 | )
69 |
70 | def register(self):
71 | bridge_cid_path = resolve_dot_bridge() / "cid"
72 | with open(bridge_cid_path, "a") as f:
73 | f.write(f"{self.container_id}\n")
74 |
75 | def pull_image(self):
76 | with log_task(
77 | start_message=f"Pulling [white]{self.config.image}",
78 | end_message=f"Image [white]{self.config.image}[/white] pulled",
79 | ):
80 | if not self.client.images.list(name=self.config.image):
81 | self.client.images.pull(self.config.image)
82 |
83 | def start_container(self):
84 | with log_task(
85 | start_message=f"Starting container [white]{self.config.name}[/white]",
86 | end_message=f"Container [white]{self.config.name}[/white] started",
87 | ):
88 | containers = self.client.containers.list(
89 | filters={"name": self.config.name}, all=True
90 | )
91 | if containers:
92 | # Container names are unique, there are 1 or 0 results
93 | [model] = containers
94 | container = cast(Container, model)
95 | if container.status in ["paused", "exited"]:
96 | container.restart()
97 | else:
98 | container = self.client.containers.run(
99 | **self.config.model_dump(),
100 | detach=True,
101 | )
102 | container = cast(Container, container)
103 | self.container_id = container.id
104 |
105 | @abstractmethod
106 | def ensure_ready(self) -> None:
107 | pass
108 |
--------------------------------------------------------------------------------
/bridge/service/package.yml:
--------------------------------------------------------------------------------
1 | tags: ['bridge.service']
2 |
--------------------------------------------------------------------------------
/bridge/service/postgres.py:
--------------------------------------------------------------------------------
1 | import os
2 | from time import sleep
3 | from typing import Optional, Union
4 |
5 | import docker
6 | import psycopg
7 | from pydantic import BaseModel, Field
8 |
9 | from bridge.console import log_task
10 | from bridge.service.docker import ContainerConfig, DockerService
11 | from bridge.utils.filesystem import resolve_dot_bridge
12 |
13 |
14 | class PostgresEnvironment(BaseModel):
15 | POSTGRES_USER: str = "postgres"
16 | POSTGRES_PASSWORD: str = "postgres"
17 | POSTGRES_DB: str = "postgres"
18 | POSTGRES_HOST: str = "localhost"
19 | POSTGRES_PORT: str = "5432"
20 |
21 |
22 | class PostgresConfig(ContainerConfig[PostgresEnvironment]):
23 | image: str = "postgres:12"
24 | name: str = "bridge_postgres"
25 | ports: dict[str, int] = {"5432/tcp": 5432}
26 | volumes: dict[str, Union[list[str], dict[str, str]]] = Field(
27 | default_factory=lambda: {
28 | str(resolve_dot_bridge() / "pgdata"): {
29 | "bind": "/var/lib/postgresql/data",
30 | "mode": "rw",
31 | }
32 | }
33 | )
34 | environment: PostgresEnvironment = Field(default_factory=PostgresEnvironment)
35 |
36 |
37 | class PostgresService(DockerService[PostgresConfig]):
38 | def __init__(
39 | self, client: docker.DockerClient, config: Optional[PostgresConfig] = None
40 | ) -> None:
41 | super().__init__(client, config or PostgresConfig())
42 |
43 | def ensure_ready(self):
44 | dsn = (
45 | f"dbname={self.config.environment.POSTGRES_DB} "
46 | f"user={self.config.environment.POSTGRES_USER} "
47 | f"password={self.config.environment.POSTGRES_PASSWORD} "
48 | f"host={self.config.environment.POSTGRES_HOST} "
49 | f"port={self.config.environment.POSTGRES_PORT}"
50 | )
51 | with log_task(
52 | start_message=f"Waiting for [white]{self.config.name}[/white] to be ready",
53 | end_message=f"[white]{self.config.name}[/white] is ready",
54 | ):
55 | while True:
56 | try:
57 | with psycopg.connect(dsn) as conn, conn.cursor() as cur:
58 | cur.execute("SELECT 1")
59 | return
60 | except psycopg.OperationalError:
61 | sleep(0.1)
62 |
63 | def shell(self):
64 | # Open a shell to the Postgres container
65 | # NOTE: This entirely replaces the currently running process!
66 | os.execvp(
67 | "docker",
68 | [
69 | "docker",
70 | "exec",
71 | "-it",
72 | self.config.name,
73 | "psql",
74 | "-U",
75 | self.config.environment.POSTGRES_USER,
76 | "-d",
77 | self.config.environment.POSTGRES_DB,
78 | "-h",
79 | self.config.environment.POSTGRES_HOST,
80 | "-p",
81 | self.config.environment.POSTGRES_PORT,
82 | ],
83 | )
84 |
--------------------------------------------------------------------------------
/bridge/service/redis.py:
--------------------------------------------------------------------------------
1 | import os
2 | from time import sleep
3 | from typing import Optional
4 |
5 | import docker
6 | import redis
7 |
8 | from bridge.console import log_task
9 | from bridge.platform.redis import RedisEnvironment
10 | from bridge.service.docker import ContainerConfig, DockerService
11 |
12 |
13 | class RedisConfig(ContainerConfig):
14 | image: str = "redis:7.2.4"
15 | name: str = "bridge_redis"
16 | ports: dict[str, int] = {"6379/tcp": 6379}
17 |
18 |
19 | class RedisService(DockerService[RedisConfig]):
20 | def __init__(
21 | self, client: docker.DockerClient, config: Optional[RedisConfig] = None
22 | ) -> None:
23 | super().__init__(client, config or RedisConfig())
24 | self.redis_client_environment = RedisEnvironment()
25 |
26 | def ensure_ready(self):
27 | with log_task(
28 | start_message=f"Waiting for [white]{self.config.name}[/white] to be ready",
29 | end_message=f"[white]{self.config.name}[/white] is ready",
30 | ):
31 | while True:
32 | try:
33 | # Attempt to create a connection to Redis
34 | r = redis.Redis(
35 | host=self.redis_client_environment.host,
36 | port=self.redis_client_environment.port,
37 | )
38 | if r.ping():
39 | return # Redis is ready and responding
40 | except redis.ConnectionError:
41 | sleep(0.1)
42 |
43 | def shell(self):
44 | # Open a shell to the Redis container
45 | # NOTE: This entirely replaces the currently running process!
46 | os.execvp("docker", ["docker", "exec", "-it", self.config.name, "redis-cli"])
47 |
--------------------------------------------------------------------------------
/bridge/utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gauge-sh/bridge/8b34304e7db5ac888b26b4aebdb9102ea282f874/bridge/utils/__init__.py
--------------------------------------------------------------------------------
/bridge/utils/filesystem.py:
--------------------------------------------------------------------------------
1 | import os
2 | import stat
3 | import sys
4 | from pathlib import Path
5 |
6 | from bridge.console import log_error
7 |
8 |
9 | def set_executable(file_path: Path) -> None:
10 | file_path.chmod(
11 | file_path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
12 | )
13 |
14 |
15 | def resolve_project_dir() -> Path:
16 | current_dir = os.getcwd()
17 | manage_py_path = Path(os.path.join(current_dir, "manage.py"))
18 | if not manage_py_path.exists():
19 | log_error(
20 | f"No manage.py file found in {os.getcwd()}. "
21 | f"Run the command from the same directory as manage.py"
22 | )
23 | sys.exit(1)
24 |
25 | return Path(current_dir)
26 |
27 |
28 | def resolve_dot_bridge() -> Path:
29 | project_dir = resolve_project_dir()
30 |
31 | def _create(path: str, is_file: bool = False, file_content: str = "") -> None:
32 | if not os.path.exists(path):
33 | if is_file:
34 | with open(path, "w") as f:
35 | f.write(file_content.strip())
36 | else:
37 | os.makedirs(path)
38 |
39 | # Create .bridge
40 | bridge_path = os.path.join(project_dir, ".bridge")
41 | _create(bridge_path)
42 | # Create pgdata
43 | pgdata_path = os.path.join(bridge_path, "pgdata")
44 | _create(pgdata_path)
45 | # Create .gitignore
46 | gitignore_content = """
47 | # This folder is for bridge configuration. Do not edit.
48 |
49 | # gitignore all content, including this .gitignore
50 | *
51 | """
52 | gitignore_path = os.path.join(bridge_path, ".gitignore")
53 | _create(gitignore_path, is_file=True, file_content=gitignore_content)
54 | return Path(bridge_path)
55 |
--------------------------------------------------------------------------------
/bridge/utils/package.yml:
--------------------------------------------------------------------------------
1 | tags: ['bridge.utils']
2 |
--------------------------------------------------------------------------------
/bridge/utils/pydantic.py:
--------------------------------------------------------------------------------
1 | from pydantic import BaseModel
2 |
3 |
4 | class Empty(BaseModel): ...
5 |
--------------------------------------------------------------------------------
/bridge/utils/sanitize.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 |
4 | def sanitize_postgresql_identifier(input_string: str):
5 | # Remove leading and trailing whitespace
6 | sanitized = input_string.strip()
7 |
8 | # Replace spaces and other disallowed characters with underscores
9 | sanitized = re.sub(r"\W", "_", sanitized)
10 |
11 | # Ensure the name starts with a letter or underscore
12 | if not re.match(r"^[a-zA-Z_]", sanitized):
13 | sanitized = "_" + sanitized
14 |
15 | # Truncate to 63 characters to meet Postgres limitations
16 | sanitized = sanitized[:63]
17 |
18 | return sanitized
19 |
--------------------------------------------------------------------------------
/dev-requirements.txt:
--------------------------------------------------------------------------------
1 | ruff==0.4.1
2 | pytest==8.1.1
3 | pytest-mock==3.14.0
4 | django-stubs==4.2.7
5 | pyright==1.1.360
6 | coverage==7.4.4
7 | tach==0.1.2
--------------------------------------------------------------------------------
/docs/bridge_init_render.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gauge-sh/bridge/8b34304e7db5ac888b26b4aebdb9102ea282f874/docs/bridge_init_render.gif
--------------------------------------------------------------------------------
/docs/faq.md:
--------------------------------------------------------------------------------
1 | # FAQ
2 |
3 | ### How does it work locally?
4 |
5 | When running locally, Bridge uses Docker to create and manage containers for Postgres and Redis. Since Bridge is included in your settings module, it automatically configures your Django application to connect to these services. Celery and Flower require your application code, and are spun up as background processes.
6 |
7 | ### How does it work with deployments?
8 |
9 | When you are ready to deploy, Bridge creates configuration files for Render that specify how to build and run your Django application alongside the same services. Bridge also writes a "Deploy to Render" button straight into your README for added convenience! You can deploy your application by clicking the 'Deploy to Render' button shown on your project's GitHub page.
10 |
11 | ### What if I don't need all the services that bridge provides?
12 |
13 | Bridge is designed to be modular. You can configure only the services you need by creating or editing the `bridge.yaml` file that Bridge creates in your project root. By default, `enable_postgres: true` and `enable_worker: true` are set, but you can change these to `false` to prevent bridge from configuring Postgres and Celery respectively.
14 |
15 |
16 | ### How can I stop the services that bridge spins up?
17 | `bridge stop` will stop all running services.
18 |
19 |
20 | ### How can I access the database directly?
21 | Locally, bridge provides access to a psql shell through `bridge db shell`. Remotely, [Render has instructions for connecting](https://docs.render.com/databases#connecting-with-the-external-url).
22 |
23 | ### How can I access redis directly?
24 | Bridge provides access to redis-cli through `bridge redis shell`. Remotely, [Render has instructions for connecting](https://docs.render.com/redis#connecting-using-redis-cli).
25 |
26 | ### How can I access Celery?
27 | Flower is a web interface into all the information you need to debug and work with Celery. By default, bridge will run Flower on [http://localhost:5555](http://localhost:5555).
28 |
--------------------------------------------------------------------------------
/docs/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gauge-sh/bridge/8b34304e7db5ac888b26b4aebdb9102ea282f874/docs/favicon.ico
--------------------------------------------------------------------------------
/docs/getting-started.md:
--------------------------------------------------------------------------------
1 | # Getting Started
2 |
3 | Bridge includes an SDK and CLI tool which operate within your Django project. This page will guide you through the process of installing and configuring Bridge.
4 |
5 | ## Requirements
6 | Bridge requires **[Docker](https://docs.docker.com/get-docker/)** to be installed on your machine.
7 | Verify your docker installation with:
8 | ```bash
9 | > docker version
10 | Client: ...
11 | ```
12 |
13 | ## Installation
14 | Install bridge from PyPI:
15 | ```bash
16 | pip install python-bridge
17 | ```
18 |
19 | ## Usage
20 | Adding bridge to your project is incredibly simple.
21 |
22 | Add the following code to the end of your `settings.py` file (or `DJANGO_SETTINGS_MODULE`):
23 | ```python
24 | # Configure infrastructure with Bridge.
25 | # All other settings should be above these lines.
26 | from bridge import django
27 |
28 | django.configure(locals())
29 | ```
30 |
31 | The next time you start up your application, bridge will create and configure local infrastructure for you:
32 | ```bash
33 | > ./manage.py runserver
34 |
35 | Setting up service bridge_postgres...
36 | [12:00:00] ✓ Image postgres:12 pulled
37 | [12:00:00] ✓ Container bridge_postgres started
38 | [12:00:00] ✓ bridge_postgres is ready
39 | Service bridge_postgres started!
40 | Setting up service bridge_redis...
41 | [12:00:00] ✓ Image redis:7.2.4 pulled
42 | [12:00:00] ✓ Container bridge_redis started
43 | [12:00:00] ✓ bridge_redis is ready
44 | Service bridge_redis started!
45 | Setting up service bridge_celery...
46 | [12:00:00] ✓ Local worker started
47 | Service bridge_celery started!
48 | Setting up service bridge_flower...
49 | [12:00:00] ✓ Flower started
50 | Service bridge_flower started!
51 | Performing system checks...
52 |
53 | System check identified no issues (0 silenced).
54 | Starting development server at http://127.0.0.1:8000/
55 | Quit the server with CONTROL-C.
56 | ```
57 | That's it! You now have all the local infrastructure you need to run your django application.
58 |
59 | ### Deploys
60 | Bridge can handle deployed configuration for your app too! Simply run:
61 | ```bash
62 | bridge init render
63 | ```
64 | You may be prompted for the entrypoint of your application and settings file if bridge cannot detect them.
65 |
66 | Bridge will create all the configuration necessary for you to immediately deploy to [Render](https://render.com/). This includes a Blueprint `render.yaml` as well as build scripts and start scripts for your Django application.
67 |
68 | After running `bridge init render`, commit the changes and visit your project on GitHub. You will see the following button at the end of your README in the root of your repository:
69 |
70 | 
71 |
72 | To deploy your application to the world, simply click the button! Bridge will configure everything needed for Render to deploy and host your app.
73 |
74 | In the future, we'll look into supporting more deployment runtimes such as Heroku, AWS, GCP, Azure, and more.
75 |
76 | ### Project Structure
77 |
78 | !!! note
79 |
80 | Bridge currently makes assumptions about your project structure as outlined below. If your project does not follow these conventions, you may need to adjust the generated files before deploying.
81 |
82 | Bridge assumes the following project structure:
83 | ```
84 | /
85 | ├── /
86 | │ ├── settings.py
87 | │ ├── [wsgi.py | asgi.py]
88 | │ ├── ...
89 | ├── manage.py
90 | ├── [requirements.txt | poetry.lock | Pipfile.lock]
91 | ├── ...
92 | ```
93 |
94 | This structure is the default for Django projects created with `django-admin startproject`. The generated build script in `bridge-django-render/build.sh` may need changes if your project structure differs significantly.
95 |
--------------------------------------------------------------------------------
/docs/index.md:
--------------------------------------------------------------------------------
1 | # Overview
2 |
3 | Automate your local and deployed infra in one line.
4 |
5 | 
6 |
7 |
8 | ## What is bridge?
9 | Bridge enables you to seamlessly run and deploy all the infrastructure you need for a complete Django project.
10 |
11 | - One line of copy-paste configuration
12 | - Local Postgres database automatically configured and connected
13 | - Local Redis and Celery instances automatically configured and connected
14 | - Easy one-command deploy configuration to Render
15 |
16 | [Get started](getting-started.md)
17 |
18 | [FAQ](faq.md)
19 |
--------------------------------------------------------------------------------
/docs/runserver_demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gauge-sh/bridge/8b34304e7db5ac888b26b4aebdb9102ea282f874/docs/runserver_demo.gif
--------------------------------------------------------------------------------
/docs/runserver_noreload_cat_bridge_yaml.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gauge-sh/bridge/8b34304e7db5ac888b26b4aebdb9102ea282f874/docs/runserver_noreload_cat_bridge_yaml.gif
--------------------------------------------------------------------------------
/mkdocs.yml:
--------------------------------------------------------------------------------
1 | # yaml-language-server: $schema=https://squidfunk.github.io/mkdocs-material/schema.json
2 | site_name: Bridge
3 | site_url: https://never-over.github.io/bridge/
4 | repo_name: bridge
5 | repo_url: https://github.com/Never-Over/bridge
6 | nav:
7 | - index.md
8 | - getting-started.md
9 | - faq.md
10 | theme:
11 | palette:
12 |
13 | # Palette toggle for automatic mode
14 | - media: "(prefers-color-scheme)"
15 | toggle:
16 | icon: material/brightness-auto
17 | name: Switch to light mode
18 |
19 | # Palette toggle for light mode
20 | - media: "(prefers-color-scheme: light)"
21 | scheme: default
22 | toggle:
23 | icon: material/brightness-7
24 | name: Switch to dark mode
25 |
26 | # Palette toggle for dark mode
27 | - media: "(prefers-color-scheme: dark)"
28 | scheme: slate
29 | toggle:
30 | icon: material/brightness-4
31 | name: Switch to system preference
32 | name: material
33 | favicon: favicon.ico
34 | icon:
35 | logo: fontawesome/solid/shield-halved
36 | repo: fontawesome/brands/git-alt
37 | features:
38 | - navigation.instant
39 | - navigation.instant.progress
40 | - navigation.sections
41 | - navigation.tracking
42 | - toc.follow
43 | markdown_extensions:
44 | - pymdownx.highlight:
45 | anchor_linenums: true
46 | line_spans: __span
47 | pygments_lang_class: true
48 | - pymdownx.inlinehilite
49 | - pymdownx.snippets
50 | - pymdownx.superfences
51 | - pymdownx.details
52 | - admonition
53 | extra:
54 | social:
55 | - icon: fontawesome/solid/envelope
56 | link: mailto:admin@0x63problems.dev
57 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [project]
2 | name = "python-bridge"
3 | version = "0.1.2"
4 | authors = [
5 | { name="Caelean Barnes", email="caeleanb@gmail.com" },
6 | { name="Evan Doyle", email="evanmdoyle@gmail.com" },
7 | ]
8 | description = "A Python tool to abstract your Django infrastructure."
9 | readme = "README.md"
10 | requires-python = ">=3.8"
11 | classifiers = [
12 | "Programming Language :: Python :: 3",
13 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
14 | "Operating System :: OS Independent",
15 | "Development Status :: 4 - Beta",
16 | "Intended Audience :: Developers",
17 | "Programming Language :: Python",
18 | "Programming Language :: Python :: 3.9",
19 | "Programming Language :: Python :: 3.10",
20 | "Programming Language :: Python :: 3.11",
21 | "Programming Language :: Python :: 3.12",
22 | "Programming Language :: Python :: 3 :: Only",
23 | "Topic :: Software Development :: Libraries :: Python Modules",
24 | ]
25 | keywords = ['python', 'deployment', 'local', 'infrastructure', 'postgres', 'django', 'architecture']
26 | dependencies = [
27 | "docker==7.0.0",
28 | "psycopg[binary]==3.1.18",
29 | "redis==5.0.3",
30 | "celery==5.3.6",
31 | "flower==2.0.1",
32 | "rich==13.7.1",
33 | "pydantic==2.6.4",
34 | "pyyaml==6.0.1",
35 | "dj-database-url==2.1.0",
36 | "psutil==5.9.8",
37 | ]
38 |
39 | [project.urls]
40 | Homepage = "https://github.com/never-over/bridge"
41 | Issues = "https://github.com/never-over/bridge/issues"
42 |
43 | [tool.pyright]
44 | include = ["bridge"]
45 | exclude = ["**/__pycache__", '**/.venv']
46 | reportMissingTypeStubs = false
47 |
48 | [build-system]
49 | requires = ["setuptools>=61.0"]
50 | build-backend = "setuptools.build_meta"
51 |
52 | [project.scripts]
53 | bridge = "bridge.cli.bridge:main"
54 |
--------------------------------------------------------------------------------
/ruff.toml:
--------------------------------------------------------------------------------
1 | extend-include = ["*.ipynb"]
2 |
3 | [lint]
4 | extend-select = [
5 | # pycodestyle
6 | "E",
7 | # Pyflakes
8 | "F",
9 | # pyupgrade
10 | "UP",
11 | # flake8-bugbear
12 | "B",
13 | # flake8-simplify
14 | "SIM",
15 | # isort
16 | "I",
17 | ]
18 |
19 | [format]
20 | docstring-code-format = true
21 |
22 |
23 | [lint.flake8-tidy-imports]
24 | # Disallow all relative imports.
25 | ban-relative-imports = "all"
26 |
27 | [lint.pycodestyle]
28 | max-line-length = 100
--------------------------------------------------------------------------------
/tach.yml:
--------------------------------------------------------------------------------
1 | constraints:
2 | bridge:
3 | depends_on:
4 | - bridge.framework
5 | bridge.cli:
6 | depends_on:
7 | - bridge
8 | - bridge.framework
9 | - bridge.service
10 | - bridge.utils
11 | bridge.framework:
12 | depends_on:
13 | - bridge.platform
14 | - bridge
15 | - bridge.service
16 | - bridge.utils
17 | bridge.platform:
18 | depends_on:
19 | - bridge.service
20 | - bridge
21 | bridge.service:
22 | depends_on:
23 | - bridge.platform
24 | - bridge
25 | - bridge.utils
26 | bridge.utils:
27 | depends_on:
28 | - bridge
29 | exclude:
30 | - tests
31 | - docs
32 | exclude_hidden_paths: true
33 |
--------------------------------------------------------------------------------
/tests/configuration/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gauge-sh/bridge/8b34304e7db5ac888b26b4aebdb9102ea282f874/tests/configuration/__init__.py
--------------------------------------------------------------------------------
/tests/configuration/test_django_local.py:
--------------------------------------------------------------------------------
1 | import builtins
2 |
3 | import pytest
4 |
5 | from bridge.config import BridgeConfig
6 | from bridge.framework.django import DjangoHandler
7 | from bridge.platform import Platform
8 |
9 |
10 | @pytest.fixture
11 | def django_settings():
12 | return {
13 | "ALLOWED_HOSTS": ["localhost"],
14 | "DATABASES": {
15 | "default": {
16 | "ENGINE": "django.db.backends.sqlite3",
17 | "NAME": "db.sqlite3",
18 | }
19 | },
20 | "STATIC_URL": "/static/",
21 | "DEBUG": True,
22 | "SECRET_KEY": "secret",
23 | }
24 |
25 |
26 | @pytest.fixture
27 | def django_handler(django_settings):
28 | bridge_config = BridgeConfig()
29 | return DjangoHandler(
30 | project_name="test",
31 | framework_locals=django_settings,
32 | bridge_config=bridge_config,
33 | )
34 |
35 |
36 | def was_module_imported(import_mock, module_name):
37 | """Check if the specified module was attempted to be imported."""
38 | return any(
39 | call_args[0][0] == module_name for call_args in import_mock.call_args_list
40 | )
41 |
42 |
43 | def test_configure_postgres(django_handler):
44 | django_handler.configure_postgres(platform=Platform.LOCAL)
45 | assert django_handler.framework_locals["DATABASES"] == {
46 | "default": {
47 | "ENGINE": "django.db.backends.postgresql",
48 | "NAME": "postgres",
49 | "USER": "postgres",
50 | "PASSWORD": "postgres",
51 | "HOST": "localhost",
52 | "PORT": 5432,
53 | }
54 | }
55 |
56 |
57 | def test_configure_worker(mocker, django_handler):
58 | mocked_django_celery_module = mocker.MagicMock()
59 | mocker.patch.dict(
60 | "sys.modules", {"bridge.service.django_celery": mocked_django_celery_module}
61 | )
62 | original_import = builtins.__import__
63 | mocked_import = mocker.MagicMock(side_effect=original_import)
64 | mocker.patch("builtins.__import__", mocked_import)
65 | django_handler.configure_worker(platform=Platform.LOCAL)
66 | assert was_module_imported(mocked_import, "bridge.service.django_celery")
67 | assert (
68 | django_handler.framework_locals["CELERY_BROKER_URL"]
69 | == "redis://localhost:6379/0"
70 | )
71 | assert (
72 | django_handler.framework_locals["CELERY_RESULT_BACKEND"]
73 | == "redis://localhost:6379/0"
74 | )
75 |
76 |
77 | def test_configure_allowed_hosts(django_handler):
78 | previous_allowed_hosts = django_handler.framework_locals["ALLOWED_HOSTS"].copy()
79 | django_handler.configure_allowed_hosts(platform=Platform.LOCAL)
80 | assert django_handler.framework_locals["ALLOWED_HOSTS"] == previous_allowed_hosts
81 |
82 |
83 | def test_configure_debug(django_handler):
84 | previous_debug = django_handler.framework_locals["DEBUG"]
85 | django_handler.configure_debug(platform=Platform.LOCAL)
86 | assert django_handler.framework_locals["DEBUG"] == previous_debug
87 |
88 |
89 | def test_configure_secret_key(mocker, django_handler):
90 | previous_secret_key = django_handler.framework_locals["SECRET_KEY"]
91 | django_handler.configure_secret_key(platform=Platform.LOCAL)
92 | assert django_handler.framework_locals["SECRET_KEY"] == previous_secret_key
93 |
94 |
95 | def test_configure_staticfiles(django_handler):
96 | previous_static_url = django_handler.framework_locals.get("STATIC_URL")
97 | previous_static_root = django_handler.framework_locals.get("STATIC_ROOT")
98 | previous_staticfiles_dirs = django_handler.framework_locals.get("STATICFILES_DIRS")
99 | previous_staticfiles_storage = django_handler.framework_locals.get(
100 | "STATICFILES_STORAGE"
101 | )
102 | django_handler.configure_staticfiles(platform=Platform.LOCAL)
103 | assert django_handler.framework_locals.get("STATIC_URL") == previous_static_url
104 | assert django_handler.framework_locals.get("STATIC_ROOT") == previous_static_root
105 | assert (
106 | django_handler.framework_locals.get("STATICFILES_DIRS")
107 | == previous_staticfiles_dirs
108 | )
109 | assert (
110 | django_handler.framework_locals.get("STATICFILES_STORAGE")
111 | == previous_staticfiles_storage
112 | )
113 |
114 |
115 | def test_configure_services(mocker, django_handler):
116 | mocked_configure_postgres = mocker.patch.object(
117 | django_handler, "configure_postgres", new=mocker.MagicMock()
118 | )
119 | mocked_configure_worker = mocker.patch.object(
120 | django_handler, "configure_worker", new=mocker.MagicMock()
121 | )
122 | django_handler.configure_services(platform=Platform.LOCAL)
123 | mocked_configure_postgres.assert_called_once_with(platform=Platform.LOCAL)
124 | mocked_configure_worker.assert_called_once_with(platform=Platform.LOCAL)
125 |
--------------------------------------------------------------------------------
/tests/configuration/test_django_render.py:
--------------------------------------------------------------------------------
1 | import builtins
2 |
3 | import pytest
4 |
5 | from bridge.config import BridgeConfig
6 | from bridge.framework.django import DjangoHandler
7 | from bridge.platform import Platform
8 |
9 |
10 | @pytest.fixture
11 | def render_env(mocker):
12 | mocker.patch(
13 | "os.environ",
14 | {
15 | "BRIDGE_PLATFORM": "render",
16 | "DATABASE_URL": "postgres://render:password@renderpg:5432/renderdb",
17 | "REDIS_URL": "redis://renderredis:6379/0",
18 | "CELERY_BROKER_URL": "redis://renderredis:6379/0",
19 | "CELERY_RESULT_BACKEND": "redis://renderredis:6379/0",
20 | "SECRET_KEY": "fakesecret",
21 | "WEB_CONCURRENCY": "4",
22 | "DEBUG": "False",
23 | },
24 | )
25 |
26 |
27 | @pytest.fixture
28 | def django_settings():
29 | return {
30 | "ALLOWED_HOSTS": ["localhost"],
31 | "DATABASES": {
32 | "default": {
33 | "ENGINE": "django.db.backends.sqlite3",
34 | "NAME": "db.sqlite3",
35 | }
36 | },
37 | "STATIC_URL": "/static/",
38 | "BASE_DIR": "test",
39 | "DEBUG": True,
40 | "SECRET_KEY": "secret",
41 | }
42 |
43 |
44 | @pytest.fixture
45 | def django_handler(django_settings):
46 | bridge_config = BridgeConfig()
47 | return DjangoHandler(
48 | project_name="test",
49 | framework_locals=django_settings,
50 | bridge_config=bridge_config,
51 | )
52 |
53 |
54 | def was_module_imported(import_mock, module_name):
55 | """Check if the specified module was attempted to be imported."""
56 | return any(
57 | call_args[0][0] == module_name for call_args in import_mock.call_args_list
58 | )
59 |
60 |
61 | def test_configure_postgres(render_env, django_handler):
62 | django_handler.configure_postgres(platform=Platform.RENDER)
63 | assert django_handler.framework_locals["DATABASES"] == {
64 | "default": {
65 | "ENGINE": "django.db.backends.postgresql",
66 | "NAME": "renderdb",
67 | "USER": "render",
68 | "PASSWORD": "password",
69 | "HOST": "renderpg",
70 | "PORT": 5432,
71 | }
72 | }
73 |
74 |
75 | def test_configure_worker(mocker, render_env, django_handler):
76 | mocked_django_celery_module = mocker.MagicMock()
77 | mocker.patch.dict(
78 | "sys.modules", {"bridge.service.django_celery": mocked_django_celery_module}
79 | )
80 | original_import = builtins.__import__
81 | mocked_import = mocker.MagicMock(side_effect=original_import)
82 | mocker.patch("builtins.__import__", mocked_import)
83 | django_handler.configure_worker(platform=Platform.RENDER)
84 | assert was_module_imported(mocked_import, "bridge.service.django_celery")
85 | assert (
86 | django_handler.framework_locals["CELERY_BROKER_URL"]
87 | == "redis://renderredis:6379/0"
88 | )
89 | assert (
90 | django_handler.framework_locals["CELERY_RESULT_BACKEND"]
91 | == "redis://renderredis:6379/0"
92 | )
93 |
94 |
95 | def test_configure_allowed_hosts(render_env, django_handler):
96 | django_handler.configure_allowed_hosts(platform=Platform.RENDER)
97 | assert set(django_handler.framework_locals["ALLOWED_HOSTS"]) == {
98 | ".onrender.com",
99 | "localhost",
100 | }
101 |
102 |
103 | def test_configure_debug(render_env, django_handler):
104 | django_handler.configure_debug(platform=Platform.RENDER)
105 | assert django_handler.framework_locals["DEBUG"] is False
106 |
107 |
108 | def test_configure_secret_key(render_env, django_handler):
109 | django_handler.configure_secret_key(platform=Platform.RENDER)
110 | assert django_handler.framework_locals["SECRET_KEY"] == "fakesecret"
111 |
112 |
113 | def test_configure_staticfiles(django_handler):
114 | django_handler.configure_staticfiles(platform=Platform.RENDER)
115 | assert django_handler.framework_locals.get("STATIC_URL") == "/static/"
116 | assert django_handler.framework_locals.get("STATIC_ROOT") == "test/staticfiles"
117 | assert (
118 | django_handler.framework_locals.get("STATICFILES_STORAGE")
119 | == "whitenoise.storage.CompressedManifestStaticFilesStorage"
120 | )
121 | assert (
122 | "whitenoise.middleware.WhiteNoiseMiddleware"
123 | in django_handler.framework_locals.get("MIDDLEWARE", [])
124 | )
125 |
126 |
127 | def test_configure_services(mocker, django_handler):
128 | mocked_configure_postgres = mocker.patch.object(
129 | django_handler, "configure_postgres", new=mocker.MagicMock()
130 | )
131 | mocked_configure_worker = mocker.patch.object(
132 | django_handler, "configure_worker", new=mocker.MagicMock()
133 | )
134 | django_handler.configure_services(platform=Platform.RENDER)
135 | mocked_configure_postgres.assert_called_once_with(platform=Platform.RENDER)
136 | mocked_configure_worker.assert_called_once_with(platform=Platform.RENDER)
137 |
--------------------------------------------------------------------------------
/tests/django/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gauge-sh/bridge/8b34304e7db5ac888b26b4aebdb9102ea282f874/tests/django/__init__.py
--------------------------------------------------------------------------------
/tests/django/django_bridge/README.md:
--------------------------------------------------------------------------------
1 | # Bridge Deployment
2 |
3 |
4 | [](https://render.com/deploy)
5 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/bridge-django-render/build-worker.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | # Exit on error
3 | set -o errexit
4 |
5 | # Modify this line as needed for your package manager (pip, poetry, etc.)
6 | pip install -r requirements.txt
7 |
8 | # Install additional dependencies
9 | pip install psycopg-binary
10 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/bridge-django-render/build.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | # Exit on error
3 | set -o errexit
4 |
5 | # Get the directory of the current script.
6 | DIR=$(dirname "$0")
7 |
8 | # Use our Python script to install dependencies
9 | INSTALL_DEPS_SCRIPT="$DIR/install_deps.py"
10 | python "$INSTALL_DEPS_SCRIPT"
11 |
12 | # Install additional dependencies
13 | pip install gunicorn uvicorn psycopg-binary whitenoise[brotli]
14 |
15 | # Collect static asset files
16 | python manage.py collectstatic --no-input
17 |
18 | # Apply any outstanding database migrations
19 | python manage.py migrate
20 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/bridge-django-render/install_deps.py:
--------------------------------------------------------------------------------
1 | # [Generated by Bridge]
2 | import os
3 | import subprocess
4 |
5 |
6 | def install_dependencies():
7 | # Check for requirements.txt and install using pip
8 | if os.path.exists("requirements.txt"):
9 | print("requirements.txt found. Installing dependencies...")
10 | subprocess.run(["pip", "install", "-r", "requirements.txt"], check=True)
11 |
12 | # Check for Pipfile.lock and install using Pipenv
13 | elif os.path.exists("Pipfile.lock"):
14 | print("Pipfile.lock found. Installing Pipenv and dependencies...")
15 | subprocess.run(["pip", "install", "pipx"], check=True)
16 | subprocess.run(["pipx", "install", "pipenv"], check=True)
17 | subprocess.run(["pipenv", "sync"], check=True)
18 |
19 | # Check for poetry.lock and install using Poetry
20 | elif os.path.exists("poetry.lock"):
21 | print("poetry.lock found. Installing Poetry and dependencies...")
22 | subprocess.run(["pip", "install", "pipx"], check=True)
23 | subprocess.run(["pipx", "install", "poetry"], check=True)
24 | subprocess.run(["poetry", "install"], check=True)
25 |
26 | else:
27 | print(
28 | "No dependency file found."
29 | "Please ensure your dependency file is in the current directory."
30 | )
31 |
32 |
33 | if __name__ == "__main__":
34 | install_dependencies()
35 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/bridge-django-render/start-worker.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | celery -A bridge.service.django_celery worker -l INFO --concurrency="${TASK_CONCURRENCY:-4}"
3 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/bridge-django-render/start.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | gunicorn django_bridge.custom_wsgi:application -w "${WEB_CONCURRENCY:-4}" -b 0.0.0.0:"$PORT"
3 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/bridge.yaml:
--------------------------------------------------------------------------------
1 | enable_postgres: true
2 | enable_worker: true
3 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/django_bridge/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gauge-sh/bridge/8b34304e7db5ac888b26b4aebdb9102ea282f874/tests/django/django_bridge/django_bridge/__init__.py
--------------------------------------------------------------------------------
/tests/django/django_bridge/django_bridge/custom_asgi.py:
--------------------------------------------------------------------------------
1 | """
2 | ASGI config for django_bridge project.
3 |
4 | It exposes the ASGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.asgi import get_asgi_application
13 |
14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_bridge.settings")
15 |
16 | application = get_asgi_application()
17 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/django_bridge/custom_wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for django_bridge project.
3 |
4 | It exposes the WSGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.wsgi import get_wsgi_application
13 |
14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_bridge.settings")
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/django_bridge/settings.py:
--------------------------------------------------------------------------------
1 | """
2 | Django settings for django_bridge project.
3 |
4 | Generated by 'django-admin startproject' using Django 5.0.3.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/5.0/topics/settings/
8 |
9 | For the full list of settings and their values, see
10 | https://docs.djangoproject.com/en/5.0/ref/settings/
11 | """
12 |
13 | from pathlib import Path
14 |
15 | # Build paths inside the project like this: BASE_DIR / 'subdir'.
16 | BASE_DIR = Path(__file__).resolve().parent.parent
17 |
18 | # Quick-start development settings - unsuitable for production
19 | # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
20 |
21 | # SECURITY WARNING: keep the secret key used in production secret!
22 | SECRET_KEY = "django-insecure-$4uazv5^y3^be14t2$w-t@r0k!mgp+vvqv424&2(z8zt5*e*b5"
23 |
24 | # SECURITY WARNING: don't run with debug turned on in production!
25 | DEBUG = True
26 |
27 | ALLOWED_HOSTS = []
28 |
29 | # Application definition
30 |
31 | INSTALLED_APPS = [
32 | "django.contrib.admin",
33 | "django.contrib.auth",
34 | "django.contrib.contenttypes",
35 | "django.contrib.sessions",
36 | "django.contrib.messages",
37 | "django.contrib.staticfiles",
38 | ]
39 |
40 | MIDDLEWARE = [
41 | "django.middleware.security.SecurityMiddleware",
42 | "django.contrib.sessions.middleware.SessionMiddleware",
43 | "django.middleware.common.CommonMiddleware",
44 | "django.middleware.csrf.CsrfViewMiddleware",
45 | "django.contrib.auth.middleware.AuthenticationMiddleware",
46 | "django.contrib.messages.middleware.MessageMiddleware",
47 | "django.middleware.clickjacking.XFrameOptionsMiddleware",
48 | ]
49 |
50 | ROOT_URLCONF = "django_bridge.urls"
51 |
52 | TEMPLATES = [
53 | {
54 | "BACKEND": "django.template.backends.django.DjangoTemplates",
55 | "DIRS": [],
56 | "APP_DIRS": True,
57 | "OPTIONS": {
58 | "context_processors": [
59 | "django.template.context_processors.debug",
60 | "django.template.context_processors.request",
61 | "django.contrib.auth.context_processors.auth",
62 | "django.contrib.messages.context_processors.messages",
63 | ],
64 | },
65 | },
66 | ]
67 |
68 | WSGI_APPLICATION = "django_bridge.custom_wsgi.application"
69 |
70 | # Database
71 | # https://docs.djangoproject.com/en/5.0/ref/settings/#databases
72 |
73 | # DATABASES = {
74 | # "default": {
75 | # "ENGINE": "django.db.backends.sqlite3",
76 | # "NAME": BASE_DIR / "db.sqlite3",
77 | # }
78 | # }
79 |
80 |
81 | # Password validation
82 | # https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators
83 |
84 | AUTH_PASSWORD_VALIDATORS = [
85 | {
86 | "NAME": "django.contrib.auth."
87 | "password_validation.UserAttributeSimilarityValidator",
88 | },
89 | {
90 | "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
91 | },
92 | {
93 | "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
94 | },
95 | {
96 | "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
97 | },
98 | ]
99 |
100 | # Internationalization
101 | # https://docs.djangoproject.com/en/5.0/topics/i18n/
102 |
103 | LANGUAGE_CODE = "en-us"
104 |
105 | TIME_ZONE = "UTC"
106 |
107 | USE_I18N = True
108 |
109 | USE_TZ = True
110 |
111 | # Static files (CSS, JavaScript, Images)
112 | # https://docs.djangoproject.com/en/5.0/howto/static-files/
113 |
114 | STATIC_URL = "static/"
115 |
116 |
117 | # Default primary key field type
118 | # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
119 |
120 | DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
121 |
122 |
123 | from bridge import django # noqa: E402
124 |
125 | django.configure(locals())
126 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/django_bridge/urls.py:
--------------------------------------------------------------------------------
1 | """
2 | URL configuration for django_bridge project.
3 |
4 | The `urlpatterns` list routes URLs to views. For more information please see:
5 | https://docs.djangoproject.com/en/5.0/topics/http/urls/
6 | Examples:
7 | Function views
8 | 1. Add an import: from my_app import views
9 | 2. Add a URL to urlpatterns: path('', views.home, name='home')
10 | Class-based views
11 | 1. Add an import: from other_app.views import Home
12 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
13 | Including another URLconf
14 | 1. Import the include() function: from django.urls import include, path
15 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
16 | """
17 |
18 | from django.contrib import admin
19 | from django.urls import path
20 | from polls.views import test_view
21 |
22 | urlpatterns = [path("evan/", admin.site.urls), path("test_view/", test_view)]
23 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Django's command-line utility for administrative tasks."""
3 |
4 | import os
5 | import sys
6 |
7 |
8 | def main():
9 | """Run administrative tasks."""
10 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_bridge.settings")
11 | try:
12 | from django.core.management import execute_from_command_line
13 | except ImportError as exc:
14 | raise ImportError(
15 | "Couldn't import Django. Are you sure it's installed and "
16 | "available on your PYTHONPATH environment variable? Did you "
17 | "forget to activate a virtual environment?"
18 | ) from exc
19 | execute_from_command_line(sys.argv)
20 |
21 |
22 | if __name__ == "__main__":
23 | main()
24 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/polls/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gauge-sh/bridge/8b34304e7db5ac888b26b4aebdb9102ea282f874/tests/django/django_bridge/polls/__init__.py
--------------------------------------------------------------------------------
/tests/django/django_bridge/polls/admin.py:
--------------------------------------------------------------------------------
1 | # Register your models here.
2 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/polls/apps.py:
--------------------------------------------------------------------------------
1 | from django.apps import AppConfig
2 |
3 |
4 | class PollsConfig(AppConfig):
5 | default_auto_field = "django.db.models.BigAutoField"
6 | name = "polls"
7 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/polls/migrations/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gauge-sh/bridge/8b34304e7db5ac888b26b4aebdb9102ea282f874/tests/django/django_bridge/polls/migrations/__init__.py
--------------------------------------------------------------------------------
/tests/django/django_bridge/polls/models.py:
--------------------------------------------------------------------------------
1 | # Create your models here.
2 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/polls/tasks.py:
--------------------------------------------------------------------------------
1 | import uuid
2 |
3 | from celery import shared_task
4 | from django.contrib.auth.models import User
5 |
6 |
7 | @shared_task
8 | def create_random_user():
9 | User.objects.create_user(username=str(uuid.uuid4()))
10 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/polls/tests.py:
--------------------------------------------------------------------------------
1 | # Create your tests here.
2 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/polls/views.py:
--------------------------------------------------------------------------------
1 | # Create your views here.
2 | from django.http.response import HttpResponse
3 |
4 | from polls.tasks import create_random_user
5 |
6 |
7 | def test_view(request):
8 | create_random_user.delay() # type: ignore
9 | return HttpResponse("Hello, world. You're at the polls index.")
10 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/render.yaml:
--------------------------------------------------------------------------------
1 | services:
2 | - type: web
3 | plan: starter
4 | runtime: python
5 | name: django_bridge
6 | buildCommand: ./bridge-django-render/build.sh
7 | startCommand: ./bridge-django-render/start.sh
8 | envVars:
9 | - key: BRIDGE_PLATFORM
10 | value: render
11 | - key: SECRET_KEY
12 | generateValue: true
13 | - key: WEB_CONCURRENCY
14 | value: 4
15 | - key: DEBUG
16 | value: "False"
17 | - key: DATABASE_URL
18 | fromDatabase:
19 | name: django_bridge-db
20 | property: connectionString
21 | - key: REDIS_URL
22 | fromService:
23 | name: django_bridge-redis
24 | type: redis
25 | property: connectionString
26 |
27 | - type: redis
28 | name: django_bridge-redis
29 | plan: free
30 | ipAllowList: []
31 | - type: worker
32 | name: django_bridge-worker
33 | runtime: python
34 | buildCommand: ./bridge-django-render/build-worker.sh
35 | startCommand: ./bridge-django-render/start-worker.sh
36 | envVars:
37 | - key: BRIDGE_PLATFORM
38 | value: render
39 | - key: DJANGO_SETTINGS_MODULE
40 | value: django_bridge.settings
41 | - key: SECRET_KEY
42 | generateValue: true
43 | - key: TASK_CONCURRENCY
44 | value: 4
45 | - key: DEBUG
46 | value: "False"
47 | - key: DATABASE_URL
48 | fromDatabase:
49 | name: django_bridge-db
50 | property: connectionString
51 | - key: REDIS_URL
52 | fromService:
53 | name: django_bridge-redis
54 | type: redis
55 | property: connectionString
56 |
57 |
58 | databases:
59 | - name: django_bridge-db
60 | plan: free
61 | databaseName: django_bridge_db
62 | user: django_bridge
63 |
--------------------------------------------------------------------------------
/tests/django/django_bridge/requirements.txt:
--------------------------------------------------------------------------------
1 | python-bridge
2 | django==5.0.3
3 |
--------------------------------------------------------------------------------