SQLAlchemy ValueError for slash in password for cr

2019-08-31 14:44发布

问题:

Fairly simple-looking problem: my Python script is attempting to create a SQLAlchemy database connection. The password contains a forward slash:

engineString = 'postgresql://wberg:pass/word@localhost/mydatabase'
engine = sqlalchemy.create_engine(engineString)

But the second line raises:

ValueError: invalid literal for int() with base 10: 'pass'

Using a raw string (prepending with 'r') doesn't help. Is there some way to get SQLAlchemy to accept that password? My normal next step would be to try to construct the connection with subordinate methods, but I can't see another way of making a connection in the doc. Am I simply not allowed passwords with slashes here? I can accomodate this, but it seems unlikely that the toolkit could have gotten this far without that feature.

Versions: Python 2.6.6, SQLAlchemy 0.8.0

回答1:

Slashes aren't valid characters for URL component strings. You need to URL-encode the password portion of the connect string:

from urllib import quote_plus as urlquote
from sqlalchemy.engine import create_engine
engineString = 'postgresql://wberg:%s@localhost/mydatabase' % urlquote('pass/word')
engine = create_engine(engineString)