Some code for twisted

Source: Internet
Author: User

Before using Swoole write a program in the data volume when there is a memory leak, to twisted implementation, self-test error, recorded as follows (the pressure test CPU consumption from 80% to 20%, the throughput RPS from 120 to 280).

#!/usr/bin/env python fromTwisted.internetImporttask, Reactor fromTwisted.pythonImportLog fromTwisted.webImportstatic, server, resourceImportMySQLdbImportJSONclassRotatemap (object):def __init__(self): self.using=0 Self.unuse= 1Self.map= [{},{}]    deffind (Self, key):ifSelf.map[self.using].has_key (key):returnSelf.map[self.using][key]returnFalsedefset (self, nmap): Self.map[self.unuse]=nmap Self._swap ()defGet (self):returnSelf.map[self.using]def_swap (self): Self.using,self.unuse=Self.unuse,self.usingcheck=Rotatemap () allow=Rotatemap () Start=Rotatemap () log.startlogging (open ("/tmp/tserver.log",'W'))classTserver (Resource. Resource): IsLeaf=TruedefGetchild (self, Name, request):ifName = ="':            return SelfreturnResource.getchild (self, name, request)defRender_get (self, request):ifRequest.requestHeaders.hasHeader ("x-forwarded-for"): Log.msg ("%s %s%s"% (Request.requestHeaders.getRawHeaders ("x-forwarded-for"), Request.path, Json.dumps (Request.args)))Else: Log.msg ("%s %s%s"% ("127.0.0.1", Request.path, Json.dumps (Request.args))) if "/api1"==Request.path:ifRequest.args.has_key ("version"): Version= request.args["version"][0]ifVersion! ="":                GlobalStart Info=start.get () result= {}                ifinfo["version"] !=version:result["Needup"] =True result["version"] =InfoElse: result["Needup"] =Falsereturnjson.dumps (Result)elif "/api2"==Request.path:host=""            ifRequest.args.has_key ("Host"): Host= request.args["Host"][0]GlobalCheckifHost! ="": v1=Check.find (host)ifV1 = =False:v1="0"            return "%s"%(v1)elif "/api3"==Request.path:host=""            ifRequest.args.has_key ("Host"): Host= request.args["Host"][0] V1= V2 = 1Global AllowifHost! =""  andAllow.find (host)! =False:v1=0return "%d|%d"%(V1,V2)elif "/reload"==Request.path:cmd="file"            ifRequest.args.has_key ("cmd"): cmd= request.args["cmd"][0] Helper=Reloadhelper () helper.reload (cmd)return " Done"        Else: Request.setresponsecode (50U)            return "404 Not Found"Request.setresponsecode (400)        return "Request"classReloadhelper (object):defReload (self, cmd): log.msg ("Reload%s Start"%(cmd))ifcmd = ="DB": Self._reloaddb ()elifcmd = ="file": Self._reloadfile () log.msg ("Reload%s End"%(cmd))def_reloadfile (self): Data={} f= Open ("Check.data") Line=F.readline () whileLine:domain, Levelid= Line.strip (). Split ("|") Data[domain]=Levelid Line=f.readline () f.close ( )Globalcheck Check.set (data) data={} f= Open ("Allow.data") Line=F.readline () whileLine:domain=Line.strip () Data[domain]="0" Line=f.readline () f.close ( )GlobalAllow allow.set (data)def_reloaddb (self):Try: Conn=mysqldb.connect (host='hostname', user='username', passwd='passwd', port=3306) conn.select_db ("dbname") cur=conn.cursor () Cur.execute ("Set names UTF8") Cur.execute ("SELECT ID, version, name from table ORDER by ID DESC LIMIT 1") Row=Cur.fetchone ()ifLen (Row) = = 3: Data={} data["ID"] =Row[0] data["version"] = row[1] data["name"] = row[2]                Globalstart Start.set (data) Cur.close () conn.close ()exceptMysqldb.error, E:log.err ("MySQL error%d,%s"% (E.args[0], e.args[1]) Helper=Reloadhelper () L= task. Loopingcall (Helper.reload,"DB") L.start (600) L= task. Loopingcall (Helper.reload,"file") L.start (3600000)defMain (): Tserver= static. File ("/usr/local/nginx/html") Tserver.putchild ("Service", Tserver ()) Tserver.putchild ("HTML", Static. File ("/usr/nginx/html")) Reactor.listentcp (8080, server. Site (Tserver), 50,"127.0.0.1") Reactor.run ()if __name__=='__main__': Main ()

Some code for twisted

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.