Search code examples
pythonfalconframework

How to divide Python code to modules with shared code?


I'm using Falcon framework. I want that all standalone classes store in their own dirs( class that serve for /module1/ was inside dir /module1/):

/app
   ./app.py
    /modules
        /__init__.py
        /module1
            ...
        /module2
            ...
        ....

In app.py I have initialization of application:

import falcon
# falcon.API instances are callable WSGI apps
app=falcon.API()

My problems:

  1. how I must organize import of modules, that I can access from module2 to module1?
  2. How I can access to app variable of app.py from /module2:

I need do this code:

module2_mngr = Module2(CONFIG_FILE)
app.add_route('/module2', module2_mngr)

PS: Sorry for my English


Solution

  • Simple example where I can use different configuration based on api.debug.DEBUG flag:

    create some base path: /somepath/my_app/

    create the folder sturcture:

    /somepath/my_app/api

    /somepath/my_app/api/debug

    /somepath/my_app/conf

    /somepath/my_app/conf/prod

    /somepath/my_app/conf/dev

    create empty files:

    /somepath/my_app/__init__.py 
    /somepath/my_app/api/__init__.py
    /somepath/my_app/conf/prod/__init__.py
    /somepath/my_app/conf/dev/__init__.py
    

    Example main.py (/somepath/my_app/main.py):

    import api.debug
    api.debug.DEBUG = False
    import conf
    

    Setup api.debug.DEBUG == False

    /somepath/my_app/api/debug/__init__.py:
    
    DEBUG = False
    

    Create simple "router":

    • If api.debug.DEBUG is True - loads production configuration.
    • If api.debug.DEBUG is False - loads development configuration.

    So we create

    /somepath/my_app/conf/__init__.py:
    
    import api.debug
    if not api.debug.DEBUG:
        from conf.prod import *
    else:
        from conf.dev import *