• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python db.getSession函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中yokadi.core.db.getSession函数的典型用法代码示例。如果您正苦于以下问题:Python getSession函数的具体用法?Python getSession怎么用?Python getSession使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了getSession函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: do_a_edit_command

    def do_a_edit_command(self, line):
        """Edit the command of an alias.
        a_edit_command <alias name>"""
        session = db.getSession()
        name = line
        if name not in self.aliases:
            raise YokadiException("There is no alias named {}".format(name))

        command = tui.editLine(self.aliases[name])

        session = db.getSession()
        db.Alias.setCommand(session, name, command)
        session.commit()
        self._updateAliasDict()
开发者ID:agateau,项目名称:yokadi,代码行数:14,代码来源:aliascmd.py


示例2: eventLoop

def eventLoop():
    """Main event loop"""
    delta = timedelta(hours=float(getConfigKey("ALARM_DELAY")))
    suspend = timedelta(hours=float(getConfigKey("ALARM_SUSPEND")))
    cmdDelayTemplate = getConfigKey("ALARM_DELAY_CMD")
    cmdDueTemplate = getConfigKey("ALARM_DUE_CMD")
    session = db.getSession()
    # For the two following dict, task id is key, and value is (duedate, triggerdate)
    triggeredDelayTasks = {}
    triggeredDueTasks = {}
    activeTaskFilter = [Task.status != "done",
                        Task.projectId == Project.id,
                        Project.active == True]  # noqa

    def process(now):
        delayTasks = session.query(Task).filter(Task.dueDate < now + delta,
                                                Task.dueDate > now,
                                                *activeTaskFilter)
        dueTasks = session.query(Task).filter(Task.dueDate < now,
                                              *activeTaskFilter)
        processTasks(delayTasks, triggeredDelayTasks, cmdDelayTemplate, suspend)
        processTasks(dueTasks, triggeredDueTasks, cmdDueTemplate, suspend)

    nextProcessTime = datetime.today().replace(microsecond=0)
    while event[0]:
        now = datetime.today().replace(microsecond=0)
        if now > nextProcessTime:
            process(now)
            nextProcessTime = now + timedelta(seconds=PROCESS_INTERVAL)
        time.sleep(EVENTLOOP_INTERVAL)
开发者ID:agateau,项目名称:yokadi,代码行数:30,代码来源:yokadid.py


示例3: run

    def run(self):
        filename = self.options.filename
        if not filename:
            filename = os.path.join(os.path.expandvars("$HOME"), ".yokadi.db")
            print("Using default database (%s)" % filename)

        db.connectDatabase(filename, createIfNeeded=False)
        session = db.getSession()

        # Basic tests :
        if not len(session.query(db.Config).all()) >=1:
            print("Your database seems broken or not initialised properly. Start yokadi command line tool to do it")
            sys.exit(1)

        # Start ical http handler
        if self.options.icalserver:
            yokadiIcalServer = YokadiIcalServer(self.options.tcpPort, self.options.tcpListen)
            yokadiIcalServer.start()

        # Start the main event Loop
        try:
            while event[1] != "SIGTERM":
                eventLoop()
                event[0] = True
        except KeyboardInterrupt:
            print("\nExiting...")
开发者ID:hswick,项目名称:yokadi,代码行数:26,代码来源:yokadid.py


示例4: do_p_edit

    def do_p_edit(self, line):
        """Edit a project.
        p_edit <project name>"""
        session = db.getSession()
        project = dbutils.getOrCreateProject(line, createIfNeeded=False)

        if not project:
            raise YokadiException("Project does not exist.")

        # Create project line
        projectLine = parseutils.createLine(project.name, "", project.getKeywordDict())

        # Edit
        line = tui.editLine(projectLine)

        # Update project
        projectName, garbage, keywordDict = parseutils.parseLine(line)
        if garbage:
            raise BadUsageException("Cannot parse line, got garbage (%s)" % garbage)
        if not dbutils.createMissingKeywords(list(keywordDict.keys())):
            return
        try:
            project.name = projectName
            project.setKeywordDict(keywordDict)
            session.merge(project)
            session.commit()
        except IntegrityError:
            session.rollback()
            raise YokadiException("A project named %s already exists. Please find another name" % projectName)
