Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

python - Is it possible to pass a dictionary into create_engine function in SQLAlchemy?

I am trying to start a connection to an Azure SQL database. For security reasons I cannot hardcode in the username and password, I need to get it from a dictionary in a config file and put it into the connection URL that way.

When I try to do so and run it in a Jupyter notebook, the {key[value]} is not being replaced by what it refers to in the config file.

If I use a formatted string, I get a KeyError. If I do not use a formatted string, it simply prints the {variablename} literally.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot pass a dictionary straight into create_engine() as a substitute for the url, however you can pass a sqlalchemy.engine.url.URL object which can be instantiated easily with a dict.

From the docs:

This object is suitable to be passed directly to a create_engine() call.

For example:

from sqlalchemy.engine.url import URL

config = dict(
    drivername='driver',
    username='username',
    password='qwerty1',
    host='127.0.0.1',
    port='5000',
    database='mydb',
    query={'encoding': 'utf-8'}
)

url = URL(**config)

print(url)  # driver://username:qwerty1@127.0.0.1:5000/mydb?encoding=utf-8

engine = create_engine(URL, echo=True)

However, the issues you are having with passing in a string formatted URL aren't likely to be a SQLAlchemy problem as the string formatting would take place before create_engine() gets it's hands on the string. Unfortunately your question doesn't include an example that reproduces the exact problem you are having, so I cannot say much more than that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...