当前位置: 首页>>代码示例>>Python>>正文


Python Base.update方法代码示例

本文整理汇总了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)
开发者ID:aragornis,项目名称:currency-converter,代码行数:38,代码来源:rates.py

示例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")
开发者ID:noisemaster,项目名称:AdamTestBot,代码行数:40,代码来源:utils.py

示例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")
开发者ID:agincel,项目名称:AdamTestBot,代码行数:40,代码来源:utils.py

示例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)
#.........这里部分代码省略.........
开发者ID:magomez96,项目名称:AdamTestBot,代码行数:103,代码来源:atbCommunity.py

示例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
开发者ID:lazywhite,项目名称:python,代码行数:32,代码来源:pydblite_t.py

示例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()
#.........这里部分代码省略.........
开发者ID:noisemaster,项目名称:AdamTestBot,代码行数:103,代码来源:atbCommunity.py

示例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()
开发者ID:agincel,项目名称:AdamTestBot,代码行数:72,代码来源:atbLikesDB.py


注:本文中的pydblite.Base.update方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。