开发者ID:fabaff,项目名称:yokadi,代码行数:29,代码来源:projectcmd.py


示例5: end

    def end(self):
        today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
        # Adjust idColumn
        maxId = db.getSession().query(func.max(Task.id)).one()[0]
        self.idColumn.width = max(2, len(str(maxId)))

        # Adjust titleColumn
        self.titleColumn.width = self.maxTitleWidth
        totalWidth = sum([x.width for x in self.columns]) + len(self.columns)
        if totalWidth >= self.termWidth:
            self.titleColumn.width -= (totalWidth - self.termWidth) + len(self.columns)
        self.titleColumn.formater = TitleFormater(self.titleColumn.width, self.cryptoMgr)

        # Print table
        for sectionName, taskList in self.taskLists:
            dateSplitters = [(1, "day"), (7, "week"), (30, "month"), (30 * 4, "quarter"), (365, "year")]
            splitterRange, splitterName = dateSplitters.pop()
            splitterText = None
            self._renderTaskListHeader(sectionName)
            for task in taskList:
                while self.splitOnDate and task.creationDate > today - timedelta(splitterRange):
                    splitterText = "Last %s" % splitterName
                    if len(dateSplitters) > 0:
                        splitterRange, splitterName = dateSplitters.pop()
                    else:
                        self.splitOnDate = False

                if splitterText:
                    print(C.GREEN + splitterText.center(totalWidth) + C.RESET, file=self.out)
                    splitterText = None

                self._renderTaskListRow(task)
开发者ID:hswick,项目名称:yokadi,代码行数:32,代码来源:textlistrenderer.py


示例6: addTask

def addTask(projectName, title, keywordDict=None, interactive=True):
    """Adds a task based on title and keywordDict.
    @param projectName: name of project as a string
    @param title: task title as a string
    @param keywordDict: dictionary of keywords (name : value)
    @param interactive: Ask user before creating project (this is the default)
    @type interactive: Bool
    @returns : Task instance on success, None if cancelled."""
    session = db.getSession()
    if keywordDict is None:
        keywordDict = {}

    # Create missing keywords
    if not createMissingKeywords(keywordDict.keys(), interactive=interactive):
        return None

    # Create missing project
    project = getOrCreateProject(projectName, interactive=interactive)
    if not project:
        return None

    # Create task
    task = Task(creationDate=datetime.now().replace(second=0, microsecond=0), project=project, title=title,
                description="", status="new")
    session.add(task)
    task.setKeywordDict(keywordDict)
    session.merge(task)

    return task
开发者ID:agateau,项目名称:yokadi,代码行数:29,代码来源:dbutils.py


示例7: do_k_list

 def do_k_list(self, line):
     """List all keywords."""
     for name, taskIds in _listKeywords(db.getSession()):
         if taskIds:
             tasks = ", ".join([str(x) for x in taskIds])
         else:
             tasks = "none"
         print("{} (tasks: {})".format(name, tasks))
开发者ID:agateau,项目名称:yokadi,代码行数:8,代码来源:keywordcmd.py


示例8: getItemPropertiesStartingWith

def getItemPropertiesStartingWith(item, field, text):
    """Return a list of item.field starting with text
    @param item: the object item, example : Task, Project, Keyword...
    @param field: the item's field lookup : Project.q.name, Task.q.title, Keyword.q.name. Don't forget the magic q
    @param text: The begining of the text as a str
    @return: list of matching strings"""
    session = db.getSession()
    return [x.name for x in session.query(item).filter(field.like(str(text) + "%"))]
开发者ID:fabaff,项目名称:yokadi,代码行数:8,代码来源:completers.py


示例9: __init__

    def __init__(self, filterLine=None):
        self.name = ""  # Keyword name
        self.value = ""  # Keyword value
        self.negative = False  # Negative filter
        self.valueOperator = "="  # Operator to compare value
        self.session = db.getSession()

        if filterLine:
            self.parse(filterLine)
