mock_httpserver

来源:互联网 发布:卷积神经网络模型算法 编辑:程序博客网 时间:2024/06/05 06:37

简单的http_mock 


#! /usr/local/bin/python2.6#encoding=utf-8import BaseHTTPServerimport urlparseimport timefrom SocketServer import ThreadingMixInimport threadingimport urllib2import urllibimport sysimport jsonimport socketclass 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_dataself.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"%telif len(path)<3 :return "[%s]�쳣����001"%telif len(path[2].strip())<=2:return "[%s]�ӿ���Ч�����ȱ������0"%tfunc_name = path[2].strip().lstrip('/').rstrip('/')args = path[4].strip().lstrip('/').rstrip('/')print "path = ",func_nameprint "args = ",argsredirect_url = ""if func_name == 'syncgetcurrentinfo':redirect_url = "http://ts.alibaba.net/testsupply/index.php/smokesynctasks/syncgetcurrentinfo/?";else:response = "[%s]δ֪�ӿ�:%s"%(t,func_name)return responsetry:print redirect_url+argshttp_timeout = 60*5 #��ʱ���ã���λ����return_data = ""while True:time_start = time.time() #��λ����time.sleep(5) #5���һ��״̬������Ƶ���������#print http_timeoutresponse = 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":breakelif return_json['status'] == "TASK IS RUNNING":time_end = time.time() #��λ����cost_time = time_end - time_starthttp_timeout = http_timeout - cost_timeif http_timeout <= 0:return '[%s]������ʱ�����ϵapiά����Ա!'%(t)continueelif return_json['status'] == "Failed":breakreturn return_dataexcept socket.timeout:return '[%s]������ʱ�����ϵapiά����Ա!'%(t)except Exception, e:print Exception,":",ereturn '[%s]�������쳣�����ϵapiά����Ա!'%tdef get_post_result(self,path,post_data):t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())if path == None:return "[%s]�ӿڲ������ǿյ�!\n"%telif post_data == None or len(post_data)==0:return "[%s]û��post���!"%telif len(path)<3 :return "[%s]�쳣����001"%telif len(path[2].strip())<=1:return "[%s]�ӿ���Ч�����ȱ������0"%tfunc_name = path[2].strip()[1:]print "path = ",func_nameredirect_url = ""if func_name == 'syncpushrequest':redirect_url = "http://ts.alibaba.net/testsupply/index.php/smokesynctasks/syncpushrequest";else:response = "[%s]δ֪�ӿ�:%s"%(t,func_name)return responsetry: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 #��¼�����е�����idif 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_inforeturn 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,":",et = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())return '[%s]�������쳣(%s)�����ϵapiά����Ա!'%(t,str(e))class ThreadingHttpServer( ThreadingMixIn, BaseHTTPServer.HTTPServer ):    passif __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 requestserver_thread = threading.Thread(target=server.serve_forever)# Exit the server thread when the main thread terminatesserver_thread.setDaemon(True)server_thread.start()print "Server loop running in thread:", server_thread.getName()while True:pass


0 0
原创粉丝点击