Objects you can pass from the browser to the server – and back!

The biggest strength of Anvil is that you can build your whole web app in Python. You’re using the same language in the browser as on the server, and you can even share code between the two.

Today, we’re making Anvil even more powerful, by allowing you to define your own classes and pass them between client and server code.

How does it work?

Just create a Module – that’s Python code that’s available both in the browser and on the server. We’ll call it Vegetables. Then we can define a class there, and decorate it with @anvil.server.portable_class:

class Potato:
  def __init__(self, weight, temperature):
    self.weight = weight
    self.temperature = temperature

  def __repr__(self):
    return f"<Potato: {self.weight:.0f} grams, {self.temperature}°C>"

That’s it! Now you can pass instances of Potato into server-side functions, or return them back to the browser. Here’s some code for a server module:

from .Vegetables import Potato
import random

def get_potato(hot=True):
  return Potato(weight = random.uniform(140, 225),
                temperature = 80 if hot else 25)

def heat_up(potato):
  potato.temperature = 90
  return potato

And now you can call those functions from the browser!

    cold_potato = anvil.server.call('get_potato', hot=False)

    hot_potato = anvil.server.call('heat_up', cold_potato)

And sure enough, that prints:

<Potato: 168 grams, 25 degrees C>
<Potato: 168 grams, 90 degrees C>

We’ve made a class that you can pass from client to server code, and back, with just a Python function call. Simple!

You can open this example in the Anvil editor:

What else can I do?

That’s just scratching the surface of what you can do with our new Portable Classes. You can control how your objects are transmitted, customise permissions, and more.

Check out our documentation for more information and examples:

Build your own app with Anvil

If you’re new here, welcome! Anvil is a platform for building full-stack web apps with nothing but Python. No need to wrestle with JS, HTML, CSS, Python, SQL and all their frameworks – just build it all in Python.

Want to build an app of your own? Get started with one of our tutorials: