Report this

What is the reason for this report?

Connecting to managed PostgreSQL from functions using psycopg2

Posted on November 19, 2022
panu

By panu

Hi,

I just can’t wrap my head around this issue. Any time I try to connect to managed postgres from a function using psycopg2 the function times out.

2022-11-19T18:45:33.700648Z    stderr: The action did not initialize or run as expected.

The action exceeded its time limits of 15000 milliseconds.

Some facts:

  • Functions and databases are part of the same App
  • Database Trusted sources are off, it can be reached from anywhere
  • Function memory limit has been raised to 1024MB
  • Function timeout has been raised to 15000ms
  • It builds and deploys fine. I can import psycopg2 in code without errors.

Is there something missing? This should be the most basic usecase there is. Could you provide a good example/tutorial on this like you have with JS and MongoDB?

My project.yml:

packages:
  - name: sample
    environment:
      DATABASE_URL: <removed>
    functions:
      - name: hello
        runtime: python:default
        limits:
          timeout: 15000
          memory: 1024

My build.sh:

#!/bin/bash

set -e

virtualenv virtualenv
source virtualenv/bin/activate
pip install -r requirements.txt
deactivate

My requirements.txt:

psycopg2-binary==2.9.5

My __main__.py:

from urllib.parse import urlparse
import os
import psycopg2


def main(args):
    print("hello from hello")
    db_url = os.environ.get("DATABASE_URL")
    assert db_url is not None, "DATABASE_URL is missing!"
    print("db_url found")
    p = urlparse(db_url)
    print("parsed")
    conn = psycopg2.connect(
        dbname="name",
        user=p.username,
        password=p.password,
        port=p.port,
        host=p.hostname,
        sslmode="require",
    )
    print("connection created")
    conn.close()
    print("connection closed")
    return {"body": str(44)}

It runs fine if I remove database connection command from it. All the print statements work as expected. But if I have the connection statement there it does not even print anything. Running it locally works just fine.

from urllib.parse import urlparse
import os
import psycopg2


def main(args):
    print("hello from hello")
    db_url = os.environ.get("DATABASE_URL")
    assert db_url is not None, "DATABASE_URL is missing!"
    print("db_url found")
    p = urlparse(db_url)
    print("parsed")
    return {"body": str(44)}

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Start building today

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.