本文整理汇总了Python中tools.exitErr函数的典型用法代码示例。如果您正苦于以下问题:Python exitErr函数的具体用法?Python exitErr怎么用?Python exitErr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了exitErr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
示例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)
示例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()
示例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
示例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()
示例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()
示例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()
示例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)
示例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()
示例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()
示例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()
示例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
示例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()
示例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
示例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")