M
M
Maria2018-06-07 03:01:21
Python
Maria, 2018-06-07 03:01:21

How to connect to the database using *.ini configuration files?

Help, please, to understand.
I have a method for getting data from a db and it has a connection string:
connection_string = 'mysql://test:[email protected]/test_db'
e = create_engine(connection_string, echo=True)
How can I change the method to get the connection string from the configuration file (development.ini or some custom db.ini from the root folder)
The official documentation has an example:

the code
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession, Base

def main(global_config, **settings):
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine

    config = Configurator(settings=settings,
                          root_factory='tutorial.models.Root')
    config.include('pyramid_chameleon')
    config.add_route('wiki_view', '/')
    config.add_route('wikipage_add', '/add')
    config.add_route('wikipage_view', '/{uid}')
    config.add_route('wikipage_edit', '/{uid}/edit')
    config.add_static_view('deform_static', 'deform:static/')
    config.scan('.views')
    return config.make_wsgi_app()
def main(global_config, **settings):
    engine = engine_from_config(settings, 'sqlalchemy.')

The development.ini file contains this line
[app:main]
use = egg:tutorial
pyramid.reload_templates = true
pyramid.includes =
    pyramid_debugtoolbar
    pyramid_tm

sqlalchemy.url = sqlite:///%(here)s/sqltutorial.sqlite

and by the prefix "sqlalchemy." get the connection string.
But as I understand it, this setting will work only for the main method.
Please tell me how to implement this approach for any method using engine_from_config(), for example:
def save(request):
    data = request.json_body
    user_hash = sha1(json.dumps(data).encode('utf-8')).hexdigest()
    user = json.dumps(data.get("user"))
    settings = data.get("settings")
    s = orm.Session()
    try:
        connection_string = 'mysql://user_db:[email protected]/user_db'
        e = create_engine(connection_string, echo=True)
        meta = MetaData(bind=e, reflect=True)
        ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
ariezzz_python, 2018-07-17
@ariezzz_python

See here:
https://stackoverflow.com/questions/31764020/worki...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question