#-*-coding:utf-8-*-"""Import classification from a file determines the hierarchical relationship based on tabs or spaces at the beginning of a line (4 spaces Equal to one tab tab and spaces cannot be mixed) must be UTF-8 encoded-------test.txt shoes sneakers Sandals slipper boots sport Badminton Singles doubles swimming----------------------"""ImportRedisImportMySQLdbImportJSONclassCategory (object): Cache= Redis. Strictredis (host='localhost', Port = 6379,db=0) Conn= MySQLdb.connect (host='192.168.1.222', user='Root', passwd='123456', db='Gmian', charset='UTF8') """Open File read per row for processing""" defRun (Self,category_file): F= Open (Category_file,'R') whileTrue:#Print isinstance (line, Unicode) # detect if Unicode #Print Unicode (line, "Utf-8")line =F.readline ()ifline:self.writeCate (line)Else: Breakf.close ()#Delete Cache def __del__(self): keys= self.__class__. Cache.smembers ('Category_keys') forKeyinchkeys:self.__class__. Cache.delete (key) self.__class__. Cache.delete ('Category_cateid') self.__class__. Cache.delete ('Category_keys') #get an auto-Grow ID@classmethoddefGETINCR (CLS):returnInt (CLS.CACHE.INCR ('Category_cateid')) +Db_auto_insert#Add categories to the list by hierarchy@classmethoddefAdd (cls,num,catename): ID=cls.getincr () cls.insert_db (id,num,catename) Cls.cache.sadd ('Category_keys','Category_level_'+str (num)) Cls.cache.lpush ('Category_level_'+str (num), Json.dumps ([Id,catename] )#Get parent class@classmethoddefGetparentid (cls,num): Parent= Cls.cache.lindex ('Category_level_'+str (num-1), 0)if notParent:RaiseNameerror ('STOP!! The parent class was not found') Parent=json.loads (parent)returnParent[0] @classmethoddefwritecate (cls,line): Num,catename=Cls.getlevelnum (line) Cls.add (num,catename) @classmethoddefinsert_db (cls,id,num,catename):ifNum:pid=cls.getparentid (num)Else: PID=0 Cursor=cls.conn.cursor () cursor.execute ("INSERT INTO Gm_category (Cat_id,cat_name,parent_id,style,is_top_style,is_top_show,cat_ico) value (%s,%s,%s,%s,% s,%s,%s)", (Id,catename,pid,"', 0, 0,"') ) Cls.conn.commit ()#either all is \ t or all of them are space spaces 4 to one unit@staticmethoddefgetlevelnum (str): I=0 whileStr[i] = ='\ t': I+=1ifI:returnI,str[i:] whileStr[i] = =' ': I+=1if notI:return0,strreturnI/4, Str[i:]if __name__=='__main__': #>$ python category.py 153 (db_auto_insert) cate1.txt cate2.txt ... ImportSYSTry: Db_auto_insert= Int (sys.argv[1])#The maximum ID already exists otherwise the ID repeat insert failsFiles = sys.argv[2:] if notFiles:RaiseIndexerror ('Input Category File') exceptIndexerror as E:RaiseValueError ('---------argv errors-------') Cate=Category () forFileinchFiles:Try: Cate.run (file)exceptException as E:PrintePrintU"""+file+ u""Import failed"
Python Import categories from files