开发者ID:fabaff,项目名称:yokadi,代码行数:9,代码来源:parseutils.py


示例10: do_a_edit_name

    def do_a_edit_name(self, line):
        """Edit the name of an alias.
        a_edit_name <alias name>"""
        session = db.getSession()
        name = line
        if name not in self.aliases:
            raise YokadiException("There is no alias named {}".format(name))

        newName = tui.editLine(name)
        newName = parseOneWordName(newName)

        if newName in self.aliases:
            raise YokadiException("There is already an alias named {}.".format(newName))

        session = db.getSession()
        db.Alias.rename(session, name, newName)
        session.commit()
        self._updateAliasDict()
开发者ID:agateau,项目名称:yokadi,代码行数:18,代码来源:aliascmd.py


示例11: warnIfKeywordDoesNotExist

def warnIfKeywordDoesNotExist(keywordFilters):
    """Warn user is keyword does not exist
    @return: True if at least one keyword does not exist, else False"""
    session = db.getSession()
    doesNotExist = False
    for keyword in [k.name for k in keywordFilters]:
        if session.query(Keyword).filter(Keyword.name.like(keyword)).count() == 0:
            tui.error("Keyword %s is unknown." % keyword)
            doesNotExist = True
    return doesNotExist
开发者ID:agateau,项目名称:yokadi,代码行数:10,代码来源:parseutils.py


示例12: do_p_list

 def do_p_list(self, line):
     """List all projects."""
     session = db.getSession()
     for project in session.query(Project).all():
         if project.active:
             active = ""
         else:
             active = "(inactive)"
         taskCount = session.query(Task).filter_by(project=project).count()
         print("{:20} {:>4} {}".format(project.name, taskCount, active))
开发者ID:agateau,项目名称:yokadi,代码行数:10,代码来源:projectcmd.py


示例13: do_a_remove

 def do_a_remove(self, line):
     """Remove an alias"""
     if line in self.aliases:
         session = db.getSession()
         del self.aliases[line]
         alias = session.query(db.Alias).filter_by(name=line).one()
         session.delete(alias)
         session.commit()
     else:
         tui.error("No alias with that name. Use a_list to display all aliases")
开发者ID:agateau,项目名称:yokadi,代码行数:10,代码来源:aliascmd.py


示例14: taskIdCompleter

def taskIdCompleter(cmd, text, line, begidx, endidx):
    # TODO: filter on parameter position
    # TODO: potential performance issue with lots of tasks, find a better way to do it
    session = db.getSession()
    tasks = [x for x in session.query(Task).filter(Task.status != 'done') if str(x.id).startswith(text)]
    print()
    for task in tasks:
        # Move that in a renderer class ?
        print("%s: %s / %s" % (task.id, task.project.name, task.title))
    return [str(x.id) for x in tasks]
开发者ID:fabaff,项目名称:yokadi,代码行数:10,代码来源:completers.py


示例15: __init__

 def __init__(self):
     self.lastTaskId = None  # Last id created, used
     self.lastProjectName = None  # Last project name used
     self.lastTaskIds = []  # Last list of ids selected with t_list
     self.kFilters = []  # Permanent keyword filters (List of KeywordFilter)
     self.pFilter = ""  # Permanent project filter (name of project)
     self.session = db.getSession()
     for name in bugutils.PROPERTY_NAMES:
         dbutils.getOrCreateKeyword(name, interactive=False)
     dbutils.getOrCreateKeyword(NOTE_KEYWORD, interactive=False)
     self.session.commit()
开发者ID:fabaff,项目名称:yokadi,代码行数:11,代码来源:taskcmd.py


示例16: do_a_remove

 def do_a_remove(self, line):
     """Remove an alias"""
     if line in self.aliases:
         session = db.getSession()
         del self.aliases[line]
         aliases = session.query(db.Config).filter_by(name="ALIASES").one()
         aliases.value = str(repr(self.aliases))
         session.add(aliases)
         session.commit()
     else:
         tui.error("No alias with that name. Use a_list to display all aliases")
