Skip to content
This repository

web.database should take a URL #171

Closed
aaronsw opened this Issue · 2 comments

2 participants

Aaron Swartz Zhang Huangbin
Aaron Swartz
Owner

This function will convert from a URL to the kind of dictionary it understands:

def dburl2dict(url):
    dbn, rest = url.split('://', 1)
    user, rest = rest.split(':', 1)
    pw, rest = rest.split('@', 1)
    host, rest = rest.split(':', 1)
    port, rest = rest.split('/', 1)
    db = rest
    return dict(dbn=dbn, user=user, pw=pw, db=db, host=host)
Zhang Huangbin

It doesn't work if password contains '@'. For example:

>>> dburl2dict('postgres://james:"pw_with_@"@serverfarm.example.net:5432/mygreatdb')
{'host': '"@serverfarm.example.net', 'pw': '"pw_with_', ...}

Both host and pw are incorrect.

My dirty patch to fix it and append port in dict:

diff --git a/web/db.py b/web/db.py
index a51fa7a..66b7cf1 100644
--- a/web/db.py
+++ b/web/db.py
@@ -1139,13 +1139,23 @@ def dburl2dict(url):
         {'user': 'james', 'host': 'serverfarm.example.net', 'db': 'mygreatdb', 'pw': 'day', 'dbn': 'postgres'}

     """
+    import re
     dbn, rest = url.split('://', 1)
     user, rest = rest.split(':', 1)
-    pw, rest = rest.split('@', 1)
+    user = re.sub("""['"]""", '', user)
+    if rest.startswith('"'):
+        pw, rest = rest.split('"', 2)[1:]
+        rest = rest.split('@', 1)[1]
+    elif rest.startswith("'"):
+        pw, rest = rest.split("'", 2)[1:]
+        rest = rest.split('@', 1)[1]
+    else:
+        pw, rest = rest.split('@', 1)
+
     host, rest = rest.split(':', 1)
     port, rest = rest.split('/', 1)
     db = rest
-    return dict(dbn=dbn, user=user, pw=pw, db=db, host=host)
+    return dict(dbn=dbn, user=user, pw=pw, db=db, host=host, port=port)

 _databases = {}
 def database(dburl=None, **params):
Aaron Swartz
Owner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.