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

Python tools.exitErr函数代码示例

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

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



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

示例1: wrapper

        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception, e:
                logging.error("Error: %s : %s", func.__name__, str(e))

                if not hasattr(e, 'errorCode'):
                    out.failureMessage("Sorry, operation has failed!!!.")
                    tools.exitErr()

                errorCode = int(e.errorCode)

                # auth-token error, re-auth
                if errorCode == 9:
                    storage = Storage()
                    storage.removeUser()
                    GeekNote()
                    return func(*args, **kwargs)

                elif errorCode == 3:
                    out.failureMessage("Sorry, you do not have permissions "
                                       "to do this operation.")

                else:
                    return False

                tools.exitErr()
开发者ID:DerekV,项目名称:geeknote,代码行数:27,代码来源:geeknote.py


示例2: createNote

    def createNote(
        self, title, content, tags=None, created=None, notebook=None, resources=None, reminder=None, url=None
    ):
        note = Types.Note()
        note.title = title
        try:
            note.content = content.encode("utf-8")
        except UnicodeDecodeError:
            note.content = content

        if tags:
            note.tagNames = tags

        note.created = created

        if notebook:
            note.notebookGuid = notebook

        if resources:
            """ make EverNote API resources """
            note.resources = map(make_resource, resources)

            """ add to content """
            resource_nodes = ""

            for resource in note.resources:
                resource_nodes += '<en-media type="%s" hash="%s" />' % (resource.mime, resource.data.bodyHash)

            note.content = note.content.replace("</en-note>", resource_nodes + "</en-note>")

        # Allow creating a completed reminder (for task tracking purposes),
        # skip reminder creation steps if we have a DELETE
        if reminder and reminder != config.REMINDER_DELETE:
            if not note.attributes:  # in case no attributes available
                note.attributes = Types.NoteAttributes()
            now = int(round(time.time() * 1000))
            if reminder == config.REMINDER_NONE:
                note.attributes.reminderOrder = now
            elif reminder == config.REMINDER_DONE:
                note.attributes.reminderOrder = now
                note.attributes.reminderDoneTime = now
            else:  # we have an actual reminder time stamp
                if reminder > now:  # future reminder only
                    note.attributes.reminderOrder = now
                    note.attributes.reminderTime = reminder
                else:
                    out.failureMessage("Error: reminder must be in the future.")
                    tools.exitErr()

        if url:
            if note.attributes is None:
                note.attributes = Types.NoteAttributes()
            note.attributes.sourceURL = url

        logging.debug("New note : %s", note)

        return self.getNoteStore().createNote(self.authToken, note)
开发者ID:jaguarondi,项目名称:geeknote,代码行数:57,代码来源:geeknote.py


示例3: login

    def login(self):
        if self.getEvernote().checkAuth():
            out.failureMessage("You have already logged in.")
            return tools.exitErr()

        if self.getEvernote().auth():
            out.successMessage("You have successfully logged in.")
        else:
            out.failureMessage("Login error.")
            return tools.exitErr()
开发者ID:khapota,项目名称:geeknote,代码行数:10,代码来源:geeknote.py


示例4: loadPage

    def loadPage(self, url, uri=None, method="GET", params=""):
        if not url:
            logging.error("Request URL undefined")
            tools.exitErr()

        if not uri:
            urlData = urlparse(url)
            url = urlData.netloc
            uri = urlData.path + '?' + urlData.query

        # prepare params, append to uri
        if params:
            params = urlencode(params)
            if method == "GET":
                uri += ('?' if uri.find('?') == -1 else '&') + params
                params = ""

        # insert local cookies in request
        headers = {
            "Cookie": '; '.join([key + '=' + self.cookies[key] for key in self.cookies.keys()])
        }

        if method == "POST":
            headers["Content-type"] = "application/x-www-form-urlencoded"

        logging.debug("Request URL: %s:/%s > %s # %s", url,
                      uri, unquote(params), headers["Cookie"])

        conn = httplib.HTTPSConnection(url)
        conn.request(method, uri, params, headers)
        response = conn.getresponse()
        data = response.read()
        conn.close()

        logging.debug("Response : %s > %s",
                      response.status,
                      response.getheaders())
        result = tools.Struct(status=response.status,
                              location=response.getheader('location', None),
                              data=data)

        # update local cookies
        sk = Cookie.SimpleCookie(response.getheader("Set-Cookie", ""))
        for key in sk:
            self.cookies[key] = sk[key].value
        # delete cookies whose content is "deleteme"
        for key in self.cookies.keys():
            if self.cookies[key] == "deleteme":
                del self.cookies[key]

        return result
