Flask + psycopg2:插入时对象没有属性光标

时间:2018-06-25 13:02:42

标签: python postgresql cursor psycopg2

使用Flask(python 2.7.9)时出现一个奇怪的错误。在日志中:

cron_classes.py Message = ['DB connexion error!', 'Error SQL request: "'GestionBD' object has no attribute 'cursor'" : [INSERT INTO traitements (admin, date, timestamp, code_dept) VALUES (True, '2018-06-25', '2018-06-25 09:26', 84)]']

我已经启动了python的命令行,并且这样做:

$ python
Python 2.7.9 (default, Jun 29 2016, 13:08:31)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import psycopg2
>>> conn = psycopg2.connect("host=localhost dbname=xxx password=xxx user=xxx")
>>> cur=conn.cursor()
>>> cur.execute("select * from departements")
>>> cur.fetchall()

.. some datas

>>> cur.execute("INSERT INTO traitements (admin, date, timestamp, code_dept) VALUES (True, '2018-06-25', '2018-06-25 14:50', 84)")

>>> conn.commit()

>>> cur.execute("select * from traitements order by date desc limit 1")

>>> cur.fetchall()
[(1236, True, datetime.date(2018, 6, 25), datetime.datetime(2018, 6, 25, 14, 50), 84)]

正在工作!

那么,为什么在python的代码中出现错误?

def recordTreatment(self):

    self.connectDB()

    now = datetime.now()

    # enregistrement de l'operation
    request = "INSERT INTO traitements (admin, date, timestamp, code_dept) VALUES (%s, '%s', '%s', %s)" % (self.config.MANAGER.get('admin'), self.demain.date(), now.strftime('%Y-%m-%d %H:%M'), self.config.MANAGER.get('code_dept'))

    logging.info("insertTreatment request = %s" % (request,))

    if not self.db.executeReq(request):
        self.exit('critical', self.db.messerr)

将数据插入数据库。

class GestionBD(object):

    def __init__(self, dbname='massifs', user='postgres', passwd='postgres'):

        self.params     = "dbname=%s user=%s password=%s" % (dbname, user, passwd)
        self.messerr    = None

        try:
            self.conne = psycopg2.connect(self.params) 

        except psycopg2.OperationalError as err:
            self.messerr = 'Erreur connexion: %s' % (err, ) 
            self.echec = 1

        else:
            self.cursor = self.conne.cursor() 
            self.echec = 0

有人有主意吗?

更新#1: 如果我尝试使用与Flask相同的用户导入psycopg2(在根目录下,它可以正常工作),那么我会遇到一个非常奇怪的错误:

~/the-website $ python
Python 2.7.9 (default, Jun 29 2016, 13:08:31)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import psycopg2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/users/the-same-user/.local/lib/python2.7/site-packages/psycopg2/__init__.py", line 50, in <module>
    from psycopg2._psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: /home/users/the-same-user/.local/lib/python2.7/site-packages/psycopg2/_psycopg.so: ELF file OS ABI invalid
>>> quit()

谢谢

F。

0 个答案:

没有答案