gpt4 book ai didi

python - sqlite3 set_authorizer 方法出现问题

转载 作者:行者123 更新时间:2023-12-01 05:56:53 24 4
gpt4 key购买 nike

我尝试使用 Connection.set_authorizer 方法仅允许使用连接对象进行某些数据库操作。 (文档为here)

我正在使用此代码来测试:

import sqlite3 as sqlite

def select_authorizer(sqltype, arg1, arg2, dbname):
print("Test")
return sqlite.SQLITE_OK #should allow all operations

conn = sqlite.connect(":memory:")
conn.execute("CREATE TABLE A (name integer PRIMARY KEY AUTOINCREMENT)")
conn.set_authorizer(select_authorizer)
conn.execute("SELECT * FROM A").fetchall() #should still work

这给了我一个sqlite3.DatabaseError: notauthorized,而没有打印出“Test”。我猜我可能设置了错误的授权者,而且它甚至没有调用它。 (尽管错误消息肯定没有传达这一点)但根据文档,此设置看起来是正确的。

编辑:将sqlite.SQLITE_OKAY更改为sqlite.SQLITE_OK,但由于该方法似乎根本没有被调用,毫不奇怪,这没有帮助。

最佳答案

授权者回调需要 5 个参数,但您的只接受四个:

The first argument to the callback signifies what kind of operation is to be authorized. The second and third argument will be arguments or None depending on the first argument. The 4th argument is the name of the database (“main”, “temp”, etc.) if applicable. The 5th argument is the name of the inner-most trigger or view that is responsible for the access attempt or None if this access attempt is directly from input SQL code.

因此,签名应该是:

def select_authorizer(sqltype, arg1, arg2, dbname, source):

通常,在测试这样的回调时,通过使用 *args 通配符参数可以使测试变得容易:

def select_authorizer(*args):
print(args)
return sqlite.SQLITE_OK

上面的回调打印出来:

(21, None, None, None, None)
(20, 'A', 'name', 'main', None)

当我运行你的测试时SELECT

请参阅C reference for SQLite set_authorizeraction codes reference对于使用的各种常量。

关于python - sqlite3 set_authorizer 方法出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12067902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com