开发者ID:hswick,项目名称:yokadi,代码行数:11,代码来源:aliascmd.py


示例17: do_p_merge

    def do_p_merge(self, line):
        session = db.getSession()
        parser = self.parser_p_merge()
        args = parser.parse_args(line)

        src = getProjectFromName(args.source_project)
        dst = getProjectFromName(args.destination_project)
        if not args.force:
            if not tui.confirm("Merge project '{}' into '{}'".format(src.name, dst.name)):
                return
        dst.merge(session, src)
        print("Project '{}' merged into '{}'".format(src.name, dst.name))
开发者ID:agateau,项目名称:yokadi,代码行数:12,代码来源:projectcmd.py


示例18: do_c_get

 def do_c_get(self, line):
     parser = self.parser_c_get()
     args = parser.parse_args(line)
     key = args.key
     if not key:
         key = "%"
     session = db.getSession()
     k = session.query(Config).filter(Config.name.like(key)).filter_by(system=args.system).all()
     fields = [(x.name, "%s (%s)" % (x.value, x.desc)) for x in k]
     if fields:
         tui.renderFields(fields)
     else:
         raise YokadiException("Configuration key %s does not exist" % line)
开发者ID:hswick,项目名称:yokadi,代码行数:13,代码来源:confcmd.py


示例19: do_k_remove

    def do_k_remove(self, line):
        """Remove a keyword
        k_remove @<keyword>"""
        session = db.getSession()
        keyword = dbutils.getKeywordFromName(line)

        if keyword.tasks:
            print("The keyword %s is used by the following tasks: %s" % (keyword.name,
                                                                         ", ".join(str(task.id) for task in keyword.tasks)))
            if tui.confirm("Do you really want to remove this keyword"):
                session.delete(keyword)
                session.commit()
                print("Keyword %s has been removed" % keyword.name)
开发者ID:hswick,项目名称:yokadi,代码行数:13,代码来源:keywordcmd.py


示例20: do_k_edit

    def do_k_edit(self, line):
        """Edit a keyword
        k_edit @<keyword>"""
        session = db.getSession()
        keyword = dbutils.getKeywordFromName(line)
        oldName = keyword.name
        newName = tui.editLine(oldName)
        if newName == "":
            print("Cancelled")
            return

        lst = session.query(Keyword).filter_by(name=newName).all()
        if len(lst) == 0:
            # Simple case: newName does not exist, just rename the existing keyword
            keyword.name = newName
            session.merge(keyword)
            session.commit()
            print("Keyword %s has been renamed to %s" % (oldName, newName))
            return

        # We already have a keyword with this name, we need to merge
        print("Keyword %s already exists" % newName)
        if not tui.confirm("Do you want to merge %s and %s" % (oldName, newName)):
            return

        # Check we can merge
        conflictingTasks = []
        for task in keyword.tasks:
            kwDict = task.getKeywordDict()
            if oldName in kwDict and newName in kwDict and kwDict[oldName] != kwDict[newName]:
                conflictingTasks.append(task)

        if len(conflictingTasks) > 0:
            # We cannot merge
            tui.error("Cannot merge keywords %s and %s because they are both"
                      " used with different values in these tasks:" % (oldName, newName))
            for task in conflictingTasks:
                print("- %d, %s" % (task.id, task.title))
            print("Edit these tasks and try again")
            return

        # Merge
        for task in keyword.tasks:
            kwDict = task.getKeywordDict()
            if newName not in kwDict:
                kwDict[newName] = kwDict[oldName]
            del kwDict[oldName]
            task.setKeywordDict(kwDict)
        session.delete(keyword)
        session.commit()
        print("Keyword %s has been merged with %s" % (oldName, newName))
开发者ID:agateau,项目名称:yokadi,代码行数:51,代码来源:keywordcmd.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python dbutils.addTask函数代码示例发布时间:2022-05-26
下一篇:
Python ymero.ymero函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap