python-telegram-bot中的Sqlite连接

时间:2017-11-25 20:55:59

标签: python python-2.7 sqlite telegram python-telegram-bot

这是我的电报机器人的简化代码

import telegram.bot, telegram, sqlite3
from telegram.ext import Updater,CommandHandler,MessageHandler,Filters

class DatabaseManager(object):
    def __init__(self, db):
        self.conn = sqlite3.connect(db)
        self.conn.execute('pragma foreign_keys = on')
        self.conn.commit()
        self.cur = self.conn.cursor()

    def query(self, arg):
        self.cur.execute(arg)
        self.conn.commit()
        return self.cur

    def __del__(self):
        self.conn.close()


def regcheck(uid):
    for row in dbmgr.query("SELECT * FROM users WHERE id="+str(uid)+";"):
        print "regcheck is running" #this is never printed
        if row == "":
            return 1
        else:
            return 0

def start(bot, update):
    if regcheck(update.message.chat_id) == 1:
        bot.send_message(chat_id=update.message.chat_id, text="OK")
    else:
        bot.send_message(chat_id=update.message.chat_id,text="FAIL")

def main():
    global dbmgr
    dbmgr = DatabaseManager("usr.sql")

    for row in dbmgr.query("select * from users WHERE id="+str(uid)+";"):
        print row #this works perfectly fine

    updater = Updater(token=token)
    dispatcher = updater.dispatcher

    start_handler = CommandHandler('start', start)
    dispatcher.add_handler(start_handler)

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

我理解,使用dbmgr的全局变量是次优的,但这是我的第一个python-telegram-bot项目,我不知道(更好,或者至少是工作)的方式要做到这一点。

为什么row中的main()会被打印,但dbmgr.query中的regcheck()会被卡住?

1 个答案:

答案 0 :(得分:0)

尝试更改SQLite连接的初始化:

self.conn = sqlite3.connect(db, check_same_thread=False)

在此处了解更多信息