简体   繁体   English

是否可以将字典传递给 SQLAlchemy 中的 create_engine 函数?

[英]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.我正在尝试启动与 Azure SQL 数据库的连接。 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.出于安全原因,我无法对用户名和密码进行硬编码,我需要从配置文件中的字典中获取它,然后以这种方式将其放入连接 URL 中。

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.当我尝试这样做并在 Jupyter 笔记本中运行它时, {key[value]}没有被它在配置文件中引用的内容替换。

If I use a formatted string, I get a KeyError .如果我使用格式化的字符串,我会得到一个KeyError If I do not use a formatted string, it simply prints the {variablename} literally.如果我不使用格式化字符串,它只是按字面意思打印{variablename}

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 .您不能将字典直接传递给create_engine()作为 url 的替代品,但是您可以传递一个sqlalchemy.engine.url.URL对象,该对象可以使用dict轻松实例化。

From the docs :文档

This object is suitable to be passed directly to a create_engine() call.该对象适合直接传递给 create_engine() 调用。

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.但是,您在传递字符串格式的 URL 时遇到的问题不太可能是 SQLAlchemy 问题,因为字符串格式会在create_engine()获取字符串之前发生。 Unfortunately your question doesn't include an example that reproduces the exact problem you are having, so I cannot say much more than that.不幸的是,您的问题不包括重现您遇到的确切问题的示例,因此我不能说更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM