Live Chat

We'll need to share your messages (and your email address if you're logged in) with our live chat provider, Drift. Here's their privacy policy.

If you don't want to do this, you can email us instead at contact@anvil.works.

Quickstart: Server Code

Learn how to run code in Anvil’s hosted Python backend

Anvil provides a server-side Python environment for your apps.

Follow this quickstart to write a server function and call it from the client.

Create an app

Log in to Anvil and click ‘New Blank App’. Choose the Material Design theme.

Location of the Create App button

Add a Server Module

In the App Browser, click the + next to Server Modules to add a new Server Module.

Adding a Server Module in the App Browser

You will see a code editor with a yellow background.

Python code with a yellow background

Write a server function

Write this function into the Server Module:

def say_hello(name):
  print("Hello from the server " + name)
  return [1, 2, 3, 4]

Make your function client-callable

Above your say_hello function, add @anvil.server.callable. The function now looks like this:

@anvil.server.callable
def say_hello(name):
  print("Hello from the server " + name)
  return [1, 2, 3, 4]

That makes the say_hello function callable from the client side.

Switch to the Code View for Form1

Under Forms in the App Browser, select Form1.

App Browser showing where to find Form1

Click on the ‘Code’ tab to see the Python code for Form1.

The Design View for Form1 with the Code tab in the top-right highlighted

Call your server function from the client

You will see a few lines of pre-written code. Your Form is represented as a class called Form1. It currently has only one method, the __init__ method.

The Code View for Form1

At the end of the __init__ method, write these lines:

    return_value = anvil.server.call('say_hello', 'Anvil Developer')
    print("The return value was %s" % return_value)

Run your app

Now click the ‘Run’ button at the top of the screen.

Running your app in the editor

The Output Panel should display these lines:

The Output Panel showing printed messages with yellow and white backgrounds

The output with the yellow background came from a Python process running in Anvil’s cloud cluster. The output with the white background ran in your browser. You made the browser communicate with the server over the internet by writing anvil.server.call('say_hello', 'Anvil Developer').

Copy the example app

Click on the button below to clone a finished version of this app into your account.

Next up

Want more depth on this subject?

Read more about server-side code in Anvil.

Want another quickstart?

Every quickstart is on the Quickstarts page.