def selectTabType(self, tabType): for i in range(len(self.find_elements(*(By.CLASS_NAME, 'el-badge')))): if self.find_elements(*(By.CLASS_NAME, 'el-badge'))[i].text == tabType: self.find_elements(*(By.CLASS_NAME, 'el-badge'))[i].click() logger.info('点击进入{}界面'.format(tabType)) break
def fit_gaussian(normal_X): desc = scipy.stats.describe(normal_X) mean, var = desc.mean, desc.variance std_var = np.sqrt(var) logger.info(desc) logger.info('mean:' + str(mean) + ' std_var:' + str(std_var)) return {'name': 'gaussian', 'model': [mean, std_var]}
def unpack(buf): if len(buf) < 16: #包头不完整 return (UNPACK_CONTINUE, b'') else: #解析包头 header = buf[:16] (len_ack, cmd_id_ack, seq_id_ack) = struct.unpack('>I4xII', header) logger.info('收到新的封包,长度:{},cmd_id:{},seq_id:0x{:x}'.format( len_ack, cmd_id_ack, seq_id_ack)) #包长合法性验证 if len(buf) < len_ack: #包体不完整 return (UNPACK_CONTINUE, b'') else: if CMDID_PUSH_ACK == cmd_id_ack and PUSH_SEQ == seq_id_ack: #推送通知:服务器有新消息 #尝试获取sync key sync_key = Util.get_sync_key() if sync_key: #sync key存在 interface.new_sync() #使用newsync同步消息 longlink.send( pack(CMDID_REPORT_KV_REQ, business.sync_done_req2buf())) #通知服务器消息已接收 else: #sync key不存在 interface.new_init() #使用短链接newinit初始化sync key else: cmd_id = cmd_id_ack - 1000000000 if CMDID_NOOP_REQ == cmd_id: #心跳响应 logger.info('心跳返回:{}'.format(Util.b2hex(buf))) pass elif CMDID_MANUALAUTH_REQ == cmd_id: #登录响应 if business.login_buf2Resp(buf[16:len_ack], login_aes_key): raise RuntimeError('登录失败!') #登录失败 return (UNPACK_OK, buf[len_ack:]) return (UNPACK_OK, b'')
def read_data(path): #log_filepath = OUTPUT_PREFIX+'feature_info_dest_1s.csv' data = pd.read_csv(path, header=None, names=[ 'time', 'host_ip', 'prot', 'dest_port', 'NHP', 'NH', 'ANF', 'NF', 'NP', 'NB', 'ND', 'cor_ip_list' ], dtype={'dest_port': object}, parse_dates=['time']) #data.drop(['NP','NB'],axis=1,inplace=True) data.drop(['NP', 'NHP'], axis=1, inplace=True) data = data[~((data.prot == 'tcp') & (data.dest_port == '80'))] data.sort_values(by='time', inplace=True) #data.set_index('time',inplace=True) #data = data[data.host_ip.str.startswith('10.')] #normal_data = data[(data.index>=datetime.datetime(2013, 4, 2, 9, 0))&(data.index<datetime.datetime(2013, 4, 2, 21, 0))] data = data.loc[~data['host_ip'].isin(FILTER_SOURCE_IP_LIST)] #data = data.loc[~(data['prot']=='udp')] #mask = (data['time'] > NORMAL_START_DATE) & (data['time'] <= NORMAL_END_DATE) #normal_data = data.loc[mask] normal_data = data global attacker_victim_all attacker_victim_all += ['147.32.96.69'] logger.info('attacker ignore list: ' + str(attacker_victim_all)) normal_data = normal_data.loc[~normal_data['host_ip']. isin(attacker_victim_all)] return normal_data, data
def traffic_feature_anomaly_detect_overall(path, direction): ANOMALY_SCORE_COL_NAME = 'anomaly_score' normal_data, data = read_data(path) final_data = pd.DataFrame() final_data['time'] = data.time final_data['ip'] = data.host_ip final_data['dest_port'] = data['dest_port'] final_data['cor_ip_list'] = data['cor_ip_list'] final_data[ANOMALY_SCORE_COL_NAME] = 0 final_data['direction'] = direction final_data['raw_values'] = data.ANF port_list = list(pd.unique(data.dest_port)) for port in port_list: logger.info('##################################') logger.info('anomaly for ' + direction + ' data ') local_normal_data = normal_data local_data = local_normal_data score = feature_anomaly_score_computation(local_normal_data, local_data) final_data.iloc[:, final_data.columns.get_loc(ANOMALY_SCORE_COL_NAME )] = score return final_data
def selectHaveImage(self, text): self.click(*self._haveImage) try: self.select_item(text) except: self.select_item(text) logger.info('是否有影像 : {}'.format(text))
def selectSettlementUnit(self, vendorCode, vendorName=''): self.find_element( *(By.CLASS_NAME, 'contract-payment-plan')).find_elements( *(By.ID, 'form_vendorId'))[len( self.find_element(*( By.CLASS_NAME, 'contract-payment-plan')).find_elements( *(By.ID, 'form_vendorId'))) - 1].click() WebDriverWait(self.driver, 5).until( EC.visibility_of_element_located((By.ID, 'undefined_vendorCode'))) self.send_text(vendorCode, *(By.ID, 'undefined_vendorCode')) self.send_text(vendorName, *(By.ID, 'undefined_vendorName')) self.click(*(By.XPATH, '/html/body//form/div[3]/div/button[1]')) sleep(1) try: self.find_elements(*(By.CLASS_NAME, 'el-table__row'))[ len(self.find_elements(*(By.CLASS_NAME, 'el-table__row'))) - 1].click() except: logger.warning('警告,第一次没找到,重新查找点击') self.find_elements(*(By.CLASS_NAME, 'el-table__row'))[ len(self.find_elements(*(By.CLASS_NAME, 'el-table__row'))) - 1].click() logger.info('选择结算单位的部门编码为 : {}'.format(vendorCode)) logger.info('选择结算单位的部门名称为 : {}'.format(vendorName)) self.click(*(By.XPATH, '/html/body//div[3]/span/button[2]'))
def input_operationType(self, text): self.click(*self._operationTypeId) WebDriverWait(self.driver, 5).until( EC.visibility_of_element_located(self._operationTypeId)) self.send_text(text, *self._operationTypeId) sleep(1) logger.info("选择的业务类型为:{}".format(text))
def input_date(self, date): if int(date) > 32 or int(date) < 1: raise Exception("请输入正确的日期值") flag = False for i in range(len(self.find_elements(*(By.XPATH, '/html/body/div')))): if flag == True: break if ('el-date-picker' in self.getElementAttribute('class', *(By.XPATH, '/html/body/div[{}]'.format(i + 1)))) and \ ('display: none' not in self.getElementAttribute('style', *(By.XPATH, '/html/body/div[{}]'.format(i + 1)))): for x in range(6): if flag == True: break for y in range(7): if self.get_elementText( * (By.XPATH, '/html/body/div[{}]/div[1]/div/div[2]/table[1]/tbody/tr[{}]/td[{}]/div/span' .format(i + 1, x + 2, y + 1))) == date: self.click(*( By.XPATH, '/html/body/div[{}]/div[1]/div/div[2]/table[1]/tbody/tr[{}]/td[{}]/div/span' .format(i + 1, x + 2, y + 1))) flag = True break else: pass if flag != True: logger.error('日期框选择日期失败,请检查配置') raise Exception('日期框选择日期失败,请检查配置') else: logger.info("当前日期框填写的日期值为:{}号".format(date))
def __selectLe(self, leCode, leName=''): """ describe: form表单点击新增选择核算主体 :param leCode: 核算主体编码 :param leName: 核算主体名称 :return: None """ WebDriverWait(self.driver, 5).until( EC.visibility_of_element_located((By.ID, 'form_leId'))) self.click(*(By.ID, 'form_leId')) WebDriverWait(self.driver, 5).until( EC.visibility_of_element_located((By.ID, 'undefined_CODE'))) self.send_text(leCode, *(By.ID, 'undefined_CODE')) self.send_text(leName, *(By.ID, 'undefined_NAME')) self.click(*(By.XPATH, '/html/body//form/div[3]/div/button[1]')) sleep(1) try: self.find_elements(*(By.CLASS_NAME, 'el-table__row'))[ len(self.find_elements(*(By.CLASS_NAME, 'el-table__row'))) - 1].click() except: logger.warning('警告,第一次没找到,重新查找点击') self.find_elements(*(By.CLASS_NAME, 'el-table__row'))[ len(self.find_elements(*(By.CLASS_NAME, 'el-table__row'))) - 1].click() logger.info('选择的核算主体编码为 : {}'.format(leCode)) logger.info('选择的核算主体名称为 : {}'.format(leName)) self.click(*(By.XPATH, '/html/body//div//span/button[2]'))
def __selectCompanyBank(self, account): """ describe: form表单点击新增选择归属账户 :param account: 银行账户 :return: None """ self.click(*(By.ID, 'form_companyBankId')) WebDriverWait(self.driver, 5).until( EC.visibility_of_element_located( (By.ID, 'undefined_BANK_ACCOUNT_NUM'))) self.send_text(account, *(By.ID, 'undefined_BANK_ACCOUNT_NUM')) self.click(*(By.XPATH, '/html/body//form/div[2]/div/button[1]')) sleep(1) try: self.find_elements(*(By.CLASS_NAME, 'el-table__row'))[ len(self.find_elements(*(By.CLASS_NAME, 'el-table__row'))) - 1].click() except: logger.warning('警告,第一次没找到,重新查找点击') self.find_elements(*(By.CLASS_NAME, 'el-table__row'))[ len(self.find_elements(*(By.CLASS_NAME, 'el-table__row'))) - 1].click() logger.info('选择的核算主体编码为 : {}'.format(account)) self.click(*(By.XPATH, '/html/body//div//span/button[2]'))
def __selectSignEmp(self, loginName, realName=''): """ describe: form表单选择签收人 :param loginName: 登录账号 :param realName: 员工名称 :return: None """ self.click(*(By.ID, 'form_signEmpId')) WebDriverWait(self.driver, 5).until( EC.visibility_of_element_located((By.ID, 'undefined_LOGIN_NAME'))) self.send_text(loginName, *(By.ID, 'undefined_LOGIN_NAME')) self.send_text(realName, *(By.ID, 'undefined_REAL_NAME')) self.click(*(By.XPATH, '/html/body//form/div[3]/div/button[1]')) sleep(3) try: self.find_elements(*(By.CLASS_NAME, 'el-table__row'))[ len(self.find_elements(*(By.CLASS_NAME, 'el-table__row'))) - 1].click() except: logger.warning('警告,第一次没找到,重新查找点击') self.find_elements(*(By.CLASS_NAME, 'el-table__row'))[ len(self.find_elements(*(By.CLASS_NAME, 'el-table__row'))) - 1].click() logger.info('选择登录账号为 : {}'.format(loginName)) logger.info('选择员工名称为 : {}'.format(realName)) self.click(*(By.XPATH, '/html/body//div//span/button[2]'))
def __selectOperatorDept(self, deptName, companyName=''): """ describe: form表单选择经办部门 :param deptName: 部门名称 :param companyName: 公司名称 :return: None """ self.click(*(By.ID, 'form_operatorDeptId')) WebDriverWait(self.driver, 5).until( EC.visibility_of_element_located((By.ID, 'undefined_DEPT_NAME'))) self.send_text(deptName, *(By.ID, 'undefined_DEPT_NAME')) self.send_text(companyName, *(By.ID, 'undefined_COMPANY_NAME')) self.click(*(By.XPATH, '/html/body//form/div[3]/div/button[1]')) sleep(1) try: self.find_elements(*(By.CLASS_NAME, 'el-table__row'))[ len(self.find_elements(*(By.CLASS_NAME, 'el-table__row'))) - 1].click() except: logger.warning('警告,第一次没找到,重新查找点击') self.find_elements(*(By.CLASS_NAME, 'el-table__row'))[ len(self.find_elements(*(By.CLASS_NAME, 'el-table__row'))) - 1].click() logger.info('选择部门名称为 : {}'.format(deptName)) logger.info('选择公司名称为 : {}'.format(companyName)) self.click(*(By.XPATH, '/html/body//div//span/button[2]'))
def __selectOperator(self, empNo, empName=''): """ describe: form表单选择经办人 :param empNo: 员工工号 :param empNum: 员工名称 :return: None """ self.click(*(By.ID, 'form_operatorId')) WebDriverWait(self.driver, 5).until( EC.visibility_of_element_located((By.ID, 'undefined_EMP_NO'))) self.send_text(empNo, *(By.ID, 'undefined_EMP_NO')) self.send_text(empName, *(By.ID, 'undefined_EMP_NAME')) self.click(*(By.XPATH, '/html/body//form/div[3]/div/button[1]')) sleep(1) try: self.find_elements(*(By.CLASS_NAME, 'el-table__row'))[ len(self.find_elements(*(By.CLASS_NAME, 'el-table__row'))) - 1].click() except: logger.warning('警告,第一次没找到,重新查找点击') self.find_elements(*(By.CLASS_NAME, 'el-table__row'))[ len(self.find_elements(*(By.CLASS_NAME, 'el-table__row'))) - 1].click() logger.info('选择员工工号为 : {}'.format(empNo)) logger.info('选择员工名称为 : {}'.format(empName)) self.click(*(By.XPATH, '/html/body//div//span/button[2]'))
def test_businessApprove(self, comFeeApplyBoe_testdata): logger.info(" ----- 单据业务审批开始 ----- ") global boeNum self.businessApprove = BusinessApprove(boeNum) content = self.businessApprove.boeBusinessApprove() logger.info(" ----- 单据业务审批结束 ----- ") assert content == '审批成功'
def setup_class(self): self.driver = driverFactory.get_driver('chrome') self.publicloginpage = PublicLoginPage(self.driver) self.publicloginpage.goto_publicloginpage(config.getUrlDict()['url']['publicHost']) logger.info("链接地址为:{}".format(config.getUrlDict()['url']['publicHost'])) self.driver.implicitly_wait(1) logger.info("测试用户登录场景")
def login_buf2Resp(buf,login_aes_key): #解包 loginRes = mm_pb2.ManualAuthResponse() loginRes.result.code = -1 loginRes.ParseFromString(Util.UnPack(buf,login_aes_key)) #登录异常处理 if -301 == loginRes.result.code: #DNS解析失败,请尝试更换idc logger.info('登陆结果:\ncode:{}\n请尝试更换DNS重新登陆!'.format(loginRes.result.code)) elif -106 == loginRes.result.code: #需要在IE浏览器中滑动操作解除环境异常/扫码、短信、好友授权(滑动解除异常后需要重新登录一次) logger.info('登陆结果:\ncode:{}\nError msg:{}\n'.format(loginRes.result.code,loginRes.result.err_msg.msg[loginRes.result.err_msg.msg.find('<Content><![CDATA[')+len('<Content><![CDATA['):loginRes.result.err_msg.msg.find(']]></Content>')])) #打开IE,完成授权 logger.info('请在浏览器授权后重新登陆!') Util.OpenIE(loginRes.result.err_msg.msg[loginRes.result.err_msg.msg.find('<Url><![CDATA[')+len('<Url><![CDATA['):loginRes.result.err_msg.msg.find(']]></Url>')]) elif loginRes.result.code: #其他登录错误 logger.info('登陆结果:\ncode:{}\nError msg:{}\n'.format(loginRes.result.code,loginRes.result.err_msg.msg[loginRes.result.err_msg.msg.find('<Content><![CDATA[')+len('<Content><![CDATA['):loginRes.result.err_msg.msg.find(']]></Content>')])) else: #登陆成功 #密钥协商 Util.sessionKey = Util.aesDecrypt(loginRes.authParam.session.key,Util.DoEcdh(loginRes.authParam.ecdh.ecdhKey.key)) #保存uin/wxid Util.uin = loginRes.authParam.uin Util.wxid = loginRes.accountInfo.wxId logger.info('登陆成功!\nsession_key:{}\nuin:{}\nwxid:{}\nnickName:{}\nalias:{}'.format(Util.sessionKey,Util.uin,Util.wxid,loginRes.accountInfo.nickName,loginRes.accountInfo.Alias)) #初始化db Util.init_db() return loginRes.result.code
def test_businessApprove(self): logger.info(" ----- 单据业务审批开始 ----- ") global boeNum self.businessApprove = BusinessApprove(boeNum) content = self.businessApprove.boeBusinessApprove() logger.info(" ----- 单据业务审批开始 ----- ") assert content == '审批成功'
def test_sharingCenterApprove(self): logger.info(" ----- 单据财务审批开始 ----- ") global boeNum self.sharingCenterApprove = SharingCenterApprove(boeNum) self.sharingCenterApprove.sharingCenterApproveChuShen() self.sharingCenterApprove.sharingCenterApproveFuShen() logger.info(" ----- 单据财务审批结束 ----- ")
def test_deleteBusinessCategoryBig(self): sleep(1) self.businessTypePage.open_businessType() sleep(1) self.businessTypePage.input_filterBox("test") sleep(1) self.businessTypePage.click_businessOpen() self.businessTypePage.click_businessTypeBig() sleep(1) self.businessTypePage.click_deleteButton() sleep(1) self.businessTypePage.click_deleteSubmitButton() self.businessTypePage.click_totalBusinessType() WebDriverWait(self.businessTypePage.driver, 5).until( EC.visibility_of_element_located( self.businessTypePage.getToastBox())) logger.info("这是:------->{}".format( self.businessTypePage.getToastBoxText())) assert self.businessTypePage.getToastBoxText() == "删除成功"
def test_updateBusinessCategoryBig(self): sleep(1) self.businessTypePage.open_businessType() sleep(1) self.businessTypePage.input_filterBox("test") sleep(1) self.businessTypePage.click_businessOpen() self.businessTypePage.click_businessTypeBig() self.businessTypePage.click_editButton() self.businessTypePage.input_businessTypeCodeBox("test") self.businessTypePage.input_businessTypeNameCBox("test") self.businessTypePage.input_appDisplayNameCBox("test") self.businessTypePage.input_auditPointsCBox("test") self.businessTypePage.click_submitButton() WebDriverWait(self.businessTypePage.driver, 5).until( EC.visibility_of_element_located( self.businessTypePage.getToastBox())) logger.info("这是:------->{}".format( self.businessTypePage.getToastBoxText())) assert self.businessTypePage.getToastBoxText() == "编辑成功"
def click_salaryAddButton(self): try: self.click(*self._salaryAddButton) except: sleep(1) self.click(*self._salaryAddButton) logger.info('点击新增按钮')
def test_addBusinessCategoryBig(self): WebDriverWait(self.businessTypePage.driver, 5).until( EC.visibility_of_element_located( self.businessTypePage.getReimbursementBasis())) self.businessTypePage.open_reimbursementBasis() self.businessTypePage.open_businessType() WebDriverWait(self.businessTypePage.driver, 5).until( EC.visibility_of_element_located( self.businessTypePage.getTotalBusinessType())) self.businessTypePage.click_totalBusinessType() self.businessTypePage.click_addBusinessCategoryBigButton() self.businessTypePage.input_businessTypeCodeBox("test") self.businessTypePage.input_businessTypeNameCBox("test") self.businessTypePage.input_appDisplayNameCBox("test") self.businessTypePage.input_auditPointsCBox("test") self.businessTypePage.click_submitButton() WebDriverWait(self.businessTypePage.driver, 5).until( EC.visibility_of_element_located( self.businessTypePage.getToastBox())) logger.info("这是:------->{}".format( self.businessTypePage.getToastBoxText())) assert self.businessTypePage.getToastBoxText() == "新建成功"
def GetDns(): headers = { "Accept": "*/*", "Accept-Encoding": "deflate", "Cache-Control": "no-cache", "Connection": "close", "Content-type": "application/octet-stream", "User-Agent": "MicroMessenger Client" } conn = http.client.HTTPConnection('dns.weixin.qq.com', timeout=10) conn.request("GET", '/cgi-bin/micromsg-bin/newgetdns', "", headers) response = conn.getresponse() data = zlib.decompress(response.read(), -zlib.MAX_WBITS) conn.close() parsed = xmltodict.parse(data, encoding='utf-8') ipLong = '' ipShort = '' #取长短链接ip,默认使用服务器返回的第一个ip dictDomain = parsed['dns']['domainlist']['domain'] for i in range(len(dictDomain)): if dictDomain[i]['@name'] == 'szlong.weixin.qq.com': ipLong = dictDomain[i]['ip'][0] elif dictDomain[i]['@name'] == 'szshort.weixin.qq.com': ipShort = dictDomain[i]['ip'][0] logger.info('长链接ip:' + ipLong + ',短链接ip:' + ipShort) return {'longip': ipLong, 'shortip': ipShort}
def input_toCity(self, text): WebDriverWait(self.driver, 5).until(EC.visibility_of_element_located(self._toCity)) self.click(*self._toCity) self.send_text(text, *self._toCity) logger.info('选择的到达城市为:{}'.format(text)) sleep(1)
def input_expenseAmount(self, text): self.click(*self._expenseAmount) element = self.find_element(*self._expenseAmount) ActionChains(self.driver).send_keys_to_element( element, Keys.BACKSPACE).perform() ActionChains(self.driver).send_keys_to_element(element, text).perform() logger.info('还款金额为:{}'.format(text))
def InitAll(): Util.initLog() Util.ip = GetDns() #初始化ECC key if not Util.GenEcdhKey(): logger.info('初始化ECC Key失败!') Util.ExitProcess()
def tuling_robot(msg): #使用图灵接口获取自动回复信息 data = { 'reqType': 0, 'perception': { "inputText": { "text": msg.raw.content }, }, 'userInfo': { "apiKey": TULING_KEY, "userId": Util.GetMd5(msg.from_id.id) } } try: robot_ret = eval( Util.post(TULING_HOST, TULING_API, json.dumps(data)).decode()) logger.debug('tuling api 返回:{}'.format(robot_ret)) #自动回消息 interface.new_send_msg( msg.from_id.id, robot_ret['results'][0]['values']['text'].encode(encoding="utf-8")) except: logger.info('tuling api 调用异常!') return
def input_costExpenseAmount(self, text, count='0'): self._costExpenseAmount = (By.ID, 'cost.{}.expenseAmount'.format(count)) self.find_elements(*self._costExpenseAmount)[len(self.find_elements(*self._costExpenseAmount))-2].click() element = self.find_elements(*self._costExpenseAmount)[len(self.find_elements(*self._costExpenseAmount))-2] self.find_elements(*self._costExpenseAmount)[len(self.find_elements(*self._costExpenseAmount))-2].send_keys(Keys.BACKSPACE) ActionChains(self.driver).send_keys_to_element(element, text).perform() logger.info('输入的总金额为 : {}'.format(text))
def selectReceiveVendor(self, name, account=''): """ describe: 选择收票方 :param text: 出票方 :param text: 出票方 :return: None """ self.click(*(By.ID, 'boeHeaderChild.0.vendorId')) WebDriverWait(self.driver, 5).until( EC.visibility_of_element_located((By.ID, 'itemname'))) self.send_text(name, *(By.ID, 'itemname')) self.send_text(account, *(By.ID, 'itembankAccount')) self.click(*(By.XPATH, '/html/body//form/div[3]/div/button[1]')) sleep(1) try: self.find_elements(*(By.CLASS_NAME, 'el-table__row'))[ len(self.find_elements(*(By.CLASS_NAME, 'el-table__row'))) - 1].click() except: logger.warning('警告,第一次没找到,重新查找点击') self.find_elements(*(By.CLASS_NAME, 'el-table__row'))[ len(self.find_elements(*(By.CLASS_NAME, 'el-table__row'))) - 1].click() logger.info('选择的收款人为 : {}'.format(name)) logger.info('选择的银行账户为 : {}'.format(account)) self.click(*(By.XPATH, '/html/body//div//span/button[2]'))
def send_ax_request(self,url,method="GET",retry=3,content_type="application/json",**kwargs): import tornado.httpclient as http from tornado.httpclient import HTTPError from Config import AX_SERVER if not url.startswith(AX_SERVER): url=AX_SERVER+url http_client = http.HTTPClient() http_request = http.HTTPRequest(url,method=method,headers={"Content-Type":content_type},connect_timeout=30,request_timeout=60,**kwargs) logger.info("Sending request to AX url: %s, method: %s"%(url,method)) if retry<1: retry=1 while retry>0: retry-=1 response=http_client.fetch(http_request,raise_error=False) logger.info(http_request.method+" | "+http_request.url+" | "+str(response.code)) if response.code<400: http_client.close() return response.body elif response.code==599: logger.info("Timeout, retry chance:"+str(retry)) if retry>0: continue else: raise HTTPError(response.code,message=response.body,response=response) else: raise HTTPError(response.code,message=response.body,response=response)
def send_swarm_request(self,url,method="GET",retry=1,content_type="application/json",**kwargs): import tornado.httpclient as http from tornado.httputil import HTTPHeaders from tornado.httpclient import HTTPError if not url.startswith(SWARM_API_URL_BASE): url=SWARM_API_URL_BASE+url http_client = http.HTTPClient() header =HTTPHeaders() header.add("content_type",content_type) if hasattr(self,"cookie"): #logged in header.add("Cookie",self.cookie) else: #not logged-in. readonly header.add("Cookie",self.readonly_cookie) http_request = http.HTTPRequest(url,method=method,headers=header,**kwargs) logger.info("Sending request to SWARM url: %s, method: %s"%(url,method)) if retry<0: retry=1 while retry>0: retry-=1 response=http_client.fetch(http_request,raise_error=False) logger.info (http_request.method+" | "+http_request.url+" | "+str(response.code)) if response.code<300: http_client.close() if "Set-Cookie" in response.headers.keys(): cookie=response.headers["Set-Cookie"] logger.info("Set Coockie: "+ cookie) self.cookie=cookie return response.body elif response.code==599: logger.info("Timeout, retry chance:"+str(retry)) logger.error(response.body) if retry>0: continue else: raise HTTPError(response.code,message=response.body,response=response) else: raise HTTPError(response.code,message=response.body,response=response)
print "-h\t\t\t\tShow help" if __name__ == "__main__": port=None try: options,args = getopt.getopt(sys.argv[1:],"hp:",["help","port="]) except getopt.GetoptError: print_help() sys.exit() for name,value in options: if name in ("-h","--help"): print_help() if name in ("-p","--port"): port=value logger.info("Port is "+port) if not port: port=8000 logger.info("Use default port "+str(port)) app = tornado.web.Application( route_map, template_path=Config.TEMPLATE_PATH, cookie_secret="131221", debug=True ) app.listen(int(port)) tornado.ioloop.IOLoop.current().start()