开发者ID:IntrepidSuccess,项目名称:geeknote,代码行数:51,代码来源:oauth.py


示例5: logout

    def logout(self, force=None):
        if not self.getEvernote().checkAuth():
            out.failureMessage("You have already logged out.")
            return tools.exitErr()

        if not force and not out.confirm('Are you sure you want to logout?'):
            return tools.exit()

        result = self.getEvernote().removeUser()
        if result:
            out.successMessage("You have successfully logged out.")
        else:
            out.failureMessage("Logout error.")
            return tools.exitErr()
开发者ID:khapota,项目名称:geeknote,代码行数:14,代码来源:geeknote.py


示例6: edit

    def edit(
        self,
        note,
        title=None,
        content=None,
        tag=None,
        created=None,
        notebook=None,
        resource=None,
        reminder=None,
        url=None,
        raw=None,
    ):
        self.connectToEvernote()
        note = self._searchNote(note)

        inputData = self._parseInput(title, content, tag, created, notebook, resource, note, reminder, url)

        if inputData["content"] == config.EDITOR_OPEN:
            result = self._editWithEditorInThread(inputData, note, raw=raw)
        else:
            out.preloader.setMessage("Saving note...")
            result = bool(self.getEvernote().updateNote(guid=note.guid, **inputData))

        if result:
            out.successMessage("Note successfully saved.")
        else:
            out.failureMessage("Error: could not save note.")
            return tools.exitErr()
开发者ID:jaguarondi,项目名称:geeknote,代码行数:29,代码来源:geeknote.py


示例7: create

    def create(
        self,
        title,
        content=None,
        tag=None,
        created=None,
        notebook=None,
        resource=None,
        reminder=None,
        url=None,
        raw=None,
    ):
        self.connectToEvernote()

        # Optional Content.
        content = content or " "

        inputData = self._parseInput(title, content, tag, created, notebook, resource, None, reminder, url)

        if inputData["content"] == config.EDITOR_OPEN:
            result = self._editWithEditorInThread(inputData, raw=raw)
        else:
            out.preloader.setMessage("Creating note...")
            result = bool(self.getEvernote().createNote(**inputData))

        if result:
            out.successMessage("Note successfully created.")
        else:
            out.failureMessage("Error: could not create note.")
            return tools.exitErr()
开发者ID:jaguarondi,项目名称:geeknote,代码行数:30,代码来源:geeknote.py


示例8: find

    def find(self, search=None, tags=None, notebooks=None,
             date=None, exact_entry=None, content_search=None,
             with_url=None, count=None, ignore_completed=None, reminders_only=None,):

        request = self._createSearchRequest(search, tags, notebooks,
                                            date, exact_entry,
                                            content_search,
                                            ignore_completed, reminders_only)

        if not count:
            count = 20
        else:
            count = int(count)

        logging.debug("Search count: %s", count)

        createFilter = True if search == "*" else False
        result = self.getEvernote().findNotes(request, count, createFilter)

        if result.totalNotes == 0:
            out.failureMessage("Notes have not been found.")
            return tools.exitErr()

        # save search result
        # print result
        self.getStorage().setSearch(result)

        out.SearchResult(result.notes, request, showUrl=with_url)
开发者ID:IntrepidSuccess,项目名称:geeknote,代码行数:28,代码来源:geeknote.py


