11

I faced very strange issue - my solution using sqlalchemy cannot connects to database. It depends on password I am using. for example, following records are working perfect:

PWD='123123123'
USR='test_user';
SQLALCHEMY_DATABASE_URI = 'mysql://{}:{}@localhost:3306/test_db'.format(USR, PWD)

#final result is 'mysql://test_user:123123123@localhost:3306/test_db'.format(USR, PWD)

But when I trying to put something serious to password (like '8yq+aB&k$V') connection failed. How to 'escape' or encode password somehow that sqlalchemy passed it to mysql succesfully?

Alex G.P.
  • 9,609
  • 6
  • 46
  • 81
  • What is the resultant string contained within SQLALCHEMY_DATABASE_URI? – Simon at The Access Group Jul 22 '13 at 12:06
  • @Simonatmso.net not quite sure that understood your question. Syntax of connection string for MySQL (SQLALCHEMY_DATABASE_URI) is known and described in sqlalchemy docs. I just trying to split informations. So, instead of first curly braces user will be substituted and password - instead of second one. – Alex G.P. Jul 22 '13 at 12:09
  • Anyway, updated code block. – Alex G.P. Jul 22 '13 at 12:10
  • That was what I was asking - with the more secure password does the resultant string end up as intended? (What does `print SQLALCHEMY_DATABASE_URI` output?). If that outputs as intended, then something SQLAlchemy is doing must be causing issues with one of the characters in your password (again making assumptions, I'd look at the `&` or `+`) – Simon at The Access Group Jul 22 '13 at 12:14
  • `mysql://test_user:8yq+aB&k$V@localhost:3306/test_db` - i checked it. I am also suspecting that matter is ampersand or something other non-aplhanumeric usage. But hoped that somebody faced the same problem. that is sad. – Alex G.P. Jul 22 '13 at 12:17
  • Have you tried the same password without the ampersand in? That would prove it decisively. Once you've narrowed down the problematic character(s) that in turn lets you narrow down your search (or just work around it) – Simon at The Access Group Jul 22 '13 at 12:18
  • It looks like problem related to `+` sign. I will check it later. – Alex G.P. Jul 22 '13 at 12:23

1 Answers1

17

This question/answer is perhaps a duplicate of this one so worth checking this first Writing a connection string when password contains special characters

According to the SQLAlchemy documentation

the string format of the URL is an RFC-1738-style string.

According to the RFC-1738 definition

If the character corresponding to an octet is
reserved in a scheme, the octet must be encoded.  The characters ";",
"/", "?", ":", "@", "=" and "&" are the characters which may be
 reserved for special meaning within a scheme.

To this end, I would assume that your password (and username for that matter) needs to be URL encoded to ensure any such characters are properly escaped. According to How to urlencode a querystring in Python? this can be done in python using urlencode()

Community
  • 1
  • 1