1) Python, now used, followed by daily practice grammar and deep excavation applications

Source: Internet
Author: User
Tags cas urlencode ticket redis cluster

Python1, the MAC system comes with a Python path/system/library/frameworks/python.framework/version contains multiple versions available: Start Pythonimport sysprint Sys.path View Path/system/library/frameworks/python.framework/versions/2.7/lib/python27.zip  2, Mac Inside can start the idle new. py file, and then open cmd with the Mac to carry the Python path/.py file Windows can be written in notepad++, and then CTRL + F5 configuration, as Run 3,mac Chinese character support Https://www.jianshu.com/p/8333f08ec87d 4 is not supported, automatically send mail http://www.runoob.com/python/python-email.html#! /usr/bin/env python#! /usr/bin/env python# coding=utf-8import sysimport osimport urllibimport urllib2import unittestimport jsonimport time& Nbsp;reload (SYS) sys.setdefaultencoding ("Utf-8")  from email.mime.text import Mimetextfrom Email.mime.multipart Import Mimemultipartimport smtplib def sendmail (): msg = Mimemultipart () #att = Mimetext (open (R ' C:\Users\ Alice02.yang\desktop\brandid.txt ', ' RB '). Read (), ' base64 ', ' gb2312 ') #att ["content-type"] = ' application/ Octet-stream ' #att ["content-disposition"] = ' attachment; Filename= "Brandid.txt" ' #msg. Attach (ATT) &Nbsp;strto = (' [email protected] ', ' [email protected] ') msg[' to '] = '; '. Join (Strto) msg[' from '] = ' [email protected] ' msg[' subject '] = ' brandid '  try:server = smtplib. SMTP () server.connect (' smtp.163.com ') server.login (' [email protected] ', ' yzh1990a1a1 ') server.sendmail (msg[') From '], strto,msg.as_string ()) server.quit () print ' Finish ' except Exception, E:print str (e)  if __name__ = = ' __main_ _ ': SendMail ()   linux and cmd use CRONTAB-E and then write six o'clock in the afternoon 20 * * * * CD/USERS/VIP/PYTHONTESTSCRIPT; Python testautosendmail.py exit    steps to isolate message release from anti-spam gateways: http://wiki.corp.vipshop.com/pages/viewpage.action ?pageid=35029549&src=search   start → program → accessories → system tools → schedule tasks → open Add task schedule. Go to the Task Scheduler Wizard.   with Task Scheduler, you can schedule any script, program, or document to run at one of the most convenient times. Task Scheduler starts every time Windows XP is started and runs in the background. &NBSP;5, connecting database operations Linux to install MYSQLDB plugin  import mysqldb def conncur (): Conn=mysqldb.connect (host= ' 10.198.184.184 ', user= ' root ', passwd= ' admin ', port=3306,charset= ' GBK ') cur=conn.cursor () return conn,cur defConsql (): Try:conn,cur=conncur () cur.execute (' drop database if exists Vip_test_pythonmysql ') cur.execute (' Create Database if not exists Vip_test_pythonmysql ') conn.select_db (' Vip_test_pythonmysql ') #sqlfile =open (R ' D:\vipd.sql ') # Sql=sqlfile.readlines ()   #sqlfile. Close ()   #for line in sql: #cur. Execute (line) #conn. Commit () Cur.close () Conn.close () except Mysqldb.error,e:print "Mysql Error%d:%s"% (E.args[0], e.args[1])  if __name__ = = ' __main__ ': con SQL ()  6, multithreaded # coding:gbkimport timeimport urllibimport urllib2import threadingfrom Queue Import queuefrom time Import sleep     #THREAD_NUM = 10#one_worker_num = 500#loop_sleep = 0.01  thread_num = 100one_worker_num = 10loop_sleep = 0.5  perf_test_url= " error_num = 0 def Get (Url,para): Url_ Value = Urllib.urlencode (para) fullurl=url+ '? ' +url_valueprint Fullurldata=urllib2.urlopen (fullurl,timeout=20) json=data.read () return json     def doWork (index): t = Threading.currentthrEAD () #print "[" +t.name+ "" +str (Index) + "]" +perf_test_url try:url= "http://10.199.144.188/ Vips-mobile-operation-center-api/cms/content/list/get_rule_resp ' para= Build_para () json = Get (Url,para) print Jsonexcept Urllib2. Urlerror, E:print "[" +t.name+ "" +str (Index) + "]" Print Eglobal Error_numerror_num + 1  def working (): t = Thread Ing.currentthread () print "[" +t.name+ "] Sub Thread Begin"  i = 0while i < one_worker_num:i + 1doWork (i) Sleep (loop_ SLEEP)  print "[" +t.name+ "] Sub Thread End"  def Build_para ():p ara={}para[' mid ']= ' 123456789 ' para[' function ' ]= ' testfunction ' para[' appname ']= ' TestApp ' para[' warehouse ']= ' vip_sh ', ' para[' tag ']= ' C10 ' para[' client ']= ' ipad ' para[ ' Areaid ']= ' 103101 ' para[' mchannel ']= ' ' Return ' para  def main (): T1 = time.time () Threads = [] for i in Range (thread_num): t = Threading. Thread (target=working, name= "T" +str (i)) T.setdaemon (True) threads.append (t) for T in Threads:t.start () for T in Threads: T.join ()  print "main thread End" t2 = Time.tiMe () print "========================================" print "URL:", perf_test_urlprint "task num:", Thread_num, "*", one _worker_num, "=", Thread_num*one_worker_numprint "Total time Cost:", T2-t1print "per req Time Cost (sec):", (T2-T1)/(THR Ead_num*one_worker_num) print "req per sec:", 1/((T2-T1)/(Thread_num*one_worker_num)) print "Error NUM:", Error_num&nbs P; if __name__ = = "__main__": Main ()  7, Unit test Operation 52944782  Write testcase, then Testloader load TestCase to Testsuite, Then the Testsuite is run by Texttestrunner, and the result of the run is saved in Texttestresult, when we execute it through the command line or Unittest.main (). Main will call run in Texttestrunner, or we can execute the use case directly through Texttestrunner. Import Unittestclass TESTCDI (unittest. TestCase):d EF setUp (self): Consql ()  #------------------------across hit one-----------------------------#---- --------------------hit Challenger-----------------------------def testbroute_2 (self):  if __name__ = = ' __main_ _ ': Unittest.main ()   Each test method starts with   , otherwise the  8,post/get request operation is not recognized by UnitTest  #! /usr/bin/env python# CodinG=utf-8import urllib2import urllibimport httplibimport jsonurl= ' http://10.199.144.226/ vips-infra-cdi-rule-engine-service/cdi_rule_engine_service/get_cdi_resp/' Para={}para={}var={}f1=open (r "c \ Users\alice02.yang\desktop\my.txt ", ' W ') para[" function "]=" recommend "para[" AppName "]=" ADS "#var [" Mid "]=" 123456789 "Var[" Warehouse "]=" Vip_nh "#var [" tag "]=" B "var[" mid "]=" 11111111111 "#var [" Client "]=" iphone "#var [" Areaid "]=" 103107 "#var [" Mchannel "]=" 1 "var[" user_id "]=" 12345 "#var [" Version "]=" 2.11 "para[" variables "]=varurl_v = Urllib.urlencode ( Para) url_value=url_v.replace ("%27", '%22 ') fullurl=url+ '? ' +url_valueheaders = {"Content-type": "application/x-www-form-urlencoded", "Connection": "Keep-alive", "Referer": " http://10.199.144.226/vips-infra-cdi-rule-engine-service/cdi_rule_engine_service/get_cdi_resp/"}print Fullurlconn = Httplib. Httpconnection ("10.199.144.226"); Conn.request ("POST", "/vips-infra-cdi-rule-engine-service/cdi_rule_engine_ service/get_cdi_resp/", url_value,headers); response = Conn.getresponse ()  print Response.read () F1.close () conn.close ()   import hashlibimport jsonimport unittestimport urllib2 def Getmd5code (SRC): #print srcm1 = Hashlib.md5 () m1.update (SRC) return m1.hexdigest ()      9, connect redis cluster operation  #! /usr/bin/env python# coding=utf-8 import sysimport osimport jsonimport getoptimport urllib2from urllib Import Urlopenfrom rediscluster import strictrediscluster  reload (SYS) sys.setdefaultencoding ("Utf-8")  # URL = "Http://rank-admin.vip.vip.com/rank/category/findCategoryListInfoByTreeId" # Dataurl = "/http" Rank-admin.vip.vip.com/rank/redis/findbigdataformrediscluster "# ticket =" St-328962-sqddyif25gexgilfdxhj-cas.oa.vipshop.com "# Delete_data_url =" ". Join ([URL,"? ticket= ", Ticket," &treeid =160 "]) # Info_data_url =" ". Join ([Dataurl,"? ticket= ", Ticket," &key= "])  url =" http://rank-admin.vip.vip.com /rank/category/findcategorylistinfobytreeid "Dataurl =" http://rank-admin.vip.vip.com/rank/redis/ Findbigdataformrediscluster "Opener = Urllib2.build_opener () opener.addheaders.append (' Cookie ', ' _const_cas_assertion_= St-454039-hgko3kbgkzivpaglcb2x-cas.oa.vipshop.com ') Delete_data_url = "". Join ([URL, "? treeid=117"]) Info_data_url = "". Join ([Dataurl, "? key="])  f1=open (R ' C:\Users\alice02.yang\Desktop\ss\117mappingId.txt ', ' W ')  def Redis_cluster (key,value):p rint keyprint valueredis_nodes = [{' Host ': ' 10.198.184.184 ', ' Port ': 6379},{' host ': ' 10.198.184.184 ', ' Port ': 6380},{' host ': ' 10.198.184.185 ', ' Port ': 6379},{' host ': ' 10.198.184.185 ', ' Port ': 6380},{' Host ': ' 10.198.184.186 ', ' Port ': 6379},{' host ': ' 10.198.184.186 ', ' port ': 6380}]try:redisconn = Strictrediscluster ( Startup_nodes=redis_nodes) #rc = Strictrediscluster (startup_nodes=startup_nodes, decode_responses=true) except Exception,e:print "Connect error!" Sys.exit (1) try:redisconn.hmset (key,value) except:passprint "sssss" Print Redisconn.hgetall (key)   def rank (): catidlist=[] #print delete_data_url#content = Urlopen (Delete_data_url). Read () content = Opener.open (delete_dAta_url). Read () Print contentcontent = json.loads (content) Datas = content["Data"]; #print datasfor data in Datas:for i in da ta[' nodes ']:try:for j in i[' nodes '][0][' mappingcatids ']:catidlist.append (str (j)) Print i[' nodes '][0][' mappingcatids ']except:passreturn catidlist   def getbigdatainfo (cat): Adict = {}for i in cat:warehouse=["VIP_SH", " Vip_cd "," Vip_hz "," VIP_BJ "," Vip_nh "] #warehouse =[" Vip_zz "," vip_zzkg "," Vip_gzns "," VIP_JC "," Ht_gzzy "," Ht_gzflxy "," Vip_nbjcbs "," HT_NBYC "]for wareh in warehouse:key = str (i) +": "+ str (Wareh) +": 3105 "Print key#print Info_data_url + key Bigdatainfo = Urlopen (Info_data_url + key). Read () Bigdatainfo = Json.loads (bigdatainfo) Bigdatas = bigdatainfo["DATA"]; Try:print bigdatas["value"]adict[key]=bigdatas["value"]except:passreturn adict#for K in bigdatas["value"]: #print k# Redis_cluster (key,k,bigdatas["value"][k])   def main (): cat = Rank () #cat =[7494,1018]print catprint >> F1, "\ n". Join (cat) #adict = Getbigdatainfo (cat) #for Key,valueIn Adict.items (): #print key#print value#redis_cluster (key,value)  if __name__ = = "__main__": Main ()   10,excel table Operation  import Xlrdimport jsondata = Xlrd.open_workbook (R ' C:\Users\alice02.yang\Desktop\tt.xlsx ') Table = Data.sheet_by_name (U ' Sheet1 ') a=table.col_values (6) b=table.col_values (7) Dics={}result=[]for I in range (Len (a)): Dics={}print a[i]if Len (a[i]) ==0:breakdics[' name ']=a[i]dics[' value ']=b[i]print dicsresult.append (dics) print Resultdict_res=json.dumps (result,ensure_ascii=false) print dict_res.decode (' utf-8 '). Encode (' GBK ')   11, basic Operation http://www.runoob.com/python/python-json.html  Exception: = (, "W" fhwrite "This is a test file for testing exceptions!":p rint "Error: Failed to find file or read file "else Fhclose import osimport timeimport datetimeoverduename=list () Onedayago = ( Datetime.datetime.now ()-Datetime.timedelta (days = 1)) Onedayagotimestamp = Int (Time.mktime (Onedayago.timetuple ())) def del_files (path): For root, dirs, files in Os.walk (path):  for name in Files:if name.endswith (". xls"): Timestr = Nam E.split (". xls") [0].split (" Cdi_rule_ ") [1];timestrtoint = Int (Time.mktime (time.strptime (timestr, '%y-%m-%d '))) if Timestrtoint < = OneDayAgoTimeStamp:overdueName.append (name) If Len (overduename) >=10:for temp in OverdueName:os.remove ( Os.path.join (path, temp)) print ("Delete File:" + os.path.join (path, temp))  if __name__ = = "__main__": #path = '/tmp ' P Ath = ' E: ' Del_files (PATH)

1) Python, now used, followed by daily practice grammar and deep mining applications

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.