【发布时间】:2017-11-25 20:55:59
【问题描述】:
这是我的电报机器人的简化代码
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 项目,我不知道有一种(更好的,或至少可行的)方法来实现这一点。
为什么main() 中的row 被打印,而regcheck() 中的dbmgr.query 却卡住了?
【问题讨论】:
-
尝试在
def regcheck的开头添加global dbmgr -
在一个线程中创建的SQLite对象只能在同一个线程中使用。
-
@BartVanLoon 那么我们如何将 sqlite 添加到主线程?你知道吗?谢谢。
-
不是我的想法,抱歉。我使用简单的 CSV 文件作为我的 python-telegram-bots 的数据存储后端。对于简单的用例,这对我来说就像
sqlite一样可行。
标签: python python-2.7 sqlite telegram python-telegram-bot