| 50 | |
| 51 | |
| 52 | def parse_database_url(url): |
| 53 | url = urlparse.urlparse(url) |
| 54 | |
| 55 | # Split query strings from path. |
| 56 | path = url.path[1:] |
| 57 | if "?" in path and not url.query: |
| 58 | path, query = path.split("?", 2) |
| 59 | else: |
| 60 | path, query = path, url.query |
| 61 | |
| 62 | # Handle postgres percent-encoded paths. |
| 63 | hostname = url.hostname or "" |
| 64 | if "%2f" in hostname.lower(): |
| 65 | # Switch to url.netloc to avoid lower cased paths |
| 66 | hostname = url.netloc |
| 67 | if "@" in hostname: |
| 68 | hostname = hostname.rsplit("@", 1)[1] |
| 69 | if ":" in hostname: |
| 70 | hostname = hostname.split(":", 1)[0] |
| 71 | hostname = hostname.replace("%2f", "/").replace("%2F", "/") |
| 72 | |
| 73 | config = { |
| 74 | "DB_DATABASE": urlparse.unquote(path) if path else None, |
| 75 | "DB_USER": urlparse.unquote(url.username) if url.username else None, |
| 76 | "DB_PASSWORD": urlparse.unquote(url.password) if url.password else None, |
| 77 | "DB_HOST": hostname, |
| 78 | "DB_PORT": url.port, |
| 79 | } |
| 80 | return {k: v for k, v in config.items() if v is not None} |