Accessing an external database

Because Anvil apps have a full Python instance in the back-end, you can use Python’s standard database packages to access an external database from your Server Modules.

You can even access private databases that are only reachable from your local network, by using the Uplink.

Contents

MySQL

You can use a MySQL driver such as Pymysql to control your MySQL database server, as you would in any Python environment.

Here’s an example of querying a MySQL database from an Anvil server function:

Python | Server
import pymysql

def connect():
  connection = pymysql.connect(host='db.example.com',
                               port=3306,
                               user='root',
                               password=anvil.secrets.get_secret('db_password'),
                               cursorclass=pymysql.cursors.DictCursor)
  return connection

@anvil.server.callable
def get_people():
  conn = connect()
  with conn.cursor() as cur:
    cur.execute("SELECT name,date_of_birth,score FROM users")
    return cur.fetchall()

And here’s how you’d use it in your Forms to display data with a Data Grid:

Python | Client
class Form1(Form1Template):

  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    super().__init__(**properties)

    # Any code you write here will run before the form opens.

    self.repeating_panel_1.items = anvil.server.call('get_people')

(Note 1: This example uses the App Secrets service to store your database password encrypted, rather than leaving it “in the clear” in your source code.)

(Note 2: This example uses DictCursor to return SELECT results as lists of dictionaries. This data format is easy to use with Anvil’s Data Grids.)

PostgreSQL

You can use a Postgres driver such as Psycopg2 from a Server Module to control your Postgres database, as you would in any Python environment.

Here’s example code to query a Postgres database from an Anvil server function:

Python | Server
import psycopg2
import psycopg2.extras

def connect():
  connection = psycopg2.connect(dbname='mydatabase',
                                host='db.example.com',
                                user='postgres',
                                password=anvil.secrets.get_secret('db_password'))
  return connection

@anvil.server.callable
def get_people():
  conn = connect()
  with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
    cur.execute("SELECT name,date_of_birth,score FROM users")
    return cur.fetchall()

And here’s how you’d use it in your Forms to display data with a Data Grid:

Python | Client
class Form1(Form1Template):

  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    super().__init__(**properties)

    # Any code you write here will run before the form opens.

    self.repeating_panel_1.items = anvil.server.call('get_people')

(Note 1: This example uses the App Secrets service to store your database password encrypted, rather than leaving it “in the clear” in your source code.)

(Note 2: This example uses RealDictCursor to return SELECT results as lists of dictionaries. This data format is easy to use with Anvil’s Data Grids.)

Accessing a Private Local Database

You can connect a database to your Anvil app, even if it’s not accessible over the Internet – for example, a database that’s on your machine, or only accessible from your network.

To do this, use the Uplink, which allows you to run a local Python process on your machine and connect it to Anvil. This means you define server functions that can access your local network, and call them from your Anvil app.

How it works

First, install the anvil-uplink package and enable the Uplink for your app. Then, write a Python script that defines @anvil.server.callable functions that query your, just as you would in server code. While your script is running, your app will be able to call those functions to access your database.

Here is an example Uplink script accessing a local Postgres database:

Python | Server
import anvil.server
import psycopg2
import psycopg2.extras

# Connect this script to your Anvil app
anvil.server.connect("[insert uplink key here]")

def connect():
  connection = psycopg2.connect(dbname='mydatabase',
                                host='localhost',
                                user='postgres',
                                password='mypassword')
  return connection

@anvil.server.callable
def get_people():
  conn = connect()
  with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
    cur.execute("SELECT name,date_of_birth,score FROM users")
    return cur.fetchall()

# Sleep forever so that this script remains
anvil.server.wait_forever()

Your Uplink program only exposes the functions it defines, so you can be confident that the only operations the app can perform on your database are the operations you chose to expose.

For more information, consult the Uplink documentation.


Do you still have questions?

Our Community Forum is full of helpful information and Anvil experts.