本文整理匯總了Python中pydblite.Base.update方法的典型用法代碼示例。如果您正苦於以下問題:Python Base.update方法的具體用法?Python Base.update怎麽用?Python Base.update使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pydblite.Base
的用法示例。
在下文中一共展示了Base.update方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: from pydblite import Base [as 別名]
# 或者: from pydblite.Base import update [as 別名]
class Rates:
""" Persistence layer for exchange rates. """
def __init__(self, filename, erase_db):
self.__db = Base(filename)
self.__db.create('currency', 'rate', mode="override" if erase_db else "open")
self.__db.create_index('currency')
def setRate(self, currency, rate):
""" Persist a currency's exchange rate. """
assert rate > 0.0
records = self.__db._currency[currency]
if len(records) > 0:
assert len(records) == 1 # We never expect several exchange rates for the same currency
self.__db.update(records[0], rate = rate)
else:
self.__db.insert(currency = currency, rate = rate)
self.__db.commit()
def getRate(self, currency):
""" Get the exchange rate with EUR for the provided currency or None if it is not found.
An exchange rate for currency CUR is Value(EUR) / Value(CUR): 1 EUR = rate(CUR) CUR <=> 1/rate(CUR) EUR = 1 CUR.
"""
records = self.__db._currency[currency]
return records[0]['rate'] if len(records) > 0 else None
def getAllRates(self):
""" Get all known exchange rates as a dict. """
return [(r['currency'], r['rate']) for r in self.__db]
def getRatesCount(self):
""" Get total number of exchange rates in db. """
return len(self.__db)
示例2: likeconvert
# 需要導入模塊: from pydblite import Base [as 別名]
# 或者: from pydblite.Base import update [as 別名]
def likeconvert(likesRoot):
histPath = likesRoot + '/history'
convertcsv2db(likesRoot + '/totals.csv', likesRoot + '/likes.pdl')
db = Base(likesRoot + '/likes.pdl')
db.open()
db.add_field('history', "")
db.add_field('liked', "")
dirContents = os.listdir(histPath)
histFiles = []
for File in dirContents:
if ".csv" in File:
histFiles.append(File)
for histFile in histFiles:
try:
csvfile = open(histPath + '/' + histFile, 'rb')
reader = csv.DictReader(csvfile)
for row in reader:
if histFile.endswith('history.csv'):
recName = histFile[:-11]
print(recName)
if db(userID=recName):
rec = db(userID=recName).pop()
if not rec['liked']:
db.update(rec, liked=row['liked'])
else:
tmpLiked = rec['liked']
tmpLiked += " " + row['liked']
db.update(rec, liked=tmpLiked)
if not rec['history']:
db.update(rec, history=row['messageID'])
else:
tmpHist = rec['history']
tmpHist += " " + row['messageID']
db.update(rec, history=tmpHist)
db.commit()
except csv.Error:
print("Could not open CSV file")
示例3: likeconvert
# 需要導入模塊: from pydblite import Base [as 別名]
# 或者: from pydblite.Base import update [as 別名]
def likeconvert(likesRoot):
histPath = likesRoot + "/history"
convertcsv2db(likesRoot + "/totals.csv", likesRoot + "/likes.pdl")
db = Base(likesRoot + "/likes.pdl")
db.open()
db.add_field("history", "")
db.add_field("liked", "")
dirContents = os.listdir(histPath)
histFiles = []
for File in dirContents:
if ".csv" in File:
histFiles.append(File)
for histFile in histFiles:
try:
csvfile = open(histPath + "/" + histFile, "rb")
reader = csv.DictReader(csvfile)
for row in reader:
if histFile.endswith("history.csv"):
recName = histFile[:-11]
print(recName)
if db(userID=recName):
rec = db(userID=recName).pop()
if not rec["liked"]:
db.update(rec, liked=row["liked"])
else:
tmpLiked = rec["liked"]
tmpLiked += " " + row["liked"]
db.update(rec, liked=tmpLiked)
if not rec["history"]:
db.update(rec, history=row["messageID"])
else:
tmpHist = rec["history"]
tmpHist += " " + row["messageID"]
db.update(rec, history=tmpHist)
db.commit()
except csv.Error:
print("Could not open CSV file")
示例4: process
# 需要導入模塊: from pydblite import Base [as 別名]
# 或者: from pydblite.Base import update [as 別名]
def process(bot, chat_id, parsedCommand, messageText, currentMessage, update, instanceAge):
def sendText(givenText, replyingMessageID=0, keyboardLayout=[]):
if not chatInstanceArray[chat_id]['adminDisable']:
atbSendFunctions.sendText(bot, chat_id, givenText, replyingMessageID, keyboardLayout)
def sendPhoto(imageName):
atbSendFunctions.sendPhoto(bot, chat_id, "images/"+ imageName)
def sendSticker(stickerName):
atbSendFunctions.sendSticker(bot, chat_id, "stickers/"+ stickerName)
def passSpamCheck():
return atbMiscFunctions.spamCheck(chat_id, currentMessage.date)
try:
chatInstanceArray[chat_id]['checking'] = True
except Exception:
chatInstanceArray[chat_id] = {'checking': True, 'adminDisable': False, 'spamTimestamp': 0, 'shottyTimestamp': 0, 'shottyWinner': "", 'checkingVehicles': False, 'whoArray': []}
try:
#commands go here, in this if-elif block. Python doesn't have switch statements.
if parsedCommand == "/mom": #sends "MOM GET THE CAMERA"
sendText("MOM GET THE CAMERA")
elif atbMiscFunctions.isMoom(parsedCommand): #sends M {random number of Os} M
if passSpamCheck(): #use this to prevent spamming of a command
response = "M"
for i in range(0, random.randint(3, 75)):
response += "O"
sendText(response + "M")
elif parsedCommand == "/swag":
sendText("swiggity swag, what\'s in the bag?")
elif parsedCommand == "/worms":
if passSpamCheck():
response = "hey man can I borrow your "
if len(messageText) > len("/worms "):
response += messageText[len("/worms "):]
else:
response += "worms"
sendText(response)
elif parsedCommand == "/shh" or parsedCommand == "/shhh":
if passSpamCheck():
sendPhoto("shhh.jpg")
elif parsedCommand == "/father":
if (random.randint(0, 1)):
sendText("You ARE the father!")
else:
sendText("You are NOT the father!")
elif parsedCommand == "/rip": #sends "I can't believe that [name (defaults to sender's name)] is fucking dead."
if passSpamCheck():
response = "I can't believe that "
if len(messageText) > len("/rip "):
if (messageText[len("/rip "):] == "me"):
response += currentMessage.from_user.first_name
else:
response += messageText[len("/rip "):]
else:
response += currentMessage.from_user.first_name
response += " is fucking dead."
sendText(response)
elif parsedCommand == "/scrub":
checkingStats = False
try:
if currentMessage.text.lower().split()[1] == "stats":
db = Base('chatStorage/scrub.pdl') #The path to the DB
db.create('username', 'name', 'counter', mode="open")
K = list()
for user in db:
K.append(user)
sortedK = sorted(K, key=lambda x: int(x['counter']), reverse=True)
outputString = "SCRUBBIEST LEADERBOARD:\n"
for user in sortedK:
pluralString = " SCRUB POINT"
if not(int(user['counter']) == 1):
pluralString += "S"
pluralString += "\n"
outputString += user['name'].upper() + ": " + str(user['counter']) + pluralString
sendText(outputString)
checkingStats = True
except IndexError:
pass
if not checkingStats and (currentMessage.from_user.id == 169883788 or currentMessage.from_user.id == 44961843):
db = Base('chatStorage/scrub.pdl')
db.create('username', 'name', 'counter', mode="open")
userWasFound = False
valueSuccessfullyChanged = False
for user in db:
if int(user['username']) == currentMessage.reply_to_message.from_user.id:
db.update(user, counter=int(user['counter']) + 1)
#.........這裏部分代碼省略.........
示例5: Base
# 需要導入模塊: from pydblite import Base [as 別名]
# 或者: from pydblite.Base import update [as 別名]
db = Base("test.db", save_to_file=False)
if db.exists():
db.open()
else:
db.create("name", "age")
db.insert("bob", 10)
index = db.insert(name="alice", age=20)
print db[index] # 按照主鍵訪問record
record = db[1]
db.update(record, name="dellian")
#db.delete(record)
# db.records (所有記錄)
# query
for r in db("age") > 10:
print r
for r in (db("age") > 5 ) & (db("name") == "bob"):
print r
print db.records
#db.commit() # flush to disk
示例6: process
# 需要導入模塊: from pydblite import Base [as 別名]
# 或者: from pydblite.Base import update [as 別名]
def process(bot, chat_id, parsedCommand, messageText, currentMessage, update, instanceAge):
def sendText(givenText, replyingMessageID=0, keyboardLayout=[]):
if not chatInstanceArray[chat_id]['adminDisable']:
atbSendFunctions.sendText(bot, chat_id, givenText, replyingMessageID, keyboardLayout)
def sendPhoto(imageName):
atbSendFunctions.sendPhoto(bot, chat_id, "images/" + imageName)
def sendSticker(stickerName):
atbSendFunctions.sendSticker(bot, chat_id, "stickers/" + stickerName)
def sendAudio(audioName):
atbSendFunctions.sendAudio(bot, chat_id, "audio/" + audioName)
def sendVideo(videoName):
atbSendFunctions.sendVideo(bot, chat_id, "videos/" + videoName)
def passSpamCheck(timeDelay=15):
return atbMiscFunctions.spamCheck(chat_id, currentMessage.date, timeDelay)
try:
chatInstanceArray[chat_id]['checking'] = True
except Exception:
chatInstanceArray[chat_id] = {'checking': True, 'adminDisable': False, 'spamTimestamp': 0, 'shottyTimestamp': 0, 'shottyWinner': "", 'checkingVehicles': False, 'whoArray': []}
try:
#commands go here, in this if-elif block. Python doesn't have switch statements.
if parsedCommand == "/mom": #sends "MOM GET THE CAMERA"
sendText("MOM GET THE CAMERA")
elif atbMiscFunctions.isMoom(parsedCommand): #sends M {random number of Os} M
if passSpamCheck(): #use this to prevent spamming of a command
response = "M"
for i in range(0, random.randint(3, 75)):
response += "O"
sendText(response + "M")
elif parsedCommand == "/swag":
sendText("swiggity swag, what\'s in the bag?")
elif parsedCommand == "/worms":
if passSpamCheck():
response = "hey man can I borrow your "
if len(messageText) > len("/worms "):
response += messageText[len("/worms "):]
else:
response += "worms"
sendText(response)
elif parsedCommand == "/shh" or parsedCommand == "/shhh":
if passSpamCheck():
sendPhoto("shhh.jpg")
elif parsedCommand == "/father":
if (random.randint(0, 1)):
sendText("You ARE the father!")
else:
sendText("You are NOT the father!")
elif parsedCommand == "/rip": #sends "I can't believe that [name (defaults to sender's name)] is fucking dead."
if passSpamCheck():
response = "I can't believe that "
while "my " in messageText:
messageText = messageText.replace("my ", currentMessage.from_user.first_name + "\'s ", 1)
if len(messageText) > len("/rip "):
if messageText[len("/rip "):] == "me":
response += currentMessage.from_user.first_name
else:
response += messageText[len("/rip "):]
else:
response += currentMessage.from_user.first_name
response += " is fucking dead."
sendText(response)
elif parsedCommand == "/rips": #sends "I can't believe that [name (defaults to sender's name)] is fucking dead."
if passSpamCheck():
response = "I can't believe that "
while "my " in messageText:
messageText = messageText.replace("my ", currentMessage.from_user.first_name + "\'s ", 1)
if len(messageText) > len("/rip "):
if messageText[len("/rip "):] == "me":
response += currentMessage.from_user.first_name
else:
response += messageText[len("/rip "):]
else:
response += currentMessage.from_user.first_name
response += " are fucking dead."
sendText(response)
elif parsedCommand == "/scrub":
checkingStats = False
try:
if currentMessage.text.lower().split()[1] == "stats":
db = Base('chatStorage/scrub.pdl') #The path to the DB
db.create('username', 'name', 'counter', mode="open")
K = list()
#.........這裏部分代碼省略.........
示例7: handleLikes
# 需要導入模塊: from pydblite import Base [as 別名]
# 或者: from pydblite.Base import update [as 別名]
def handleLikes(isLiking, currentMessage):
try:
db = Base('chatStorage/likes/likes.pdl') #The path to the database
db.create('userID', 'likes', 'dislikes', 'history', 'liked', mode="open") # Create a new DB if one doesn't exist. If it does, open it
#get disliked comment ID
likedID = currentMessage.reply_to_message.message_id
likeReceivedID = currentMessage.reply_to_message.from_user.id
#check if likedID is in user's liked history
passedCheck = True
isLikingSelf = int(likeReceivedID) == int(currentMessage.from_user.id)
if isLikingSelf:
passedCheck = False
if passedCheck:
if db(userID=currentMessage.from_user.id):
liker = db(userID=currentMessage.from_user.id).pop()
else:
liker = ""
if db(userID=likeReceivedID):
liked = db(userID=likeReceivedID).pop()
else:
liked = ""
if liker and likedID not in liker['history'] and liked:
hist = liker['history']
hist += " " + likedID
db.update(liker, history=hist)
lik = liker['liked']
tmpLikes = liked['likes']
tmpDis = liked['dislikes']
if isLiking:
tmpLikes = int(tmpLikes) + 1
db.update(liked, likes=tmpLikes)
lik += " " + "t"
else:
tmpDis = int(tmpDis) + 1
db.update(liked, dislikes=tmpDis)
lik += " " + "f"
db.update(liker, liked=lik)
elif liker and not liked:
hist = liker['history']
hist += " " + likedID
db.update(liker, history=hist)
lik = liker['liked']
if isLiking:
db.insert(likeReceivedID, 1, 0, "", "")
lik += " " + "t"
else:
db.insert(likeReceivedID, 0, 1, "", "")
lik += " " + "f"
db.update(liker, liked=lik)
elif not liker and liked:
if isLiking:
tmpLikes = liked['likes']
db.insert(currentMessage.from_user.id, 0, 0, likedID, 't')
tmpLikes = int(tmpLikes) + 1
db.update(liked, likes=tmpLikes)
else:
tmpDis = liked['dislikes']
db.insert(currentMessage.from_user.id, 0, 0, likedID, 'f')
tmpDis = int(tmpDis) + 1
db.update(liked, dislikes=tmpDis)
elif not liker and not liked:
if isLiking:
db.insert(currentMessage.from_user.id, 0, 0, likedID, 't')
db.insert(likeReceivedID, 1, 0, "", "")
else:
db.insert(currentMessage.from_user.id, 0, 0, likedID, 'f')
db.insert(likeReceivedID, 0, 1, "", "")
db.commit()
except Exception:
print traceback.format_exc()