def apply_gmail_label_rules(db_session, message, added_categories, removed_categories):
 add = {}
 discard = {}
 categories = {c.name: c for c in message.categories if c.name}
 for cat in added_categories:
  if (cat.name == 'all'):
   discard = {'trash', 'spam'}
  elif (cat.name == 'trash'):
   discard = {'all', 'spam', 'inbox'}
  elif (cat.name == 'spam'):
   discard = {'all', 'trash', 'inbox'}
  elif (cat.name == 'inbox'):
   add = {'all'}
   discard = {'trash', 'spam'}
 for name in add:
  if (name not in categories):
   category = db_session.query(Category).filter((Category.namespace_id == message.namespace_id), (Category.name == name)).one()
   message.categories.add(category)
 for name in discard:
  if (name in categories):
   message.categories.discard(categories[name])

def apply_gmail_label_rules ( db_session , message , added_categories , removed_categories ) : add = { } discard = { } categories = { c . name : c for c in message . categories if c . name } for cat in added_categories : if ( cat . name == 'all' ) : discard = { 'trash' , 'spam' } elif ( cat . name == 'trash' ) : discard = { 'all' , 'spam' , 'inbox' } elif ( cat . name == 'spam' ) : discard = { 'all' , 'trash' , 'inbox' } elif ( cat . name == 'inbox' ) : add = { 'all' } discard = { 'trash' , 'spam' } for name in add : if ( name not in categories ) : category = db_session . query ( Category ) . filter ( ( Category . namespace_id == message . namespace_id ) , ( Category . name == name ) ) . one ( ) message . categories . add ( category ) for name in discard : if ( name in categories ) : message . categories . discard ( categories [ name ] )
the api optimistically updates message .