[Python] Function in Digital Ocean Returning Errors Cannot Import Module and Cannot Connect to...

Discussão em 'Python' iniciado por Stack, Junho 7, 2025.

  1. Stack

    Stack Membro Participativo

    I have a simple Python function I've deployed as a Digital Ocean Function. However, the Function errors out on importing psycopg2.

    The function:

    import os
    import psycopg2

    def get_db_connection():
    connection = psycopg2.connect(
    host=os.environ.get("DB_HOST"),
    port=os.environ.get("DB_PORT"),
    dbname=os.environ.get("DB_NAME"),
    user=os.environ.get("DB_USER"),
    password=os.environ.get("DB_PASSWORD"),
    )
    return connection

    def main(args):
    try:
    version = psycopg2.__version__
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT version();")
    db_version = cursor.fetchone()
    cursor.close()
    conn.close()

    return {
    "body": {
    "message": f"Successfully imported dependencies and found DB version {db_version}.",
    "psycopg2_version": version
    }
    }
    except Exception as e:
    return {
    "body": {
    "error": f"{str(e)}"
    },
    "statusCode": 500
    }

    if __name__ == "__main__":
    main([])


    The file structure of the function seems fine, because doctl is deploying it and Digital Ocean is successfully building it and running it. The problem is the import.

    Project.yml:

    packages:
    - name: test-functions
    actions:
    - name: tester
    runtime: 'python:default'



    requirements.txt:

    psycopg2==2.9.10


    build.sh:

    #!/bin/bash

    set -e

    virtualenv --without-pip virtualenv
    source virtualenv/bin/activate

    pip install -r requirements.txt --target virtualenv/lib/python_3.9/site-packages


    I use doctl to deploy the function to Digital Ocean (note: sls is short for serverless):

    $ doctl auth init -t <access token from DO App Platform dashboard>
    $ doctl sls namespace create --label "tests" --region "west"
    $ doctl sls connect
    $ doctl sls deploy tests


    Observing the logs:

    $ doctl sls activations logs --function test-functions/tester --follow


    Getting the response:

    $ doctl sls functions invoke test-functions/tester
    { "error": "could not import module..." }

    Continue reading...

Compartilhe esta Página