简体   繁体   English

如何在游标上覆盖psycopg2 tzinfo_factory

[英]How to override psycopg2 tzinfo_factory on cursors

So because of [reasons], I'm looking at overriding the tzinfo classes that are set by pyscopg2. 因此,由于[原因],我正在研究覆盖pyscopg2设置的tzinfo类。 I thought this would be a simple case of overriding tzinfo_factory on the cursor class. 认为这是在cursor类上覆盖tzinfo_factory的简单情况。 However, this doesn't seem to work. 但是,这似乎不起作用。

import psycopg2
from psycopg2.extensions import cursor
from psycopg2.tz import FixedOffsetTimezone

class MyFixedOffsetTimezone(FixedOffsetTimezone):
    pass

class MyCursorFactory(cursor):
    tzinfo_factory = MyFixedOffsetTimezone
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

conn = psycopg2.connect('', cursor_factory=MyCursorFactory)
cursor = conn.cursor()
cursor.execute("select now()")
results = cursor.fetchall()
print(results[0][0].tzinfo)
print(results[0][0].tzinfo.__class__)

Will still give you 仍然会给你

$ python3 example.py 
psycopg2.tz.FixedOffsetTimezone(offset=60, name=None)
<class 'psycopg2.tz.FixedOffsetTimezone'>

Is this a result of my fundamental misunderstanding of how the C implementation's members and the higher level python interact? 这是我对C实现的成员与更高级别的python如何交互的基本误解的结果吗? (or am I being a complete pleb?) versions: python 3.5.2 tested in psycopg2 2.6.2 and 2.7.1 (或者我是否是一个完整的平民?)版本:在psycopg2 2.6.22.7.1测试了python 3.5.2

I've trawled through the code, and it does seem to be referencing tzinfo_factory on the cursor (psycopg/typecast_datetime.c:typecast_PYDATETIME_cast line 140 @ 2.7.1) 我已经遍历了代码,它似乎tzinfo_factory在游标上引用了tzinfo_factory (psycopg / typecast_datetime.c:typecast_PYDATETIME_cast行140 @ 2.7.1)

tzinfo_factory = ((cursorObject *)curs)->tzinfo_factory;

You have to pass the cursor_factory=... and assign MyFixedOffsetTimezone to MyCursorFactory: 您必须通过cursor_factory=...并将MyFixedOffsetTimezone分配给MyCursorFactory:

class MyFixedOffsetTimezone(FixedOffsetTimezone):
    pass

class MyCursorFactory(cursor):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.tzinfo_factory = MyFixedOffsetTimezone

conn = psycopg2.connect('...')
cursor = conn.cursor(cursor_factory=MyCursorFactory)
cursor.execute("select now()")
results = cursor.fetchall()
print(results[0][0].tzinfo)
print(results[0][0].tzinfo.__class__)

returns: 返回:

psycopg2.tz.FixedOffsetTimezone(offset=120, name=None)
<class '__main__.MyFixedOffsetTimezone'>

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

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