andremaytorena
PROOP
2 years ago
print(DATABASE_URL)
if DATABASE_URL:
print(DATABASE_URL)
DB_HOST = DATABASE_URL.split("@")[1].split(":")[0]
DB_PORT = DATABASE_URL.split("@")[1].split(":")[1].split("/")[0]
DB_NAME = DATABASE_URL.split("@")[1].split(":")[1].split("/")[1]
DB_USER = DATABASE_URL.split("://")[1].split(":")[0]
DB_PASS = DATABASE_URL.split("://")[1].split(":")[1].split("@")[0]
# Initialize connection pool
db_pool = pool.SimpleConnectionPool(
minconn=1, # Minimum number of connections in the pool
maxconn=10, # Maximum number of connections in the pool
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASS
)
def get_connection():
"""Get a connection from the pool."""
return db_pool.getconn()
def put_connection(conn):
"""Return a connection to the pool."""
db_pool.putconn(conn)```
I have a python API in a service, and a postgres database in another, I followed these instructions in the image to add the variable for the database url, but i get the error of key invalid when I try to grab it5 Replies
Ok I just realized I had to input it here, but the variable when printed still is empty

DB_PORT = os.environ['PG_PORT']
DB_NAME = os.environ['PG_NAME']
DB_USER = os.environ['PG_USER']
DB_PASS = os.environ['PG_PASSWORD']
# Initialize connection pool
db_pool = pool.SimpleConnectionPool(
minconn=1, # Minimum number of connections in the pool
maxconn=10, # Maximum number of connections in the pool
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASS
)```
i decided to just add the variables into the service, but I get this error when trying to connect to the postgres db:
conn = psycopg2.connect(*self._args, **self._kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/venv/lib/python3.11/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
psycopg2.OperationalError: could not translate host name "postgres.railway.internal" to address: Name or service not known```
Ohhh it's because it's in another project, I didn't realize they had to be in the same project