Skip to content

Create API to Starlette app #975

@horseinthesky

Description

@horseinthesky

Hello.
I couldn't find the answer may be because the question is not very specific.

I have a working Starlette app:

import datetime
import typesystem
import uvicorn

from starlette.applications import Starlette
from starlette.routing import Route, Mount
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates

from netbox_helper import NetboxInterface
from vlantoggler import Toggler

forms = typesystem.Jinja2Forms(package="bootstrap4")
templates = Jinja2Templates(directory="templates")
statics = StaticFiles(directory="statics", packages=["bootstrap4"])

togglings = []


class VTSchema(typesystem.Schema):
    tor = typesystem.String(title='ToR name', max_length=50)
    interface = typesystem.String(title='Interface name', max_length=15)
    state = typesystem.Choice(
        title='Desired state',
        choices=[
            ('prod', 'prod'),
            ('setup', 'setup'),
        ],
    )

    def __repr__(self):
        return f"Interface {self.interface} on {self.tor} was switched to {self.state.upper()} state at {self.toggle_time}"


def render(request, form=forms.Form(VTSchema), vl_status=None):
    context = {'request': request, 'form': form, 'togglings': togglings[-5:], 'vl_status': vl_status}
    return templates.TemplateResponse('index.html', context)


async def toggle(request):
    <do stuff>
    return render(request)


app = Starlette(
    debug=True,
    routes=[
        Route('/', toggle, methods=['GET', 'POST']),
        Mount('/statics', statics, name='static'),
    ],
)

if __name__ == "__main__":
    uvicorn.run(app, loop='uvloop', log_level='debug')

And want to add API to my app with the same functionality using FastAPI but I cannot get how to combine two app objects.
Could you provide some example pls?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions