mock_httpserver

简单的http_mock 


#! /usr/local/bin/python2.6
#encoding=utf-8
import BaseHTTPServer
import urlparse
import time
from SocketServer import ThreadingMixIn
import threading
import urllib2
import urllib
import sys
import json
import socket


class WebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
	def do_GET(self):
		url_path = urlparse.urlparse(self.path)
		print url_path
		#r_str='[{"keyword":"keyword","clickurl":"http://...","number":"1"},{"keyword":"testBidword2","clickurl":"http://...","number":"2"},{"keyword":"testBidword3","clickurl":"http://...","number":"3"}]'
		enc="UTF-8"
		#encoded = ''.join(r_str).encode(enc)
		http_response_data = self.get_get_result(url_path);
		encoded = http_response_data#unicode(r_str, "utf-8")
		#f = io.BytesIO()
		#f.write(encoded)
		#f.seek(0)
		self.send_response(200)
		self.send_header("Content-type", "text/html; charset=%s" % enc)
		self.send_header("Content-Length", str(len(encoded)))
		self.end_headers()
		#shutil.copyfileobj(f,self.wfile)
		self.wfile.write(encoded)
	def do_POST(self):
		print 'get post message\n'
		url_path = urlparse.urlparse(self.path)
		length = self.headers.getheader('content-length')
		nbytes = int(length)
		data = self.rfile.read(nbytes)
		cur_thread = threading.currentThread()
		print 'Thread:%s\t get post data is:%s\n' % (cur_thread.getName(), data)
		http_response_data = self.get_post_result(url_path,data);
		message = '\r\n'+http_response_data
		self.send_response(200)
		self.end_headers()
		self.wfile.write(message)

	def get_get_result(self,path):
		t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
		if path == None:
			return "[%s]�ӿڲ������ǿյ�!\n"%t
		elif len(path)<3 :
			return "[%s]�쳣����001"%t
		elif len(path[2].strip())<=2:
			return "[%s]�ӿ���Ч�����ȱ������0"%t
		func_name = path[2].strip().lstrip('/').rstrip('/')
		args = path[4].strip().lstrip('/').rstrip('/')
		print "path = ",func_name
		print "args = ",args
		redirect_url = ""
		if func_name == 'syncgetcurrentinfo':
			redirect_url = "http://ts.alibaba.net/testsupply/index.php/smokesynctasks/syncgetcurrentinfo/?";
		else:
			response = "[%s]δ֪�ӿ�:%s"%(t,func_name)
			return response
		try:
			print redirect_url+args
			http_timeout = 60*5 #��ʱ���ã���λ����
			return_data = ""
			while True:
				time_start = time.time() #�����
				time.sleep(5) #5���һ��״̬������Ƶ���������
				#print http_timeout
				response = urllib2.urlopen(redirect_url+args,timeout=http_timeout)
				return_data = response.read()
				return_json = json.loads(return_data)
				#{"taskid":"4901","rtcode":0,"schema":"SYNC","status":"TASK IS RUNNING","timeCommited":"2016-07-20 10:47:19"}
				#{"taskid":"4901","rtcode":0,"schema":"SYNC","status":"Succeed","timeCommited":"2016-07-20 10:47:19"}
				#{"taskid":"4875","rtcode":0,"schema":"SYNC","status":"Failed","timeCommited":"2016-07-20 09:39:38","info":"http:\/\/ts.alibaba.net\/stfpres\/20160720\/res_kgb_all_smoke_20160720_093941_ads_17411.html"}
				if return_json['status'] == "Succeed":
					break
				elif return_json['status'] == "TASK IS RUNNING":
					time_end = time.time() #�����
					cost_time = time_end - time_start
					http_timeout = http_timeout - cost_time
					if http_timeout <= 0:
						return '[%s]������ʱ�����ϵapiά����Ա!'%(t)
					continue
				elif return_json['status'] == "Failed":
					break
			return return_data
		except socket.timeout:
			return '[%s]������ʱ�����ϵapiά����Ա!'%(t)
		except Exception, e:
			print Exception,":",e
			return '[%s]�������쳣�����ϵapiά����Ա!'%t

	def get_post_result(self,path,post_data):
		t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
		if path == None:
			return "[%s]�ӿڲ������ǿյ�!\n"%t
		elif post_data == None or len(post_data)==0:
			return "[%s]û��post���!"%t
		elif len(path)<3 :
			return "[%s]�쳣����001"%t
		elif len(path[2].strip())<=1:
			return "[%s]�ӿ���Ч�����ȱ������0"%t
		func_name = path[2].strip()[1:]
		print "path = ",func_name
		redirect_url = ""
		if func_name == 'syncpushrequest':
			redirect_url = "http://ts.alibaba.net/testsupply/index.php/smokesynctasks/syncpushrequest";
		else:
			response = "[%s]δ֪�ӿ�:%s"%(t,func_name)
			return response
		try:
			request = urllib2.Request(redirect_url,post_data)
			response=urllib2.urlopen(request)
			return_data = response.read()
			response.close()
			if return_data!= None:
				print return_data
				#return_data = '{"rtcode":0,"status":"SUCCESS","taskid":"4518"}'
				#return_data = '{"rtcode":0,"taskid":"4866","status":"FAIL","Details":"create smoke subtask failed"}'
				return_json = json.loads(return_data)
				taskid = -1 #��¼�����е�����id
				if return_json['status']!= None and return_json['status']=="SUCCESS":
					if return_json['taskid']!= None:
						request_url = "http://10.125.64.99:12345/syncgetcurrentinfo/?taskid=%s"%(return_json['taskid'])
						url_path = urlparse.urlparse(request_url)
						remote_status_info = self.get_get_result(url_path)
						print remote_status_info
						return str(remote_status_info)
				elif return_json['status']!= None and return_json['status']=="FAIL":
					if return_json['Details']!= None:
						return return_data #ʧ���ˣ��Ӱ�ʧ����Ϣ����
					else:
						return "request server %s failed!\n "%redirect_url #û����ʧ�����飬��ʹ��Ĭ��ʧ����ʾ��Ϣ
			else:
				return "[%s]���ýӿ�%sʧ��,û����ݷ���"%(t,func_name)
		except Exception, e:
			print t,Exception,":",e
			t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
			return '[%s]�������쳣(%s)�����ϵapiά����Ա!'%(t,str(e))

class ThreadingHttpServer( ThreadingMixIn, BaseHTTPServer.HTTPServer ):
    pass

if __name__ == '__main__':
	#server = BaseHTTPServer.HTTPServer(('0.0.0.0',18460), WebRequestHandler)
	server = ThreadingHttpServer(('0.0.0.0',12345), WebRequestHandler)
	ip, port = server.server_address
	# Start a thread with the server -- that thread will then start one
	# more thread for each request
	server_thread = threading.Thread(target=server.serve_forever)
	# Exit the server thread when the main thread terminates
	server_thread.setDaemon(True)
	server_thread.start()
	print "Server loop running in thread:", server_thread.getName()
	while True:
		pass


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值