示例9: _createSearchRequest

    def _createSearchRequest(self, search=None, tags=None,
                             notebooks=None, date=None,
                             exact_entry=None, content_search=None):

        request = ""
        if notebooks:
            for notebook in tools.strip(notebooks.split(',')):
                if notebook.startswith('-'):
                    request += '-notebook:"%s" ' % tools.strip(notebook[1:])
                else:
                    request += 'notebook:"%s" ' % tools.strip(notebook)

        if tags:
            for tag in tools.strip(tags.split(',')):

                if tag.startswith('-'):
                    request += '-tag:"%s" ' % tag[1:]
                else:
                    request += 'tag:"%s" ' % tag

        if date:
            date = tools.strip(date.split('-'))
            try:
                dateStruct = time.strptime(date[0] + " 00:00:00", "%d.%m.%Y %H:%M:%S")
                request += 'created:%s ' % time.strftime("%Y%m%d", time.localtime(time.mktime(dateStruct)))
                if len(date) == 2:
                    dateStruct = time.strptime(date[1] + " 00:00:00", "%d.%m.%Y %H:%M:%S")
                request += '-created:%s ' % time.strftime("%Y%m%d", time.localtime(time.mktime(dateStruct) + 60 * 60 * 24))
            except ValueError, e:
                out.failureMessage('Incorrect date format in --date attribute. '
                                   'Format: %s' % time.strftime("%d.%m.%Y", time.strptime('19991231', "%Y%m%d")))
                return tools.exitErr()
开发者ID:khapota,项目名称:geeknote,代码行数:32,代码来源:geeknote.py


示例10: textToENML

    def textToENML(content, raise_ex=False, format='markdown'):
        """
        Create an ENML format of note.
        """
        if not isinstance(content, str):
            content = ""
        try:
            content = unicode(content, "utf-8")
            # add 2 space before new line in paragraph for creating br tags
            content = re.sub(r'([^\r\n])([\r\n])([^\r\n])', r'\1  \n\3', content)
            if format=='markdown':
              contentHTML = markdown.markdown(content).encode("utf-8")
              # Non-Pretty HTML output
              contentHTML = str(BeautifulSoup(contentHTML, 'html.parser'))
            else:
              contentHTML = Editor.HTMLEscape(content)
            return Editor.wrapENML(contentHTML)
        except:
            if raise_ex:
                raise Exception("Error while parsing text to html."
                                " Content must be an UTF-8 encode.")

            logging.error("Error while parsing text to html. "
                          "Content must be an UTF-8 encode.")
            out.failureMessage("Error while parsing text to html. "
                               "Content must be an UTF-8 encode.")
            return tools.exitErr()
开发者ID:DerekV,项目名称:geeknote,代码行数:27,代码来源:editor.py


示例11: checkVersion

 def checkVersion(self):
     versionOK = self.getUserStore().checkVersion("Python EDAMTest",
                                    UserStoreConstants.EDAM_VERSION_MAJOR,
                                    UserStoreConstants.EDAM_VERSION_MINOR)
     if not versionOK:
         logging.error("Old EDAM version")
         return tools.exitErr()
开发者ID:khapota,项目名称:geeknote,代码行数:7,代码来源:geeknote.py


示例12: _searchNote

    def _searchNote(self, note):
        note = tools.strip(note)

        # load search result
        result = self.getStorage().getSearch()
        if result and tools.checkIsInt(note) and 1 <= int(note) <= len(result.notes):
            note = result.notes[int(note) - 1]

        else:
            request = self._createSearchRequest(search=note)

            logging.debug("Search notes: %s" % request)
            result = self.getEvernote().findNotes(request, 20)

            logging.debug("Search notes result: %s" % str(result))
            if result.totalNotes == 0:
                out.failureMessage("Notes have not been found.")
                return tools.exitErr()

            elif result.totalNotes == 1 or self.selectFirstOnUpdate:
                note = result.notes[0]

            else:
                logging.debug("Choose notes: %s" % str(result.notes))
                note = out.SelectSearchResult(result.notes)

        logging.debug("Selected note: %s" % str(note))
        return note
开发者ID:khapota,项目名称:geeknote,代码行数:28,代码来源:geeknote.py


示例13: handleTwoFactor

    def handleTwoFactor(self):
        self.code = out.GetUserAuthCode()
        self.postData['tfa']['code'] = self.code
        response = self.loadPage(self.url['base'], self.url['tfa'] + ";jsessionid=" + self.cookies['JSESSIONID'], "POST", self.postData['tfa'])
        if not response.location and response.status == 200:
            if self.incorrectCode < 3:
                out.preloader.stop()
                out.printLine('Sorry, incorrect two factor code')
                out.preloader.setMessage('Authorize...')
                self.incorrectCode += 1
                return self.handleTwoFactor()
            else:
                logging.error("Incorrect two factor code")

        if not response.location:
            logging.error("Target URL was not found in the response on login")
            tools.exitErr()
