Search code examples
pythonfileflaskstructure

How to let Python execute script in each folder


I struggled with this question for 2 days and has no idea. I have 3 folders containing 3 individual python scripts each folder script run a function.

My question is how can I access them individually?

for only 1 folder, I create, say app.py with all routes inside. but how can I access 3 folder individually and can run individual function?

My file skeleton likes:

app.py (entrance)
|---departmentA
......|-------runme.py
......|-------templates
...........|-----index.html
|---departmentB
......|-------runme.py
......|-------templates
...........|-----index.html
|---departmentC
......|-------runme.py
......|-------templates
...........|-----index.html

Thanks Alex


Solution

  • File Structure:

    app.py
    /departmentA
        __init__.py
        routes.py
        runme.py
        /pages/departmentA
            index.html
    

    app.py

    from flask import Flask
    import departmentA
    
    skill_app = Flask(__name__)
    skill_app.register_blueprint(departmentA.bp)
    
    print(departmentA.my_func())
    
    skill_app.run()
    

    /departmentA/init.py

    from .routes import bp
    from .runme import my_func
    

    /departmentA/routes.py

    from flask import Blueprint, render_template
    from .runme import my_func
    
    bp = Blueprint('dept_A', __name__, template_folder='pages', url_prefix='/department_A')
    
    @bp.route('/')
    def index():
        print(my_func())
        return render_template('departmentA/index.html')
    

    /departmentA/runme.py

    def my_func():
        return "Hello World!"
    

    Use same format in other departments.