Best Python code snippet using yandex-tank
Pendant.py
Source:Pendant.py  
...47			args = list(args)48			args[0] = self.address_string()+'" : "'+args[0]49			HTTPServer.BaseHTTPRequestHandler.log_message(self, fmt, *args)50	#----------------------------------------------------------------------51	def do_HEAD(self, rc=200, content="text/html", cl=0):52		self.send_response(rc)53		self.send_header("Content-type", content)54		if cl != 0:55			self.send_header("Content-length", cl)56		self.end_headers()57	#----------------------------------------------------------------------58	def do_GET(self):59		"""Respond to a GET request."""60		if "?" in self.path:61			page,arg = self.path.split("?",1)62			arg = dict(urlparse.parse_qsl(arg))63		else:64			page = self.path65			arg = None66#		print self.path,type(self.path)67#		print page68#		print arg69		if page == "/send":70			if arg is None: return71			for key,value in arg.items():72				if key=="gcode":73					for line in value.split('\n'):74						httpd.app.queue.put(line+"\n")75				elif key=="cmd":76					httpd.app.pendant.put(urllib.unquote(value))77			#send empty response so browser does not generate errors78			self.do_HEAD(200, "text/text", cl=len(""))79			self.wfile.write("")80		elif page == "/state":81			tmp = {}82			for name in ["controller", "state", "pins", "color", "msg", "wx", "wy", "wz", "G", "OvFeed", "OvRapid", "OvSpindle"]:83				tmp[name] = CNC.vars[name]84			contentToSend = json.dumps(tmp)85			self.do_HEAD(200, content="text/text", cl=len(contentToSend))86			self.wfile.write(contentToSend)87		elif page == "/config":88			snd = {}89			snd["rpmmax"] = httpd.app.get("CNC","spindlemax")90			contentToSend = json.dumps(snd)91			self.do_HEAD(200, content="text/text", cl=len(contentToSend))92			self.wfile.write(contentToSend)93		elif page == "/icon":94			if arg is None: return95			filename = os.path.join(iconpath, arg["name"]+".gif")96			self.do_HEAD(200, content="image/gif", cl=os.path.getsize(filename))97			try:98				f = open(filename,"rb")99				self.wfile.write(f.read())100				f.close()101			except:102				pass103		elif page == "/canvas":104			if not Image: return105			with tempfile.NamedTemporaryFile(suffix='.ps') as tmp:106				httpd.app.canvas.postscript(107					file=tmp.name,108					colormode='color',109				)110				tmp.flush()111				try:112					with tempfile.NamedTemporaryFile(suffix='.gif') as out:113						Image.open(tmp.name).save(out.name, 'GIF')114						out.flush()115						out.seek(0)116						self.do_HEAD(200, content="image/gif", cl=os.path.getsize(tmp.name))117						self.wfile.write(out.read())118				except:119					filename = os.path.join(iconpath, "warn.gif")120					self.do_HEAD(200, content="image/gif", cl=os.path.getsize(filename))121					try:122						f = open(filename,"rb")123						self.wfile.write(f.read())124						f.close()125					except:126						pass127		elif page == "/camera":128			if not Camera.hasOpenCV(): return129			if Pendant.camera is None:130				Pendant.camera = Camera.Camera("webcam")131				Pendant.camera.start()132			if Pendant.camera.read():133				Pendant.camera.save("camera.jpg")134				#cv.imwrite("camera.jpg",img)135				self.do_HEAD(200, content="image/jpeg", cl=os.path.getsize("camera.jpg"))136				try:137					f = open("camera.jpg","rb")138					self.wfile.write(f.read())139					f.close()140				except:141					pass142		else:143			self.mainPage(page[1:])144	#----------------------------------------------------------------------145	def deal_post_data(self):146		boundary = self.headers.plisttext.split("=")[1]147		remainbytes = int(self.headers['content-length'])148		line = self.rfile.readline()149		remainbytes -= len(line)150		if not boundary in line:151			return (False, "Content NOT begin with boundary")152		line = self.rfile.readline()153		remainbytes -= len(line)154		fn = re.findall(r'Content-Disposition.*name="file"; filename="(.*)"', line)155		if not fn:156			return (False, "Can't find out file name...")157		path = os.path.expanduser("~")158		path = os.path.join(path, "bCNCUploads")159		if not os.path.exists(path):160		    os.makedirs(path)161		fn = os.path.join(path, fn[0])162		line = self.rfile.readline()163		remainbytes -= len(line)164		line = self.rfile.readline()165		remainbytes -= len(line)166		try:167			out = open(fn, 'wb')168		except IOError:169			return (False, "Can't create file to write, do you have permission to write?")170		preline = self.rfile.readline()171		remainbytes -= len(preline)172		while remainbytes > 0:173			line = self.rfile.readline()174			remainbytes -= len(line)175			if boundary in line:176				preline = preline[0:-1]177				if preline.endswith('\r'):178					preline = preline[0:-1]179				out.write(preline)180				out.close()181				return (True, "%s" % fn)182			else:183				out.write(preline)184				preline = line185		return (False, "Unexpected Ends of data.")186	#----------------------------------------------------------------------187	def do_POST(self):188		result,fMsg=self.deal_post_data()189		if(result):190			httpd.app._pendantFileUploaded=fMsg191		#send empty response so browser does not generate errors192		self.do_HEAD(200, "text/text")193	# ---------------------------------------------------------------------194	def mainPage(self, page):195		global webpath196		#handle certain filetypes197		filetype = page.rpartition('.')[2]198		if   filetype == "css": self.do_HEAD(content="text/css")199		elif filetype == "js":  self.do_HEAD(content="application/x-javascript")200		elif filetype == "json": self.do_HEAD(content="application/json")201		elif filetype == "jpg" or filetype == "jpeg" : self.do_HEAD(content="image/jpeg")202		elif filetype == "gif": self.do_HEAD(content="image/gif")203		elif filetype == "png": self.do_HEAD(content="image/png")204		elif filetype == "ico": self.do_HEAD(content="image/x-icon")205		else: self.do_HEAD()206		if page == "": page = "index.html"207		try:208			f = open(os.path.join(webpath,page),"r")209			self.wfile.write(f.read())210			f.close()211		except IOError:212			self.wfile.write("""<!DOCTYPE html>213<html>214<head>215<title>Errortitle</title>216<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=yes" />217</head>218<body>219Page not found....Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