开发者ID:jeffkowalski,项目名称:geeknote,代码行数:17,代码来源:oauth.py


示例14: _parseInput

    def _parseInput(self, title=None, content=None, tags=None, notebook=None, resources=[], note=None, reminder=None):
        result = {
            "title": title,
            "content": content,
            "tags": tags,
            "notebook": notebook,
            "resources": resources,
            "reminder": reminder,
        }
        result = tools.strip(result)

        # if get note without params
        if note and title is None and content is None and tags is None and notebook is None:
            content = config.EDITOR_OPEN

        if title is None and note:
            result['title'] = note.title

        if content:
            if content != config.EDITOR_OPEN:
                if isinstance(content, str) and os.path.isfile(content):
                    logging.debug("Load content from the file")
                    content = open(content, "r").read()

                logging.debug("Convert content")
                content = Editor.textToENML(content)
            result['content'] = content

        if tags:
            result['tags'] = tools.strip(tags.split(','))

        if notebook:
            notepadGuid = Notebooks().getNoteGUID(notebook)
            if notepadGuid is None:
                newNotepad = Notebooks().create(notebook)
                notepadGuid = newNotepad.guid

            result['notebook'] = notepadGuid
            logging.debug("Search notebook")

        if reminder:
            then = config.REMINDER_SHORTCUTS.get(reminder)
            if then:
                now = int(round(time.time() * 1000))
                result['reminder'] = now + then
            elif reminder not in [config.REMINDER_NONE, config.REMINDER_DONE, config.REMINDER_DELETE]:
                reminder = tools.strip(reminder.split('-'))
                try:
                    dateStruct = time.strptime(reminder[0] + " " + reminder[1] + ":00", config.DEF_DATE_AND_TIME_FORMAT)
                    reminderTime = int(round(time.mktime(dateStruct) * 1000))
                    result['reminder'] = reminderTime
                except (ValueError, IndexError):
                    out.failureMessage('Incorrect date format in --reminder attribute. '
                                       'Format: %s' % time.strftime(config.DEF_DATE_FORMAT, time.strptime('199912311422', "%Y%m%d%H%M")))
                    return tools.exitErr()

        return result
开发者ID:IntrepidSuccess,项目名称:geeknote,代码行数:57,代码来源:geeknote.py


示例15: allowAccess

    def allowAccess(self):
        response = self.loadPage(self.url['base'],
                                 self.url['access'],
                                 "GET",
                                 {'oauth_token': self.tmpOAuthToken})

        logging.debug(response.data)
        tree = html.fromstring(response.data);
        token = "&" + urlencode({ 'csrfBusterToken': tree.xpath("//input[@name='csrfBusterToken']/@value")[0]}) + "&" + urlencode({ 'csrfBusterToken': tree.xpath("//input[@name='csrfBusterToken']/@value")[1]})
        sourcePage = tree.xpath("//input[@name='_sourcePage']/@value")[0]
        fp = tree.xpath("//input[@name='__fp']/@value")[0]
        targetUrl = tree.xpath("//input[@name='targetUrl']/@value")[0]
        logging.debug(token);

        if response.status != 200:
            logging.error("Unexpected response status "
                          "on login 200 != %s", response.status)
            tools.exitErr()

        if 'JSESSIONID' not in self.cookies:
            logging.error("Not found value JSESSIONID in the response cookies")
            tools.exitErr()

        access = self.postData['access']
        access['oauth_token'] = self.tmpOAuthToken
        access['oauth_callback'] = ""
        access['embed'] = 'false'
        access['suggestedNotebookName'] = 'Geeknote'
        access['supportLinkedSandbox'] = ''
        access['analyticsLoginOrigin'] = 'Other'
        access['clipperFlow'] = 'false'
        access['showSwitchService'] = 'true'
        access['_sourcePage'] = sourcePage
        access['__fp'] = fp
        access['targetUrl'] = targetUrl

        response = self.loadPage(self.url['base'],
                                 self.url['access'],
                                 "POST", access, token)

        if response.status != 302:
            logging.error("Unexpected response status on allowing "
                          "access 302 != %s", response.status)
            logging.error(response.data)
            tools.exitErr()

        responseData = self.parseResponse(response.location)
        if 'oauth_verifier' not in responseData:
            logging.error("OAuth verifier not found")
            tools.exitErr()

        self.verifierToken = responseData['oauth_verifier']

        logging.debug("OAuth verifier token take")
