Пример #1
0
def set_default_difficulty(fname='situation.dict'):
    print 'load_pickle ... ',
    dic = load_pickle(fname)
    print 'done.'
    scores = calc_default_difficulty(dic)
    print 'calc_default_difficulty ... done.'
    del dic
    con = MySQLdb.connect(db=db, host=host,\
            user=user, passwd=passwd, charset=charset)
    cur = con.cursor()
    user_id, comment = 19, ''
    get_rstid = 'select Rcd from tabelog where tabelogurl = %s limit 1'
    session = Session()
    i, count = 1, len(scores)
    for_add = []
    for url, difficulty in scores.iteritems():
        print '{i} / {count} url'.format(i=i, count=count)
        difficulty = round(difficulty, 1)
        i += 1
        result = cur.execute(get_rstid, url)
        rst_id = cur.fetchone()[0] if result else None
        now = datetime.now()

        userpost = session.query(UserPost)\
                .filter('user_id = :user_id and rst_id = :rst_id')\
                .params(user_id=user_id, rst_id=rst_id).first()
        if userpost:
            print 'update'
            userpost.modified = now
            userpost.difficulty = difficulty
            userpost.comment = comment
        else:
            print 'insert'
            user_post = UserPost(user_id, rst_id, difficulty, comment, now, now)
            # session.begin()
            for_add.append(user_post)
    try:
        session.add_all(for_add)
        session.flush()
        session.commit()
        session.close()
    except Exception ,e:
        session.rollback()
        print e
        session.close()
        return False