Answer the question
In order to leave comments, you need to log in
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):
...
{
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'USER': 'admin',
'PASSWORD': 'oocooSh7',
'HOST': 'postgres.host',
'PORT': '5432',
'NAME': 'my_db'
}
{
'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
>>> 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'
>>>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question