【问题标题】:Raw Query with SQL function in SQLAlchemy/encode/databasesSQLAlchemy/encode/databases 中带有 SQL 函数的原始查询
【发布时间】:2022-01-13 08:11:56
【问题描述】:

我是 Python 和 FastAPI 的完全初学者。 我正在使用 FastAPI,并且我有一个表,其中要求使用PostgreSQLpgcrypto 模块加密用户的个人信息。 原始查询是这样的,可以在任何数据库客户端中执行,并且执行时不会出现任何错误

insert into customers (email, gender) values (pgm_sym_encrypt('hello@gmail.com', 'some_secret_key'), 'male')

如何使用 SQLAlchemy 核心或encode/databases 执行此查询? 这个我试过了

from sqlalchemy import func
query = f"""
    insert into customers (email, gender) values 
    (:email, :gender)
    """
await database.execute(query=query, values={'email': func.pgm_sys_encrypt('hello@gmail.com', 'secret_key'), 'gender': 'male'})

没有用。 我也试过了

query = f"""
    insert into customers (email, gender) values 
    (pgm_sys_encrypt('hello@gmail.com', 'secret_key'), :gender)
    """
await database.execute(query=query, values={'gender': 'male'})

这也不起作用。我不知道如何在原始查询中执行函数。请帮忙。我已经尝试了很多,但我现在对这个完全一无所知。提前感谢您的帮助。

【问题讨论】:

    标签: python sqlalchemy flask-sqlalchemy psycopg2 fastapi


    【解决方案1】:

    因为它是一个原始查询,您应该能够像在原始 SQL 中那样指定它,所以这应该可以工作:

    from sqlalchemy.sql import text
    query = """
        insert into customers (email, gender) values 
        (pgm_sys_encrypt(:email, :secret_key), :gender)
        """
    await database.execute(query=text(query), values={'email': 'hello@gmail.com', 'secret_key': 's3cr37', 'gender': 'male'})
    

    【讨论】:

    • 非常感谢。我也提出了相同的解决方案。不过还是谢谢你指出来。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2017-04-03
    • 2015-01-31
    • 2015-05-26
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    相关资源
    最近更新 更多