def searchAndSaveCategory(session, objs): if not len(objs): return None for obj in objs: try: cat = searchCategory(session, obj) except NoResultFound, e: cat = Category( name=obj['name'].decode('unicode-escape'), cat_type=obj['cat_type'].decode('unicode-escape'), url_rewrite=pinyin.get(obj['name'].decode('unicode-escape')) or '') session.add(cat) #myLogger.error('cannot find cat whose name=%s' % (obj['name'],)) continue except Exception, e: raise e
def searchAndLinkCategory(session, movie, savedMovieObj, video_type_id): if savedMovieObj is None: return None cats = movie['categories'] for catName in cats: try: # 查找已有的 catObj = session.query(Category).filter(Category.name == catName.decode('unicode-escape')).filter(Category.video_type_id == video_type_id).one() savedMovieObj.categories.append(catObj) except NoResultFound, e: # if not found, then save the cat, and associate the relations catObj = Category(name=catName.decode('unicode-escape'), video_type_id=video_type_id, url_rewrite = pinyin.get(catName.decode('unicode-escape')) or '', is_hot = 0, is_displayed = 0 ) session.add(catObj) savedMovieObj.categories.append(catObj) except Exception, e: myLogger.error(e) continue
# cat1 = Category(name="cat 1") # cat2 = Category(name="cat 2") # video2.categories.append(cat1) # video2.categories.append(cat2) # session.add(video2) # session.add(cat1) # session.add(cat2) # video = session.query(Video).filter(Video.name == 'new video').one() # cat2 = session.query(Category).filter(Category.name =='cat 2').one() # video.categories.append(cat2) # video.categories.remove(cat2) # session.commit() #logging.basicConfig(filename='debug.log',level=logging.DEBUG) db = sqlite3.connect('result.db') cursor = db.cursor() cursor.execute('''SELECT taskid, result from resultdb_cat ''') row = cursor.fetchone() try: cats = ast.literal_eval(row[1]) for cat in cats: print 'processing : ' + cat['name'].decode('unicode-escape') session.add( Category(name=cat['name'].decode('unicode-escape'), url_rewrite=cat['url_rewrite'], video_type_id=int(cat['video_type_id']), is_hot=cat['is_hot'])) except Exception, e: logging.error(e) finally: session.commit()