R
R
Radiss2020-04-26 02:04:32
Python
Radiss, 2020-04-26 02:04:32

Access to the database via a link?

There are 2 databases - POSTGRESQL and SQLITE

How to write a function that takes a string
like postgres://admin:[email protected]:5432/my_db as input, and turns it into a
dictionary with fields.

That is, such a link is perceived as postgres://:@:
/
All values ​​are strings, the dictionary is single-level and this
is what matches the key, for example, 'default' in the DATABASES dictionary in the
django settings.

At the same time, if a string
like sqlite:///C:/Users/admin/site_db.sqlite3 comes to the input, then it will turn into another
dictionary:
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'C:/Users/admin/site_db.sqlite3'
}e lang="python">


That is, such a line will be perceived as sqlite:///

In this option, there should be fewer fields in the dictionary, another ENGINE should be used, and
the passed path to the database should be used as NAME.

The task is to write a function like parse_db_url which, for example, will
take one input argument: the actual path to the database. At the output, the function
should return a dictionary with different fields, depending on what was
passed to it.

def parse_db_url(db_link):
...


Example
parse_db_url("postgres://admin:[email protected]:5432/my_db")

{
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'USER': 'admin',
'PASSWORD': 'oocooSh7',
'HOST': 'postgres.host',
'PORT': '5432',
'NAME': 'my_db'
}


Example
parse_db_url("sqlite:///C:/Users/admin/site_db.sqlite3")

{
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'C:/Users/admin/site_db.sqlite3'
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2020-04-26
@radiss

>>> from urllib.parse import urlparse
>>> u = urlparse("postgres://admin:[email protected]:5432/my_db")
>>> u.password
'oocooSh7'
>>> u.username
'admin'
>>> u.hostname
'postgres.host'
>>> u.port
5432
>>> u.path
'/my_db'
>>> us = urlparse("sqlite:///C:/Users/admin/site_db.sqlite3")
>>> us.path
'/C:/Users/admin/site_db.sqlite3'
>>> us.scheme
'sqlite'
>>>

I think you can handle it yourself.

G
galaxy, 2020-04-26
@galaxy

What's the problem with parsing a string?
You want a regular expression, but here str.split() will do the trick.
True, it will be interesting if punctuation is allowed in the password ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question