开发者ID:jeffkowalski,项目名称:geeknote,代码行数:54,代码来源:oauth.py


示例16: user

    def user(self, full=None):
        if not self.getEvernote().checkAuth():
            out.failureMessage("You are not logged in.")
            return tools.exitErr()

        if full:
            info = self.getEvernote().getUserInfo()
        else:
            info = self.getStorage().getUserInfo()
        out.showUser(info, full)
开发者ID:khapota,项目名称:geeknote,代码行数:10,代码来源:geeknote.py


示例17: getOAuthToken

    def getOAuthToken(self):
        response = self.loadPage(self.url['base'],
                                 self.url['token'],
                                 "GET",
                                 self.getTokenRequestData(
                                     oauth_token=self.tmpOAuthToken,
                                     oauth_verifier=self.verifierToken))

        if response.status != 200:
            logging.error("Unexpected response status on "
                          "getting oauth token 200 != %s", response.status)
            tools.exitErr()

        responseData = self.parseResponse(response.data)
        if 'oauth_token' not in responseData:
            logging.error("OAuth token not found")
            tools.exitErr()

        logging.debug("OAuth token take : %s", responseData['oauth_token'])
        self.OAuthToken = responseData['oauth_token']
开发者ID:jeffkowalski,项目名称:geeknote,代码行数:20,代码来源:oauth.py


示例18: edit

    def edit(self, notebook, title):
        notebook = self._searchNotebook(notebook)

        out.preloader.setMessage("Updating notebook...")
        result = self.getEvernote().updateNotebook(guid=notebook.guid, name=title)

        if result:
            out.successMessage("Notebook has been successfully updated.")
        else:
            out.failureMessage("Error while the updating the notebook.")
            return tools.exitErr()
开发者ID:Gems,项目名称:geeknote,代码行数:11,代码来源:geeknote.py


示例19: find

    def find(
        self,
        search=None,
        tag=None,
        notebook=None,
        date=None,
        exact_entry=None,
        content_search=None,
        with_url=None,
        with_tags=None,
        with_notebook=None,
        count=None,
        ignore_completed=None,
        reminders_only=None,
        guid=None,
    ):

        request = self._createSearchRequest(
            search, tag, notebook, date, exact_entry, content_search, ignore_completed, reminders_only
        )

        if not count:
            count = 20
        else:
            count = int(count)

        logging.debug("Search count: %s", count)

        createFilter = True if search == "*" else False
        result = self.getEvernote().findNotes(request, count, createFilter)

        if result.totalNotes == 0:
            out.failureMessage("Notes have not been found.")
            return tools.exitErr()

        # save search result
        # print result
        self.getStorage().setSearch(result)
        for note in result.notes:
            self.getStorage().setNote(note)

        if with_notebook:
            noteStore = self.getEvernote().getNoteStore()
            notebookNameFromGuid = dict()
            for note in result.notes:
                if note.notebookGuid not in notebookNameFromGuid:
                    notebookNameFromGuid[note.notebookGuid] = noteStore.getNotebook(
                        self.getEvernote().authToken, note.notebookGuid
                    ).name
                note.notebookName = notebookNameFromGuid[note.notebookGuid]

        out.SearchResult(
            result.notes, request, showUrl=with_url, showTags=with_tags, showNotebook=with_notebook, showGUID=guid
        )
开发者ID:jaguarondi,项目名称:geeknote,代码行数:54,代码来源:geeknote.py


示例20: getTmpOAuthToken

    def getTmpOAuthToken(self):
        response = self.loadPage(self.url['base'],
                                 self.url['token'],
                                 "GET",
                                 self.getTokenRequestData(
                                     oauth_callback="https://" + self.url['base']))

        if response.status != 200:
            logging.error("Unexpected response status on get "
                          "temporary oauth_token 200 != %s", response.status)
            tools.exitErr()

        responseData = self.parseResponse(response.data)
        if 'oauth_token' not in responseData:
            logging.error("OAuth temporary not found")
            tools.exitErr()

        self.tmpOAuthToken = responseData['oauth_token']

        logging.debug("Temporary OAuth token : %s", self.tmpOAuthToken)
开发者ID:IntrepidSuccess,项目名称:geeknote,代码行数:20,代码来源:oauth.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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