Web应用连接RDS实例报错:ValueError: invalid literal for int() with base 10: 'PORT'
Hey there, let's break down what's causing this error and how to fix it quickly.
The Root Cause
That error happens because SQLAlchemy (in .conda/envs/src/lib/python3.6/site-packages/sqlalchemy/engine/url.py line 60) is trying to convert the port value from your DATABASE_URL into an integer—but instead of getting a number like 3306, it's seeing the literal string 'PORT'. That's why the int() conversion fails.
What Went Wrong with Your Environment Variables
When you ran export DATABASE_URL=mysql+pymysql://USER:PASSWORD@HOST:PORT/DBNAME, you're hardcoding the string PORT (along with USER, HOST, etc.) into the URL, not referencing the environment variables you set later. Bash doesn't automatically replace those placeholders unless you use the $ prefix to tell it to pull the actual variable values.
Step-by-Step Fix
Verify your environment variables are set correctly
First, double-check that your individual variables have the right values by running these commands in your terminal:echo $USER echo $PASSWORD echo $HOST echo $PORT echo $DBNAMEMake sure each outputs the actual value for your RDS instance (e.g.,
3306for PORT, your RDS endpoint for HOST).Reconstruct the DATABASE_URL with proper variable references
Instead of hardcoding placeholders, use the$symbol to reference your existing environment variables when settingDATABASE_URL:export DATABASE_URL="mysql+pymysql://$USER:$PASSWORD@$HOST:$PORT/$DBNAME"The quotes are important here—they ensure bash replaces all the variables correctly without splitting on special characters.
Validate the final DATABASE_URL
Run this command to confirm the URL has all the actual values, not the placeholder strings:echo $DATABASE_URLYou should see something like
mysql+pymysql://myuser:mypassword@myhost.rds.amazonaws.com:3306/mydbname—noUSER,PORT, etc., strings left.Check your code's environment variable loading
If you're loading theDATABASE_URLin your Python code, make sure you're pulling it directly from the environment, e.g.:import os from sqlalchemy import create_engine database_url = os.environ.get("DATABASE_URL") engine = create_engine(database_url)Don't hardcode the URL with placeholders in your code—let the environment variable handle it.
Extra Tip for .env Files
If you're using a .env file (common with frameworks like Flask/Django), make sure your line looks like this (using curly braces to wrap variables for clarity):
DATABASE_URL="mysql+pymysql://${USER}:${PASSWORD}@${HOST}:${PORT}/${DBNAME}"
And ensure you're using a package like python-dotenv to load these variables into your environment before your app starts.
内容的提问来源于stack exchange,提问作者mlewis

