Search code examples
pythonroutesfasthtml

How to have separate route modules in FastHTML?


There is a similar question in How to separate flask routes to another modules but it is for Flask.

Basically I have this FastHTML python module, which references a lot more routes (here are only 2 routes included for sake of simplicity):

    from fasthtml import common as fh
    myHeaders = [
        fh.Meta(charset='UTF-8'),
        fh.Meta(name='viewport', content='width=device-width, initial-scale=1'),
        fh.Link(rel='stylesheet', href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css')
    ]

    # Creating FastAPI App
    app = fh.FastHTML(hdrs=myHeaders,secret_key=xmother.newId(25))

    # Mounting the static folder for accessing the menu.css
    app.mount("/static", StaticFiles(directory="static"), name="static")
    fh.serve()

    # Defining the routes.
    #=== I WANT TO SEPARATE THE FOLLOWING ROUTING CODE IN OTHER FILES=====

    ''' Execute the main view that is tree menu'''
    @app.get("/softprop/tree")
    def geto2(request:Request):
       request.session['id']=xmother.newId(10) #Sets the session id
       return getGeneralTreeViewCodeFH(menuDict=menuDict)

    '''Responds to the event of a field '''
    @app.get("/softprop/fieldEvent")
    def getFieldEvent(request:Request):
        return menu_params.getFieldEventDef(request)
    ''' More routes '''''
 

Can I split the routing code into several modules?


Solution

  • You can place the FastAPI App in a separate module so that it can be shared among several modules, including the main module.

    For example:

    app.py

    from fasthtml import common as fh
    
    myHeaders = [
        fh.Meta(charset='UTF-8'),
        fh.Meta(name='viewport', content='width=device-width, initial-scale=1'),
        fh.Link(rel='stylesheet', href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css')
    ]
    
    # Creating FastAPI App
    app = fh.FastHTML(hdrs=myHeaders,secret_key=xmother.newId(25))
    
    # Mounting the static folder for accessing the menu.css
    app.mount("/static", StaticFiles(directory="static"), name="static")
    

    routes/__init__.py

    from . import tree
    from . import field_event
    

    routes/tree.py

    from app import app
    
    ''' Execute the main view that is tree menu'''
    @app.get("/softprop/tree")
    def geto2(request:Request):
       request.session['id']=xmother.newId(10) #Sets the session id
       return getGeneralTreeViewCodeFH(menuDict=menuDict)
    

    routes/field_event.py

    from app import app
    
    '''Responds to the event of a field '''
    @app.get("/softprop/fieldEvent")
    def getFieldEvent(request:Request):
        return menu_params.getFieldEventDef(request)
    ''' More routes '''''
    

    main.py

    from app import fh
    import routes
    
    fh.serve()