As the codebase grew, Batman wanted to have a way to organise the code. Robyn told him that he had the super power to organise the code in a better way. He told him about the concept of views and subrouters.

Views

To organise your code in a better way - either to group by responsibility or for code splitting, you can use views.

A view, simply is a function with a collection of other closures. e.g.

Request

GET
/hello_world
def sample_view():
  def get():
      return "Hello, world!"

  def post(request):
      body = request.body
      return Response({"status_code": 200, "description": body, "headers": {}})

The above view contains two closures for the get and the post request.

You can serve views in two ways:

Using an @app.view decorator.

Request

GET
/hello_world
@app.view("/sync/view/decorator")
def sync_decorator_view():
 def get():
     return "Hello, world!"

 def post(request):
     body = request.body
     return body

Using an @app.view decorator.

Request

GET
/hello_world
  from .views import sample_view

  ...
  ...

  app.add_view("/", sample_view)

Subrouters

Batman can create subrouters in Robyn. This is useful when you want to group routes together.

Subrouters can be used for both normal routes and web sockets. They are basically a mini version of the main router and can be used in the same way.

The only thing to remember is that you need to add the subrouter to the main router.

Request

GET
/hello_world
from robyn import Robyn, SubRouter

app = Robyn(__file__)

sub_router = SubRouter("/sub_router")

@sub_router.get("/hello")
def hello():
    return "Hello, world"

web_socket = SubRouter("/web_socket")

@web_socket.message()
async def hello():
    return "Hello, world"

app.include_router(sub_router)

What's next?

Now, that Batman knows how to organise his code, he wants to know how to add dependencies to his code. Robyn tells him that he can add dependencies at the global level, router level and the view level.