本文整理汇总了Python中notmuch.Database类的典型用法代码示例。如果您正苦于以下问题:Python Database类的具体用法?Python Database怎么用?Python Database使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Database类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: flush
def flush(self):
"""
tries to flush all queued write commands to the index.
:exception: :exc:`DatabaseROError` if db is opened in read-only mode
:exception: :exc:`DatabaseLockedError` if db is locked
"""
if self.ro:
raise DatabaseROError()
if self.writequeue:
try:
mode = Database.MODE.READ_WRITE
db = Database(path=self.path, mode=mode)
except NotmuchError:
raise DatabaseLockedError()
while self.writequeue:
cmd, querystring, tags, sync = self.writequeue.popleft()
query = db.create_query(querystring)
for msg in query.search_messages():
msg.freeze()
if cmd == 'tag':
for tag in tags:
msg.add_tag(tag.encode(DB_ENC),
sync_maildir_flags=sync)
if cmd == 'set':
msg.remove_all_tags()
for tag in tags:
msg.add_tag(tag.encode(DB_ENC),
sync_maildir_flags=sync)
elif cmd == 'untag':
for tag in tags:
msg.remove_tag(tag.encode(DB_ENC),
sync_maildir_flags=sync)
msg.thaw()
示例2: get_all_tags
def get_all_tags(self):
"""
returns all tagsstrings used in the database
:rtype: list of str
"""
db = Database(path=self.path)
return [t for t in db.get_all_tags()]
示例3: get_named_queries
def get_named_queries(self):
"""
returns the named queries stored in the database.
:rtype: dict (str -> str) mapping alias to full query string
"""
db = Database(path=self.path)
return {k[6:]: v for k, v in db.get_configs('query.')}
示例4: _get_notmuch_message
def _get_notmuch_message(self, mid):
"""returns :class:`notmuch.database.Message` with given id"""
mode = Database.MODE.READ_ONLY
db = Database(path=self.path, mode=mode)
try:
return db.find_message(mid)
except:
errmsg = 'no message with id %s exists!' % mid
raise NonexistantObjectError(errmsg)
示例5: query
def query(self, querystring):
"""
creates :class:`notmuch.Query` objects on demand
:param querystring: The query string to use for the lookup
:type query: str.
:returns: :class:`notmuch.Query` -- the query object.
"""
mode = Database.MODE.READ_ONLY
db = Database(path=self.path, mode=mode)
return db.create_query(querystring)
示例6: flush
def flush(self):
"""
write out all queued write-commands in order, each one in a separate
:meth:`atomic <notmuch.Database.begin_atomic>` transaction.
If this fails the current action is rolled back, stays in the write
queue and an exception is raised.
You are responsible to retry flushing at a later time if you want to
ensure that the cached changes are applied to the database.
:exception: :exc:`DatabaseROError` if db is opened in read-only mode
:exception: :exc:`DatabaseLockedError` if db is locked
"""
if self.ro:
raise DatabaseROError()
if self.writequeue:
try:
mode = Database.MODE.READ_WRITE
db = Database(path=self.path, mode=mode)
except NotmuchError:
raise DatabaseLockedError()
while self.writequeue:
current_item = self.writequeue.popleft()
cmd, querystring, tags, sync, afterwards = current_item
try: # make this a transaction
db.begin_atomic()
except XapianError:
raise DatabaseError()
query = db.create_query(querystring)
for msg in query.search_messages():
msg.freeze()
if cmd == 'tag':
for tag in tags:
msg.add_tag(tag.encode(DB_ENC),
sync_maildir_flags=sync)
if cmd == 'set':
msg.remove_all_tags()
for tag in tags:
msg.add_tag(tag.encode(DB_ENC),
sync_maildir_flags=sync)
elif cmd == 'untag':
for tag in tags:
msg.remove_tag(tag.encode(DB_ENC),
sync_maildir_flags=sync)
msg.thaw()
# end transaction and reinsert queue item on error
if db.end_atomic() != notmuch.STATUS.SUCCESS:
self.writequeue.appendleft(current_item)
else:
if callable(afterwards):
afterwards()
示例7: remove_message
def remove_message(self, message):
"""
Remove a message from the notmuch index
:param message: message to remove
:type message: :class:`Message`
"""
path = message.get_filename()
db = Database(path=self.path, mode=Database.MODE.READ_WRITE)
try:
status = db.remove_message(path)
except NotmuchError as e:
raise DatabaseError(unicode(e))
示例8: query
def query(self, querystring):
"""
creates :class:`notmuch.Query` objects on demand
:param querystring: The query string to use for the lookup
:type query: str.
:returns: :class:`notmuch.Query` -- the query object.
"""
mode = Database.MODE.READ_ONLY
db = Database(path=self.path, mode=mode)
q = db.create_query(querystring)
# add configured exclude tags
for tag in settings.get('exclude_tags'):
q.exclude_tag(tag)
return q
示例9: add_message
def add_message(self, path):
"""
Adds a file to the notmuch index.
:param path: path to the file
:type path: str
:returns: the message object corresponding the added message
:rtype: :class:`alot.message.Message`
"""
db = Database(path=self.path, mode=Database.MODE.READ_WRITE)
try:
message, status = db.add_message(path,
sync_maildir_flags=True)
except NotmuchError as e:
raise DatabaseError(unicode(e))
return Message(self, message)
示例10: main
def main():
# Handle command line options
#------------------------------------
# No option given, print USAGE and exit
if len(sys.argv) == 1:
Notmuch().cmd_usage()
#------------------------------------
elif sys.argv[1] == 'setup':
"""Interactively setup notmuch for first use."""
exit("Not implemented.")
#-------------------------------------
elif sys.argv[1] == 'new':
"""Check for new and removed messages."""
Notmuch().cmd_new()
#-------------------------------------
elif sys.argv[1] == 'help':
"""Print the help text"""
Notmuch().cmd_help(sys.argv[1:])
#-------------------------------------
elif sys.argv[1] == 'part':
part()
#-------------------------------------
elif sys.argv[1] == 'search':
search()
#-------------------------------------
elif sys.argv[1] == 'show':
show()
#-------------------------------------
elif sys.argv[1] == 'reply':
db = Database()
if len(sys.argv) == 2:
# no search term. abort
exit("Error: notmuch reply requires at least one search term.")
# mangle arguments wrapping terms with spaces in quotes
querystr = quote_query_line(sys.argv[2:])
msgs = Query(db, querystr).search_messages()
print Notmuch().format_reply(msgs)
#-------------------------------------
elif sys.argv[1] == 'count':
if len(sys.argv) == 2:
# no further search term, count all
querystr = ''
else:
# mangle arguments wrapping terms with spaces in quotes
querystr = quote_query_line(sys.argv[2:])
print Database().create_query(querystr).count_messages()
#-------------------------------------
elif sys.argv[1] == 'tag':
# build lists of tags to be added and removed
add = []
remove = []
while not sys.argv[2] == '--' and \
(sys.argv[2].startswith('+') or sys.argv[2].startswith('-')):
if sys.argv[2].startswith('+'):
# append to add list without initial +
add.append(sys.argv.pop(2)[1:])
else:
# append to remove list without initial -
remove.append(sys.argv.pop(2)[1:])
# skip eventual '--'
if sys.argv[2] == '--': sys.argv.pop(2)
# the rest is search terms
querystr = quote_query_line(sys.argv[2:])
db = Database(mode=Database.MODE.READ_WRITE)
msgs = Query(db, querystr).search_messages()
for msg in msgs:
# actually add and remove all tags
map(msg.add_tag, add)
map(msg.remove_tag, remove)
#-------------------------------------
elif sys.argv[1] == 'search-tags':
if len(sys.argv) == 2:
# no further search term
print "\n".join(Database().get_all_tags())
else:
# mangle arguments wrapping terms with spaces in quotes
querystr = quote_query_line(sys.argv[2:])
db = Database()
msgs = Query(db, querystr).search_messages()
print "\n".join([t for t in msgs.collect_tags()])
#-------------------------------------
elif sys.argv[1] == 'dump':
# TODO: implement "dump <filename>"
if len(sys.argv) == 2:
f = sys.stdout
else:
f = open(sys.argv[2], "w")
db = Database()
query = Query(db, '')
query.set_sort(Query.SORT.MESSAGE_ID)
msgs = query.search_messages()
for msg in msgs:
f.write("%s (%s)\n" % (msg.get_message_id(), msg.get_tags()))
#-------------------------------------
elif sys.argv[1] == 'restore':
if len(sys.argv) == 2:
print("No filename given. Reading dump from stdin.")
f = sys.stdin
else:
f = open(sys.argv[2], "r")
#.........这里部分代码省略.........
示例11: cmd_new
def cmd_new(self):
"""Run 'notmuch new'"""
#get the database directory
db = Database(mode=Database.MODE.READ_WRITE)
path = db.get_path()
print self._add_new_files_recursively(path, db)
示例12: main
def main():
parser = argparse.ArgumentParser(
description="Sync message 'X-Keywords' header with notmuch tags.")
parser.add_argument("-V", "--version", action="version",
version="%(prog)s " + "v%s (%s)" % (__version__, __date__))
parser.add_argument("-q", "--query", dest="query", required=True,
help="notmuch database query string")
parser.add_argument("-p", "--db-path", dest="dbpath",
help="notmuch database path (default to try user configuration)")
parser.add_argument("-n", "--dry-run", dest="dryrun",
action="store_true", help="dry run")
parser.add_argument("-v", "--verbose", dest="verbose",
action="store_true", help="show verbose information")
# Exclusive argument group for sync mode
exgroup1 = parser.add_mutually_exclusive_group(required=True)
exgroup1.add_argument("-m", "--merge-keywords-tags",
dest="direction_merge", action="store_true",
help="merge 'X-Keywords' and tags and update both")
exgroup1.add_argument("-k", "--keywords-to-tags",
dest="direction_keywords2tags", action="store_true",
help="sync 'X-Keywords' to notmuch tags")
exgroup1.add_argument("-t", "--tags-to-keywords",
dest="direction_tags2keywords", action="store_true",
help="sync notmuch tags to 'X-Keywords'")
# Exclusive argument group for tag operation mode
exgroup2 = parser.add_mutually_exclusive_group(required=False)
exgroup2.add_argument("-a", "--add-only", dest="mode_addonly",
action="store_true", help="only add notmuch tags")
exgroup2.add_argument("-r", "--remove-only", dest="mode_removeonly",
action="store_true", help="only remove notmuch tags")
# Parse
args = parser.parse_args()
# Sync direction
if args.direction_merge:
sync_direction = SyncDirection.MERGE_KEYWORDS_TAGS
elif args.direction_keywords2tags:
sync_direction = SyncDirection.KEYWORDS_TO_TAGS
elif args.direction_tags2keywords:
sync_direction = SyncDirection.TAGS_TO_KEYWORDS
else:
raise ValueError("Invalid synchronization direction")
# Sync mode
if args.mode_addonly:
sync_mode = SyncMode.ADD_ONLY
elif args.mode_removeonly:
sync_mode = SyncMode.REMOVE_ONLY
else:
sync_mode = SyncMode.ADD_REMOVE
#
if args.dbpath:
dbpath = os.path.abspath(os.path.expanduser(args.dbpath))
else:
dbpath = None
#
db = Database(path=dbpath, create=False, mode=Database.MODE.READ_WRITE)
dbinfo = get_notmuch_revision(dbpath=dbpath)
q = Query(db, args.query)
total_msgs = q.count_messages()
msgs = q.search_messages()
#
if args.verbose:
print("# Notmuch database path: %s" % dbpath)
print("# Database revision: %d (uuid: %s)" %
(dbinfo['revision'], dbinfo['uuid']))
print("# Query: %s" % args.query)
print("# Sync direction: %s" % sync_direction.name)
print("# Sync mode: %s" % sync_mode.name)
print("# Total messages to check: %d" % total_msgs)
print("# Dryn run: %s" % args.dryrun)
#
for msg in msgs:
kwmsg = KwMessage(msg)
kwmsg.sync(direction=sync_direction, mode=sync_mode,
dryrun=args.dryrun, verbose=args.verbose)
#
db.close()
示例13: get_message
def get_message(self, mid):
"""returns the message with given id as alot.message.Message object"""
mode = Database.MODE.READ_ONLY
db = Database(path=self.path, mode=mode)
msg = db.find_message(mid)
return Message(self, msg)
示例14: get_thread
def get_thread():
query = Database().create_query('thread:0000000000000c48')
return query.search_threads().next()
示例15: get_all_tags
def get_all_tags(self):
"""returns all tags as list of strings"""
db = Database(path=self.path)
return [t for t in db.get_all_tags()]