def __init__(self): ''' Constructor ''' # token获取相关变量(使用MyNavi信息) self.token_request = HttpRequest("https://openapi.baidu.com/oauth/2.0/token") self.key_grant_type = "grant_type" self.value_grant_type = "client_credentials" self.key_client_id = "client_id" self.value_client_id = "XWNntfdAttoOsshbTLI9d7BxWX4wO8Ye" self.key_client_secret = "client_secret" self.value_client_secret = "OU4fqmeeUQaAyoSNchvgk817lWRGRGnT" # 语音合成相关变量 self.voice_request = HttpRequest("http://tsn.baidu.com/text2audio") self.key_tex = "tex" self.key_lan = "lan" self.value_lan = "zh" # token的有效期为一个月(2017-3-14th) self.key_tok = "tok" self.value_tok = "24.6f389722b04a319b23a9405b0150aec7.2592000.1492073691.282335-8404201" self.key_ctp = "ctp" self.value_ctp = 1 self.key_cuid = "cuid" self.value_cuid = "eddy_eddy_eddy_eddy_eddy"
def download_page(self, url): request = HttpRequest(url) success = request.download() if not success: return None else: return request
def stock_price(self, *args): #metodo que busca preço de ação por palavra chave if len(args) != 1: return "para ver o preço de ações deve ser passado o nome de uma \ exemplo: \\veracao AAPL" h = HttpRequest() try: temp = h.make_request(self.external_files.stock_link + args[0], self.external_files.stock_server, port=443) except: #caso de erro no servidor print(self.external_files.stock_server.encode()) return "impossível conectar ao servidor de terceiro\n" try: d = json.loads(temp)["price"] except KeyError: #caso seja uma ação errada return "Ação {} não encontrada\n".format(args[0]) except json.JSONDecodeError: return "Recebemos uma mensagem estranha do servidor externo, nossos engenheiros estão trabalhando nisso".format( args[0]) except Exception as e: print(temp) return "Problema com o servidor externo\n" return "preço da ação " + args[0] + ": " + str( d) + "\n" #preço formatado da ação
def __init__(self, config, functions): """ run testcase or testsuite. Args: config (dict): testcase/testsuite config dict { "name": "ABC", "variables": {}, "setup_hooks", [], "teardown_hooks", [] } http_client_session (instance): requests.Session() """ base_url = config.get("base_url") self.verify = config.get("verify", True) self.output = config.get("output", []) self.functions = functions self.validation_results = [] # testcase setup hooks testcase_setup_hooks = config.get("setup_hooks", []) # testcase teardown hooks self.testcase_teardown_hooks = config.get("teardown_hooks", []) self.http_client_session = HttpRequest(base_url) self.session_context = SessionContext(self.functions) if testcase_setup_hooks: self.do_hook_actions(testcase_setup_hooks, "setup")
def __init__( self, host="", url="/", method="GET", headers={}, protocol=PT.HTTP, content=None, port=None, key_file=None, cert_file=None, timeout=None): HttpRequest.__init__( self, host=host, url=url, method=method, headers=headers) self.__ssl_enable = False if protocol is PT.HTTPS: self.__ssl_enable = True self.__key_file = key_file self.__cert_file = cert_file self.__port = port self.__connection = None self._timeout = timeout self.set_body(content)
def __init__(self, host="", url="/", method="GET", headers={}, protocol="https", body=None, port=443, key_file=None, cert_file=None, timeout=None): HttpRequest.__init__(self, host=host, url=url, method=method, body=body, headers=headers) self.__ssl_enable = False if protocol is "https": self.__ssl_enable = True self.__key_file = key_file self.__cert_file = cert_file self.__port = port self.__connection = None self._timeout = timeout
def __init__(self,host="",url="/",method="GET",headers={},protocol=PT.HTTP,port=None,key_file=None,cert_file=None): HttpRequest.__init__(self,host=host,url=url,method=method,headers=headers) self.__ssl_enable=False if protocol is PT.HTTPS: self.__ssl_enable=True self.__key_file=key_file self.__cert_file=cert_file self.__port=port self.__connection=None
class MyTts(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' # token获取相关变量(使用MyNavi信息) self.token_request = HttpRequest("https://openapi.baidu.com/oauth/2.0/token") self.key_grant_type = "grant_type" self.value_grant_type = "client_credentials" self.key_client_id = "client_id" self.value_client_id = "XWNntfdAttoOsshbTLI9d7BxWX4wO8Ye" self.key_client_secret = "client_secret" self.value_client_secret = "OU4fqmeeUQaAyoSNchvgk817lWRGRGnT" # 语音合成相关变量 self.voice_request = HttpRequest("http://tsn.baidu.com/text2audio") self.key_tex = "tex" self.key_lan = "lan" self.value_lan = "zh" # token的有效期为一个月(2017-3-14th) self.key_tok = "tok" self.value_tok = "24.6f389722b04a319b23a9405b0150aec7.2592000.1492073691.282335-8404201" self.key_ctp = "ctp" self.value_ctp = 1 self.key_cuid = "cuid" self.value_cuid = "eddy_eddy_eddy_eddy_eddy" def get_token(self): data = {self.key_grant_type:self.value_grant_type, \ self.key_client_id:self.value_client_id, \ self.key_client_secret:self.value_client_secret} res = self.token_request.get(params=data).text res_dic = json.loads(res) if(res_dic.has_key("access_token")): return res_dic["access_token"] else: return None def voice_synth(self, content): data = {self.key_tex:content, \ self.key_lan:self.value_lan, \ self.key_tok:self.value_tok, \ self.key_ctp:self.value_ctp, \ self.key_cuid:self.value_cuid} voice_data = self.voice_request.get(params=data).content voice_file = open("./voice.mp3", "wb") voice_file.write(voice_data) voice_file.close()
def dollar2real( self, *args ): #metodo que converte 1 dolar em real em um servidor externo e retona try: h = HttpRequest() dollar_string = h.make_request(self.external_files.dollar_link, self.external_files.dollar_server) d = json.loads(dollar_string.decode())["USD"] message = "preço de baixo: {}\npreço de alta: {}\npreço de bid: {}\npreço de ask: {}\n".format( d["low"], d["high"], d["bid"], d["ask"]) except: message = "impossivel alcançar servidor {}".format( self.external_files.dollar_server) return message
def new_http_request(self): request = HttpRequest() request.set_url(self.api.get('url')) request.set_headers(self.api.get('headers') if self.api.get('headers') else \ {"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"}) request.set_data(self.handle_data()) return request
def test_http_request(self, a): print("测试数据是:", a) print("目前正在执行第%s条用例" % a[0]) global COOKIES res = HttpRequest(a[4], eval(a[5])).httpRequest( a[3], cookies=COOKIES) #!!!要将从excel中读出的字典格式装换一下 if res.cookies != {}: #判断cookies是否为空用{},或用len(res.cookies)==0 COOKIES = res.cookies print(res.json()) try: self.assertEqual(str(a[6]), res.json()['code']) #!!!预期结果要转换成str result = 'PASS' except AssertionError as e: result = 'FAIL' raise e #!!!终止后面的代码 finally: self.t.write_data(a[0] + 1, str(res.json()), result)
def accept_client(self, ed, connections, requests): try: connection, address = self.serversocket.accept() connection.setblocking(0) ed.register(connection.fileno(), select.EPOLLIN) connections[connection.fileno()] = connection requests[connection.fileno()] = HttpRequest() except Exception as ex: logging.error('err_accept:{}'.format(ex))
def get_json(self): http = HttpRequest() print(self.value) r = http.get(self.value) if self == DogeLinks.all_by_day: data_json = json.loads(r.text)["data"]["quotes"] for price in data_json: usd = price["quote"]["USD"] for price_detail in usd: price[price_detail] = usd[price_detail] # print('price_detail', price_detail) del price["quote"] return data_json if self == DogeLinks.day_by_5_min: return self.parse_5min_data(r.text)
def __make_request(self, command): res = HttpRequest( self.method, self.url, headers=self.headers, data=json.dumps(command, cls=JsonEncoder), ) if res.response is None: return None, 503 return self.__prepare_response(command['command'], res.response), res.status_code
def run (self): #TODO: find the efficient way to listen for connections while True: client_connection, client_address = self.listen_socket.accept() print('Connection is accepted') request_data = client_connection.recv(self.__config['buff_size']) print('Data is recevied') httpRequest = HttpRequest(request_data, self.__config) self.handle_request(httpRequest, client_connection) print('Request is handled') client_connection.close() print('Connection is closed')
def worker(work_queue, i): while True: url = work_queue.get() print(i) sock = socket.socket() try: sock.connect(('localhost', 5000)) http_request = HttpRequest(host='localhost', port=5000, method="GET", data=url) sock.sendall(http_request.request.encode('utf-8')) data = sock.recv(2**12) sock.close() print(data.decode('utf-8')) except ConnectionRefusedError: print("Server doesn't work") work_queue.task_done()
def start(): socket_in = _create_socket() while True: client_socket, client_address = socket_in.accept() print(f"Established connection with client: {client_address}") print("Waiting for message from client...") raw_request = client_socket.recv(REQ_BUFFER_SIZE) print(f"Message received. Attempting to parse...") try: request = HttpRequest(raw_request) response = HttpResponse.ok(request) except InvalidHttpRequestException as e: response = HttpResponse.bad_request(e) client_socket.send(response.serialize()) client_socket.close() print("Socket closed.")
# -*- coding: utf-8 -*- # @Time : 2019/3/17 17:56 # @File : test_cases.py import unittest from my_ddt import ddt, data from my_log import MyLog from do_excel_new import DoExcel from http_request import HttpRequest from project_path import * from get_data import GetData log = MyLog() http = HttpRequest() cases = DoExcel(test_case_path).read_excel() @ddt class Test_All(unittest.TestCase): #读取表单文件 def setUp(self): log.info('******开始执行******') def tearDown(self): log.info('******执行结束******') @data(*cases) def test_case(self, case): method = case['method'] url = case['url'] params = eval(case['params']) write = DoExcel(test_case_path) #创建写回实例
def buy(buyer_phone,seller_phone): # 买家登录 login_url = 'http://m.test.hobay.com.cn/api/app/user/login' # 登录 login_data = {"loginValidateType": "CODE", "phone": buyer_phone, "validateValue": "666666"} login_res = HttpRequest().http_request(login_url, "post", json=login_data) print("登录结果是:", login_res.json()) #已得拍接口 haveAction_url='http://m.test.hobay.com.cn/ribbon-api/auctionOlBid/haveAction?currentPage=1&pageSize=10' headers={'login':''} haveAction_res=HttpRequest().http_request(haveAction_url,'get',headers=headers,cookies=login_res.cookies) print('得拍数据',haveAction_res.json()) #找到得拍拍品 paipin_url='http://m.test.hobay.com.cn/ribbon-api/orders/saveOrderForAuction?auctionOlBidId=1435' paipin_headers={'login': ''} paipin_res=HttpRequest().http_request(paipin_url,"get",headers=paipin_headers,cookies=login_res.cookies) print("得到订单id",paipin_res.json()) # #得拍者支付拍品 # order_url='http://m.test.hobay.com.cn/ribbon-api/orders/getOrder' # a = haveAction_res.json()['data']['result'][0]['orderId'] # print(a) # order_id={'orderId': a} # headers={'login': ''} # order_res=HttpRequest().http_request(order_url,'get',params=order_id,headers=headers,cookies=login_res.cookies) # print("订单详情",order_res.json()) #得拍者支付订单 zhifu_url="http://m.test.hobay.com.cn/ribbon-api/batchOrders/payAllCBP" zhifu_headers={'login': '','payPassword': '******'} b=paipin_res.json()['data']['tradeNum'] print(b) zhifu_data={"tradeNUm":b,"payType":3,"shareWalletUserId":"","shareWalletId":""} zhifu_res = HttpRequest().http_request(zhifu_url, 'post',json=zhifu_data, headers=zhifu_headers, cookies=login_res.cookies) print("支付成功", zhifu_res.json()) #卖家登录 login_seller_url = 'http://m.test.hobay.com.cn/api/app/user/login' # 登录 login_seller_data = {"loginValidateType": "CODE", "phone": seller_phone, "validateValue": "666666"} login_seller_res = HttpRequest().http_request(login_seller_url, "post", json=login_seller_data) print("登录结果是:", login_seller_res.json()) #销售订单列表接口 sales_url = 'http://m.test.hobay.com.cn/ribbon-api/batchOrders/queryPageOrders' # 登录 sales_data = {'orderStatus':0,'buyOrSell':2,'type':0,'currentPage':1,'pageSize':10} sales_headers={'login': ''} sales_res = HttpRequest().http_request(sales_url, "post", data=sales_data,headers=sales_headers,cookies=login_seller_res.cookies) # print("销售订单列表:", sales_res.json()) #立即发货 fahuo_url='http://m.test.hobay.com.cn/orders/sendProduct' buyer_userId= login_res.json()['userId'] orderId=paipin_res.json()['data']['orderId'] fahou_data={'orderId':orderId,'payType':3,'buyerUserId':buyer_userId,'type':1,'logisticsCompany':'德邦物流','companyNum':'debangwuliu','logisticsNum':'123456789'} fahuo_headers={'login': ''} fahuo_res=HttpRequest().http_request(fahuo_url,'post',data=fahou_data,headers=fahuo_headers,cookies=login_seller_res.cookies) print('卖家发货成功',fahuo_res.json()) # #买家登录点击采购订单 # buyer_url='http://m.test.hobay.com.cn/ribbon-api/batchOrders/queryPageOrders' # buyer_data= {'orderStatus':0,'buyOrSell':2,'type':0,'currentPage':1,'pageSize':10} # buyer_headers={'login': ''} # buyer_res=HttpRequest().http_request(buyer_url,'post',data=buyer_data,headers=buyer_headers,cookies=login_res.cookies) # # print('采购订单',buyer_res.json()) #确认收货 suer_url='http://m.test.hobay.com.cn/ribbon-api/orders/recieve' sellerUserId=login_seller_res.json()['userId'] suer_data={'orderId':orderId,'payType':3,'sellerUserId':sellerUserId} suer_headers={'login': '','payPassword': '******'} suer_res = HttpRequest().http_request(suer_url, 'post', data=suer_data, headers=suer_headers, cookies=login_res.cookies) print('确认收货订单', suer_res.json())
def parner(login_phone, input_phone, input_user_id): # 登录 global login_type login_url = 'http://m.test.hobay.com.cn/api/app/user/login' # 登录 login_data = { "loginValidateType": "CODE", "phone": login_phone, "validateValue": "666666" } login_res = HttpRequest().http_request(login_url, "post", json=login_data) print("登录结果是:", login_res.json()) # 伙伴列表类型 parner_type_url = "http://m.test.hobay.com.cn/api/user/partnership/getPartnerType" parner_typer_headers = {"login": ""} parner_type_res = HttpRequest().http_request(parner_type_url, "get", headers=parner_typer_headers, cookies=login_res.cookies) parner_type = parner_type_res.json()["partnerStyle"] if parner_type == "NORMAL" or parner_type == "ADVANCED" or parner_type == "ANGEL": login_type = "正式个人焕商" elif parner_type == "PERSON": login_type = "非正式焕商" elif parner_type == "AGENT": login_type = "区域焕商" print(f"登录的用户是:{login_type}") # 正式焕商正式伙伴/非正式伙伴/区域焕商 搜索伙伴 都是用这个接口 search_parner_url = f"http://m.test.hobay.com.cn/api/user/partnership/queryPageLittlePartner?name={input_phone}&pageSize=10&page=1" search_parner_headers = {"login": ""} search_parner_res = HttpRequest().http_request( search_parner_url, "get", headers=search_parner_headers, cookies=login_res.cookies) # print("我的伙伴-搜索伙伴的结果是:", search_parner_res.json()) parner_data = search_parner_res.json()["recordList"] # 查得出来就是绑定了,查不出来可能是待转正伙伴,也可能是没绑 if len(parner_data) == 1: print("搜索查询到了一条数据") if parner_data[0]["id"] == str(input_user_id): if login_type == "正式个人焕商" or login_type == "区域焕商": print(parner_data[0]["validDay"]) if parner_data[0]["validDay"] == None: print(f"{input_phone}已经和{login_phone}绑定,是他的正式伙伴") else: print("正式焕商的正式伙伴有绑定有效期,数据异常") elif login_type == "非正式焕商": if parner_data[0]["validDay"] != None: print(f"{input_phone}是{login_phone}的非正式伙伴") else: print("非正式焕商的伙伴没有绑定有效期,数据异常") else: print("搜索查询数据id对不上,数据异常") else: if login_type == "正式个人焕商": print(f"{input_phone}不是{login_phone}的正式伙伴") # 正式焕商待转正伙伴 search_parner2_url = f"http://m.test.hobay.com.cn/api/user/partnership/queryPartnerShipBack?name={input_phone}&pageSize=10&page=1" search_parner2_res = HttpRequest().http_request( search_parner2_url, "get", headers=search_parner_headers, cookies=login_res.cookies) print("我的伙伴-待转正伙伴-搜索伙伴的结果是:", search_parner2_res.json()) parner2_data = search_parner2_res.json()["recordList"] if len(parner2_data) == 1: if parner2_data[0]["id"] == int(input_user_id): if parner2_data[0]["validDay"] != None: print(f"{input_phone}是{login_phone}的待转正伙伴") else: print(f"数据异常") else: print("数据异常") else: print(f"{input_phone}没有和{login_phone}绑定") else: print(f"{input_phone}没有和{login_phone}绑定")
def buy_goods(buyer_phone, seller_phone, product_name, payType): # 卖家登录 seller_login_url = 'http://m.test.hobay.com.cn/api/app/user/login' # 登录 seller_login_data = {"loginValidateType": "CODE", "phone": seller_phone, "validateValue": "666666"} seller_login_res = HttpRequest().http_request(seller_login_url, "post", json=seller_login_data) print("卖家登录结果是:", seller_login_res.json()) # 获取商品productStockId # 卖家-商品管理 product_url = "http://m.test.hobay.com.cn/ribbon-api/product/queryPageProductsByType?currentPage=1&type=2&pageSize=10" product_headers = {"login": ""} product_res = HttpRequest().http_request(product_url, "get", headers=product_headers, cookies=seller_login_res.cookies) print("商品管理出售中的商品是:", product_res.json()) #获取商品规格id product_data = product_res.json()['data']['result'] for i in range(0, len(product_data)): if product_data[i]['title'] == product_name: productStockId = product_data[i]['productStockWithStockImages'][0]['id'] print("商品规格id是:", productStockId) # 买家登录 login_url = 'http://m.test.hobay.com.cn/api/app/user/login' # 登录 login_data = {"loginValidateType": "CODE", "phone": buyer_phone, "validateValue": "666666"} login_res = HttpRequest().http_request(login_url, "post", json=login_data) print("登录结果是:", login_res.json()) # 买家提交订单 SaveOrder_url = 'http://m.test.hobay.com.cn/ribbon-api/batchOrders/immediatelySaveOrder' SaveOrder_data = {"message": "", "couponUserId": "", "addressId": "", "productStockIdAndNums": [{"num": 1, "productStockId": productStockId}], "type": 3} SaveOrder_headers = {"login": ""} SaveOrder_res = HttpRequest().http_request(SaveOrder_url, "post", json=SaveOrder_data, cookies=login_res.cookies, headers=SaveOrder_headers) print("提交订单结果是:", SaveOrder_res.json()) # 买家支付订单 order = SaveOrder_res.json()['data']['tradeNum'] pay_url = "http://m.test.hobay.com.cn/ribbon-api/batchOrders/payAllCBP" pay_data = {"tradeNUm": order, "payType": payType, "shareWalletUserId": "", "shareWalletId": ""} pay_headers = {"login": "", "payPassword": "******"} pay_res = HttpRequest().http_request(pay_url, "post", json=pay_data, cookies=login_res.cookies, headers=pay_headers) print("支付订单的结果是:", pay_res.json()) print("订单编号", pay_res.json()['data']['orderNums'][0]) # 确认订单 orderId = SaveOrder_res.json()['data']['orderId'] AcceptOrder_url = f"http://m.test.hobay.com.cn/ribbon-api/orders/acceptOrder?orderId={orderId}" AcceptOrder_headers = {"login": ""} AcceptOrder_res = HttpRequest().http_request(AcceptOrder_url, "get", cookies=seller_login_res.cookies, headers=AcceptOrder_headers) print("确认订单的结果是:", AcceptOrder_res.json()) # 签约 sellerUserId = seller_login_res.json()['userId'] signed_url = f"http://m.test.hobay.com.cn/ribbon-api/orders/signed" data = {"orderId": orderId, "payType": payType, "sellerUserId": sellerUserId} headers = {"login": "", "payPassword": "******"} signed_res = HttpRequest().http_request(signed_url, "post", data=data, cookies=login_res.cookies, headers=headers) print("签约的结果是:", signed_res.json())
def input_user(login_phone, input_phone): # 登录 global login_type login_url = 'http://m.test.hobay.com.cn/api/app/user/login' # 登录 login_data = { "loginValidateType": "CODE", "phone": login_phone, "validateValue": "666666" } login_res = HttpRequest().http_request(login_url, "post", json=login_data) print("登录结果是:", login_res.json()) # 录入客户 input_data = { "area": "", "city": "", "company": "大", "detailedAddress": "", "headImage": "/group1/M00/07/AC/wKgAZV8zdWaAFK94AARVJeKqSr452!1280x959.jpeg", "name": "测试", "partnerStatus": 0, "phone": input_phone, "position": "", "province": "" } input_url = "http://m.test.hobay.com.cn/ribbon-api/customer/saveCustomer" headers = {"login": ""} input_res = HttpRequest().http_request( input_url, "post", json=input_data, cookies=login_res.cookies, headers=headers, ) print("录入客户的结果是:", input_res.json()) # 注册 register_url = "http://m.test.hobay.com.cn/api/app/user/register" register_data = { "code": "666666", "loginBindingType": "PHONE", "phone": input_phone } register_res = HttpRequest().http_request(register_url, "post", json=register_data, cookies=login_res.cookies, headers=headers) print("录入客户注册的结果是:", register_res.json()) register_id = register_res.json()["userId"] print("录入客户的user_id是:", register_id) # 完善资料 info_url = "http://m.test.hobay.com.cn/api/app/user/perfectUserInfo" info_data = { "country": "中国", "province": "青海省", "city": "西宁市", "area": "城中区" } info_res = HttpRequest().http_request(info_url, "post", json=info_data, cookies=register_res.cookies, headers=headers) print("录入客户完善资料的结果是:", info_res.json()) # 我的客户 MyCustomer_url = "http://m.test.hobay.com.cn/ribbon-api/customer/getQueryPageMyCustomer?status=¤tPage=1&pageSize=20" MyCustomer_headers = {"login": ""} MyCustomer_res = HttpRequest().http_request(MyCustomer_url, "get", headers=MyCustomer_headers, cookies=login_res.cookies) # print("我的客户中的客户有:", MyCustomer_res.json()) # 判断绑定的我的客户是否激活 MyCustome_data = MyCustomer_res.json()["data"]['result'] for i in range(len(MyCustome_data)): if MyCustome_data[i]["phone"] == str(input_phone): partnerStatus = MyCustome_data[i]["partnerStatus"] if partnerStatus == 1: print(f"{input_phone}激活成功") else: print(f"{input_phone}激活失败,partnerStatus={partnerStatus}") break return register_id
def bug_goods(buyer_phone, seller_phone, product_name, payPassword, payType): # 卖家登录 login_url = 'http://m.test.hobay.com.cn/api/app/user/login' # 登录 seller_login_data = {"loginValidateType": "CODE", "phone": seller_phone, "validateValue": "666666"} seller_login_res = HttpRequest().http_request(login_url, "post", json=seller_login_data) print("登录结果是:", seller_login_res.json()) # 获取商品productStockId # 卖家-商品管理 product_url = "http://m.test.hobay.com.cn/ribbon-api/product/queryPageProductsByType?currentPage=1&type=2&pageSize=10" product_headers = {"login": ""} product_res = HttpRequest().http_request(product_url, "get", headers=product_headers, cookies=seller_login_res.cookies) # print("商品管理出售中的商品是:", product_res.json()) # 获取商品规格id product_data = product_res.json()['data']['result'] for i in range(0, len(product_data)): if product_data[i]['title'] == product_name: productStockId = product_data[i]['productStockWithStockImages'][0]['id'] print("商品规格id是:", productStockId) # 买家登录 buyer_login_data = {"loginValidateType": "CODE", "phone": buyer_phone, "validateValue": "666666"} buyer_login_res = HttpRequest().http_request(login_url, "post", json=buyer_login_data) print("登录结果是:", buyer_login_res.json()) # 获取收货地址 address_url = "http://m.test.hobay.com.cn/api/user/graphql/flat" address_data = { "query": "query currentUser{\n currentUser{\n receiveAddress(page:1,pageSize:100){\n numPerPage\n pageNum\n totalCount\n totalPage\n recordList{\n id\n name\n provinceName\n cityName\n areaName\n detailAddress\n phone\n default\n }\n }\n }\n }"} address_headers = {"login": ""} address_res = HttpRequest().http_request(address_url, 'post', json=address_data, cookies=buyer_login_res.cookies, headers=address_headers) print("获取收货地址的结果是:", address_res.json()) # 提交订单 addressId = address_res.json()['currentUser_receiveAddress_recordList'][0]['id'] SaveOrder_url = 'http://m.test.hobay.com.cn/ribbon-api/batchOrders/immediatelySaveOrder' SaveOrder_data = {"message": "", "couponUserId": "", "addressId": addressId, "productStockIdAndNums": [{"num": 1, "productStockId": productStockId}], "type": 1} SaveOrder_headers = {"login": ""} SaveOrder_res = HttpRequest().http_request(SaveOrder_url, "post", json=SaveOrder_data, cookies=buyer_login_res.cookies, headers=SaveOrder_headers) print("提交订单结果是:", SaveOrder_res.json()) # 支付订单 orderNum = SaveOrder_res.json()['data']['orderNum'] pay_url = "http://m.test.hobay.com.cn/ribbon-api/batchOrders/payAllCBP" pay_data = {"tradeNUm": orderNum, "payType": payType, "shareWalletUserId": "", "shareWalletId": ""} pay_headers = {"login": "", "payPassword": payPassword} pay_res = HttpRequest().http_request(pay_url, "post", json=pay_data, cookies=buyer_login_res.cookies, headers=pay_headers) print("支付订单的结果是:", pay_res.json()) # 确认订单 orderId = SaveOrder_res.json()['data']['orderId'] order_data = {'orderStatus': 0, 'buyOrSell': 2, 'type': 0, 'currentPage': 1, 'pageSize': 10} AcceptOrder_url = f"http://m.test.hobay.com.cn/ribbon-api/orders/acceptOrder?orderId={orderId}" AcceptOrder_headers = {"login": ""} AcceptOrder_res = HttpRequest().http_request(AcceptOrder_url, "get", json=order_data, cookies=seller_login_res.cookies, headers=AcceptOrder_headers) print("确认订单的结果是:", AcceptOrder_res.json()) # 发货 ship_url = 'http://m.test.hobay.com.cn/orders/sendProduct' buyer_userId = seller_login_res.json()['userId'] ship_data = {'orderId': orderId, 'payType': payType, 'buyerUserId': buyer_userId, 'type': 1, 'logisticsCompany': '德邦物流', 'companyNum': 'debangwuliu', 'logisticsNum': '123456789'} ship_headers = {'login': ''} ship_res = HttpRequest().http_request(ship_url, 'post', data=ship_data, headers=ship_headers, cookies=seller_login_res.cookies) print('卖家发货的结果是:', ship_res.json()) # 确认收货 suer_url = 'http://m.test.hobay.com.cn/ribbon-api/orders/recieve' sellerUserId = seller_login_res.json()['userId'] suer_data = {'orderId': orderId, 'payType': payType, 'sellerUserId': sellerUserId} suer_headers = {'login': '', 'payPassword': payPassword} suer_res = HttpRequest().http_request(suer_url, 'post', data=suer_data, headers=suer_headers, cookies=buyer_login_res.cookies) print('确认收货的结果是:', suer_res.json())
"""client""" import socket import json from http_request import HttpRequest import time import datetime sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', 8081)) print("CLIENT IS RUNNING\n") urls = ["https://mail.ru", "https://google.com", "https://yandex.ru"] * 10 http_request = HttpRequest(host='localhost', port=8080, method="GET", data=urls) sock.sendall(http_request.request) start_time = datetime.datetime.now() while True: encode_data = sock.recv(2048 * 100) data = encode_data.decode("utf-8") # data = json.loads(encode_data.decode("utf-8")) print(f"{data}\n") sock.close() print("\nCLIENT SHUT DOWN")
def bug_goods(buyer_phone, seller_phone, product_name, payType): # 卖家登录 login_url = 'http://m.test.hobay.com.cn/api/app/user/login' # 登录 seller_login_data = { "loginValidateType": "CODE", "phone": seller_phone, "validateValue": "666666" } seller_login_res = HttpRequest().http_request(login_url, "post", json=seller_login_data) print("登录结果是:", seller_login_res.json()) # 获取商品productStockId # 卖家-商品管理 product_url = "http://m.test.hobay.com.cn/ribbon-api/product/queryPageProductsByType?currentPage=1&type=2&pageSize=10" product_headers = {"login": ""} product_res = HttpRequest().http_request(product_url, "get", headers=product_headers, cookies=seller_login_res.cookies) # print("商品管理出售中的商品是:", product_res.json()) # 获取商品规格id product_data = product_res.json()['data']['result'] for i in range(0, len(product_data)): if product_data[i]['title'] == product_name: productStockId = product_data[i]['productStockWithStockImages'][0][ 'id'] print("商品规格id是:", productStockId) # 买家登录 buyer_login_data = { "loginValidateType": "CODE", "phone": buyer_phone, "validateValue": "666666" } buyer_login_res = HttpRequest().http_request(login_url, "post", json=buyer_login_data) print("登录结果是:", buyer_login_res.json()) # 获取收货地址 address_url = "http://m.test.hobay.com.cn/api/user/graphql/flat" address_data = { "query": "query currentUser{\n currentUser{\n receiveAddress(page:1,pageSize:100){\n numPerPage\n pageNum\n totalCount\n totalPage\n recordList{\n id\n name\n provinceName\n cityName\n areaName\n detailAddress\n phone\n default\n }\n }\n }\n }" } address_headers = {"login": ""} address_res = HttpRequest().http_request(address_url, 'post', json=address_data, cookies=buyer_login_res.cookies, headers=address_headers) print("获取收货地址的结果是:", address_res.json()) # 提交订单 SaveOrder_url = 'http://m.test.hobay.com.cn/ribbon-api/batchOrders/immediatelySaveOrder' SaveOrder_data = { "message": "", "couponUserId": "", "addressId": "", "productStockIdAndNums": [{ "num": 1, "productStockId": productStockId }], "type": 2 } SaveOrder_headers = {"login": ""} SaveOrder_res = HttpRequest().http_request(SaveOrder_url, "post", json=SaveOrder_data, cookies=buyer_login_res.cookies, headers=SaveOrder_headers) print("提交订单结果是:", SaveOrder_res.json()) # 支付订单 orderNum = SaveOrder_res.json()['data']['orderNum'] pay_url = "http://m.test.hobay.com.cn/ribbon-api/batchOrders/payAllCBP" pay_data = { "tradeNUm": orderNum, "payType": payType, "shareWalletUserId": "", "shareWalletId": "" } pay_headers = {"login": "", "payPassword": "******"} pay_res = HttpRequest().http_request(pay_url, "post", json=pay_data, cookies=buyer_login_res.cookies, headers=pay_headers) print("支付订单的结果是:", pay_res.json()) # 卖家确认订单 orderId = SaveOrder_res.json()['data']['orderId'] order_data = { 'orderStatus': 0, 'buyOrSell': 2, 'type': 0, 'currentPage': 1, 'pageSize': 10 } AcceptOrder_url = f"http://m.test.hobay.com.cn/ribbon-api/orders/acceptOrder?orderId={orderId}" AcceptOrder_headers = {"login": ""} AcceptOrder_res = HttpRequest().http_request( AcceptOrder_url, "get", json=order_data, cookies=seller_login_res.cookies, headers=AcceptOrder_headers) print("确认订单的结果是:", AcceptOrder_res.json()) # 获取买家订单序列号 print(orderId) OrderDetail_url = 'http://m.test.hobay.com.cn/ribbon-api/batchOrders/queryOrderDetail' OrderDetail_data = {"orderId": orderId, "buyOrSell": 1} OrderDetail_headers = {'login': ''} OrderDetail_res = HttpRequest().http_request( OrderDetail_url, 'post', data=OrderDetail_data, headers=OrderDetail_headers, cookies=buyer_login_res.cookies) print('获取买家订单序列号的结果是:', OrderDetail_res.json()) qrCode = OrderDetail_res.json()['data']['qrCode'] # print("买家订单序列号是:", qrCode) # 卖家确认序列号 consume_url = 'http://m.test.hobay.com.cn/ribbon-api/orders/consume' buyerUserId = buyer_login_res.json()['userId'] consume_data = { "orderId": orderId, "payType": payType, "buyerUserId": buyerUserId, "qrCode": qrCode } consume_headers = {'login': '', 'payPassword': '******'} consume_res = HttpRequest().http_request(consume_url, 'post', data=consume_data, headers=consume_headers, cookies=seller_login_res.cookies) print('确认收货的结果是:', consume_res.json())
def get_5min_data_by_day(day_before_today): url = f"https://web-api.coinmarketcap.com/v1.1/cryptocurrency/quotes/historical?convert=USD,BTC&format=chart_crypto_details&id=74&interval=15m&time_end={int(time.time()) - day_before_today * 86400}&time_start={int(time.time()) - (day_before_today + 1) * 86400}" http = HttpRequest() print(url) r = http.get(url) return DogeLinks.parse_5min_data(r.text)
while runflag: try: confd, addr = lisfd.accept() except socket.error as e: if e.errno == errno.EINTR: print 'get a except EINTR' else: print 'get a error', e.errno raise continue if runflag == False: break print "connect by ", addr data = confd.recv(1024) if not data: break print "receve >>>>", data, "<<<<<" http_request.request = HttpRequest(data) print http_request.request.method, http_request.request.path, http_request.request.params confd.send(response.get_response()) #confd.send(HttpResponse(httpheader,'index.html')) confd.close() else: print 'runflag#', runflag lisfd.shutdown(socket.SHUT_RD) print 'Done'
class Runner(object): """ Running testcases. Examples: >>> functions={...} >>> config = { "name": "XXXX", "base_url": "http://127.0.0.1", "verify": False } >>> runner = Runner(config, functions,http_client_session=None) >>> test_dict = { "name": "test description", "variables": [], # optional "request": { "url": "http://127.0.0.1:5000/api/users/1000", "method": "GET" } } >>> runner.run_test(test_dict) """ def __init__(self, config, functions): """ run testcase or testsuite. Args: config (dict): testcase/testsuite config dict { "name": "ABC", "variables": {}, "setup_hooks", [], "teardown_hooks", [] } http_client_session (instance): requests.Session() """ base_url = config.get("base_url") self.verify = config.get("verify", True) self.output = config.get("output", []) self.functions = functions self.validation_results = [] # testcase setup hooks testcase_setup_hooks = config.get("setup_hooks", []) # testcase teardown hooks self.testcase_teardown_hooks = config.get("teardown_hooks", []) self.http_client_session = HttpRequest(base_url) self.session_context = SessionContext(self.functions) if testcase_setup_hooks: self.do_hook_actions(testcase_setup_hooks, "setup") def __del__(self): if self.testcase_teardown_hooks: self.do_hook_actions(self.testcase_teardown_hooks, "teardown") def __clear_test_data(self): """ clear request and response data """ self.validation_results = [] self.http_client_session.init_case_data() def __get_test_data(self): """ get request/response data and validate results """ meta_data = self.http_client_session.init_data meta_data["validators"] = self.validation_results return meta_data def _handle_skip_feature(self, test_dict): """ handle skip feature for test - skip: skip current test unconditionally - skipIf: skip current test if condition is true - skipUnless: skip current test unless condition is true Args: test_dict (dict): test info Raises: SkipTest: skip test """ # TODO: move skip to initialize skip_reason = None if "skip" in test_dict: skip_reason = test_dict["skip"] elif "skipIf" in test_dict: skip_if_condition = test_dict["skipIf"] if self.session_context.eval_content(skip_if_condition): skip_reason = "{} evaluate to True".format(skip_if_condition) elif "skipUnless" in test_dict: skip_unless_condition = test_dict["skipUnless"] if not self.session_context.eval_content(skip_unless_condition): skip_reason = "{} evaluate to False".format( skip_unless_condition) if skip_reason: raise SkipTest(skip_reason) def do_hook_actions(self, actions, hook_type): """ call hook actions. Args: actions (list): each action in actions list maybe in two format. format1 (dict): assignment, the value returned by hook function will be assigned to variable. {"var": "${func()}"} format2 (str): only call hook functions. ${func()} hook_type (enum): setup/teardown """ logger.debug("call {} hook actions.".format(hook_type)) for action in actions: if isinstance(action, dict) and len(action) == 1: # format 1 # {"var": "${func()}"} var_name, hook_content = list(action.items())[0] logger.debug("assignment with hook: {} = {}".format( var_name, hook_content)) self.session_context.update_test_variables( var_name, self.session_context.eval_content(hook_content)) else: # format 2 logger.debug("call hook function: {}".format(action)) # TODO: check hook function if valid self.session_context.eval_content(action) def _run_test(self, test_dict): """ run single teststep. Args: test_dict (dict): teststep info { "name": "teststep description", "skip": "skip this test unconditionally", "times": 3, "variables": [], # optional, override "request": { "url": "http://127.0.0.1:5000/api/users/1000", "method": "POST", "headers": { "Content-Type": "application/json", "authorization": "$authorization", "random": "$random" }, "json": {"name": "user", "password": "******"} }, "extract": {}, # optional "validate": [], # optional "setup_hooks": [], # optional "teardown_hooks": [] # optional } Raises: exceptions.ParamsError exceptions.ValidationFailure exceptions.ExtractFailure """ # clear meta data first to ensure independence for each test self.__clear_test_data() # check skip self._handle_skip_feature(test_dict) # prepare test_dict = lower_test_dict_keys(test_dict) test_variables = test_dict.get("variables", {}) self.session_context.init_test_variables(test_variables) # teststep name test_name = test_dict.get("name", "") # parse test request raw_request = test_dict.get('request', {}) parsed_test_request = self.session_context.eval_content(raw_request) self.session_context.update_test_variables("request", parsed_test_request) # setup hooks setup_hooks = test_dict.get("setup_hooks", []) if setup_hooks: self.do_hook_actions(setup_hooks, "setup") try: url = parsed_test_request.pop('url') method = parsed_test_request.pop('method') parsed_test_request.setdefault("verify", self.verify) group_name = parsed_test_request.pop("group", None) except KeyError: raise exceptions.ParamsError("URL or METHOD missed!") # TODO: move method validation to json schema valid_methods = [ "GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS" ] if method.upper() not in valid_methods: err_msg = u"Invalid HTTP method! => {}\n".format(method) err_msg += "Available HTTP methods: {}".format( "/".join(valid_methods)) logger.log_error(err_msg) raise exceptions.ParamsError(err_msg) logger.log_info("{method} {url}".format(method=method, url=url)) logger.debug( "request kwargs(raw): {kwargs}".format(kwargs=parsed_test_request)) # request resp = self.http_client_session.request(method, url, name=(group_name or test_name), **parsed_test_request) resp_obj = response.ResponseObject(resp) # teardown hooks teardown_hooks = test_dict.get("teardown_hooks", []) if teardown_hooks: self.session_context.update_test_variables("response", resp_obj) self.do_hook_actions(teardown_hooks, "teardown") # extract extractors = test_dict.get("extract", {}) extracted_variables_mapping = resp_obj.extract_response(extractors) self.session_context.update_session_variables( extracted_variables_mapping) # validate validators = test_dict.get("validate", []) try: self.session_context.validate(validators, resp_obj) except (exceptions.ParamsError, exceptions.ValidationFailure, exceptions.ExtractFailure): err_msg = "{} DETAILED REQUEST & RESPONSE {}\n".format( "*" * 32, "*" * 32) # log request err_msg += "====== request details ======\n" err_msg += "url: {}\n".format(url) err_msg += "method: {}\n".format(method) err_msg += "headers: {}\n".format( parsed_test_request.pop("headers", {})) for k, v in parsed_test_request.items(): v = omit_long_data(v) err_msg += "{}: {}\n".format(k, repr(v)) err_msg += "\n" # log response err_msg += "====== response details ======\n" err_msg += "status_code: {}\n".format(resp_obj.status_code) err_msg += "headers: {}\n".format(resp_obj.headers) err_msg += "body: {}\n".format(repr(resp_obj.text)) logger.log_error(err_msg) raise finally: self.validation_results = self.session_context.validation_results def _run_testcase(self, testcase_dict): """ run single testcase. """ self.meta_datas = [] config = testcase_dict.get("config", {}) base_url = config.get("base_url") # each testcase should have individual session. http_client_session = self.http_client_session.__class__(base_url) test_runner = Runner(config, self.functions, http_client_session) tests = testcase_dict.get("teststeps", []) for index, test_dict in enumerate(tests): try: test_runner.run_test(test_dict) except Exception: # log exception request_type and name for locust stat self.exception_request_type = test_runner.exception_request_type self.exception_name = test_runner.exception_name raise finally: _meta_datas = test_runner.meta_datas self.meta_datas.append(_meta_datas) self.session_context.update_session_variables( test_runner.extract_sessions()) def run_test(self, test_dict): """ run single teststep of testcase. test_dict may be in 3 types. Args: test_dict (dict): # teststep { "name": "teststep description", "variables": [], # optional "request": { "url": "http://127.0.0.1:5000/api/users/1000", "method": "GET" } } # nested testcase { "config": {...}, "teststeps": [ {...}, {...} ] } # TODO: function { "name": "exec function", "function": "${func()}" } """ self.meta_datas = None if "teststeps" in test_dict: # nested testcase self._run_testcase(test_dict) else: # api try: self._run_test(test_dict) except Exception: # log exception request_type and name for locust stat self.exception_request_type = test_dict["request"]["method"] self.exception_name = test_dict.get("name") raise finally: self.meta_datas = self.__get_test_data() def extract_sessions(self): """ """ return self.extract_output(self.output) def extract_output(self, output_variables_list): """ extract output variables """ variables_mapping = self.session_context.session_variables_mapping output = {} for variable in output_variables_list: if variable not in variables_mapping: logger.log_warning( "variable '{}' can not be found in variables mapping, failed to output!"\ .format(variable) ) continue output[variable] = variables_mapping[variable] return output
def __init__(self, uri, port): self.rule_engine_uri = uri self.rule_engine_port = port HttpRequest.__init__(self, uri + ':' + port)
def auction(buyer_phone, seller_phone, start_time, end_time, goods_name="7025发布自留拍品,立即成交,生成订单,支付,不完成交易,退保证金时间"): # 卖家登录 login_url = 'http://m.test.hobay.com.cn/api/app/user/login' # 登录 login_data = { "loginValidateType": "CODE", "phone": seller_phone, "validateValue": "666666" } login_res = HttpRequest().http_request(login_url, "post", json=login_data) print("登录结果是:", login_res.json()) # 发布拍品 SaveOrder_url = 'http://m.test.hobay.com.cn/ribbon-api/auctionOlBid/publishAuction' SaveOrder_data = { "productImg": ["/group1/M00/07/B8/wKgAZl8fhxaASFpSAAF7g0bXYPA38!546x546.jpeg"], "name": goods_name, "price": 1, "securityPayment": 1, "scope": 1, "normalPrice": "", "categoryId": 101, "categoryName": "电视", "description": "111", "imgList": [], "firstCategory": 1 } SaveOrder_headers = {"login": ""} SaveOrder_res = HttpRequest().http_request(SaveOrder_url, "post", json=SaveOrder_data, cookies=login_res.cookies, headers=SaveOrder_headers) print("发布拍品结果是:", SaveOrder_res.json()) # operate登录 login2_url = 'http://operate.test.hobay.com.cn/adminuser/userLogin' # 登录 login2_data = { "__RequestVerificationToken": "fkfh8D89BFqTdrE2iiSdG_L781RSRtdWOH411poVUWhxzA5MzI8es07g6KPYQh9Log-xf84pIR2RIAEkOokZL3Ee3UKmX0Jc8bW8jOdhqo81", "username": "******", "password": 123, "rememberMe": "true" } login2_res = HttpRequest().http_request(login2_url, "post", data=login2_data) print("operate登录结果是:", login2_res.json()) # 审核拍品 data_id = SaveOrder_res.json()['data'] preBeginTime = getTime(start_time) preEndTime = getTime(end_time) url = 'http://operate.test.hobay.com.cn/auctionolproduct/passCheckNew' # 登录 data = { "id": data_id, "applyNum": "0", "preBeginTime": preBeginTime, "preEndTime": preEndTime, "browserBaseNum": "0", "categoryName": "电视", "description": "111", "name": goods_name, "normalPrice": "0.00", "price": "1.00", "saleablePhone": "", "unsaleable": "-1", "scope": "1.00", "securityPayment": "1.00", "firstCategory": "1", "categoryId": "101", "checkNote": "", "images": ["/group1/M00/07/B8/wKgAZl8fhxaASFpSAAF7g0bXYPA38!546x546.jpeg"], "detailImages": [] } res = HttpRequest().http_request(url, "post", json=data, cookies=login2_res.cookies) print("审核拍品的结果是:", res.json()) # 卖家设置开拍时间 signed_url = "http://m.test.hobay.com.cn/ribbon-api/auctionOlBid/starAuction" data = { "starTime": preBeginTime + 60000, "endTime": preEndTime - 60000, "auctionProductId": data_id } headers = {"login": ""} signed_res = HttpRequest().http_request(signed_url, "post", data=data, cookies=login_res.cookies, headers=headers) print("卖家设置开拍时间的结果是:", signed_res.json()) # 参与者登录 login3_url = 'http://m.test.hobay.com.cn/api/app/user/login' # 登录 login3_data = { "loginValidateType": "CODE", "phone": buyer_phone, "validateValue": "666666" } login3_res = HttpRequest().http_request(login3_url, "post", json=login3_data) print("参与者登录结果是:", login3_res.json()) # 获取收货地址 address_url = "http://m.test.hobay.com.cn/api/user/graphql/flat" address_data = { "query": "query currentUser{\n currentUser{\n receiveAddress(page:1,pageSize:100){\n numPerPage\n pageNum\n totalCount\n totalPage\n recordList{\n id\n name\n provinceName\n cityName\n areaName\n detailAddress\n phone\n default\n }\n }\n }\n }" } address_headers = {"login": ""} address_res = HttpRequest().http_request(address_url, 'post', json=address_data, cookies=login3_res.cookies, headers=address_headers) print("获取收货地址的结果是:", address_res.json()) # 提交订单 addressId = address_res.json( )['currentUser_receiveAddress_recordList'][0]['id'] SaveOrder_url = "http://m.test.hobay.com.cn/ribbon-api/auctionOlProduct/enrollAndPay" SaveOrder_data = { "auctionOlProductId": data_id, "receivingAddressId": addressId } SaveOrder_headers = {"login": ""} SaveOrder_res = HttpRequest().http_request(SaveOrder_url, "post", data=SaveOrder_data, cookies=login3_res.cookies, headers=SaveOrder_headers) print("报名提交订单结果是:", SaveOrder_res.json()) # 报名支付 order = SaveOrder_res.json()['data']['tradeNum'] pay_url = "http://m.test.hobay.com.cn/ribbon-api/pay/payCash" pay_data = {"tradeNum": order} pay_headers = {"login": "", "payPassword": "******"} pay_res = HttpRequest().http_request(pay_url, "post", data=pay_data, cookies=login3_res.cookies, headers=pay_headers) print("报名支付订单的结果是:", pay_res.json()) # 出价 time.sleep(5) chujia_url = "http://m.test.hobay.com.cn/ribbon-api/auctionOlBid/bidPrice" chujia_data = {"bidPrice": 2, "auctionOlProductId": data_id} chujia_headers = {"login": ""} chujia_res = HttpRequest().http_request(chujia_url, "post", data=chujia_data, cookies=login3_res.cookies, headers=chujia_headers) print("出价的结果是:", chujia_res.json()) # 出价排行接口 paihang_url = 'http://m.test.hobay.com.cn/ribbon-api/auctionOlBid/no_get5AuctionOlBids' paihang_data = {'auctionOlProductId': data_id} paihang_headers = {'login': ''} paihang_res = HttpRequest().http_request(paihang_url, "get", params=paihang_data, headers=paihang_headers, cookies=login3_res.cookies) print("出价排行榜", paihang_res.json())
def auction(buyer_phone, seller_phone, start_time, end_time, payPassword, goods_name="发布拍品用"): # 卖家登录 seller_login_url = 'http://m.test.hobay.com.cn/api/app/user/login' # 登录 seller_login_data = { "loginValidateType": "CODE", "phone": seller_phone, "validateValue": "666666" } seller_login_res = HttpRequest().http_request(seller_login_url, "post", json=seller_login_data) print("登录结果是:", seller_login_res.json()) # 发布拍品 SaveOrder_url = 'http://m.test.hobay.com.cn/ribbon-api/auctionOlBid/publishAuction' SaveOrder_data = { "productImg": ["/group1/M00/07/B8/wKgAZl8fhxaASFpSAAF7g0bXYPA38!546x546.jpeg"], "name": goods_name, "price": 1, "securityPayment": 1, "scope": 1, "normalPrice": "", "categoryId": 101, "categoryName": "电视", "description": "111", "imgList": [], "firstCategory": 1 } SaveOrder_headers = {"login": ""} SaveOrder_res = HttpRequest().http_request( SaveOrder_url, "post", json=SaveOrder_data, cookies=seller_login_res.cookies, headers=SaveOrder_headers) print("发布拍品结果是:", SaveOrder_res.json()) # operate登录 operate_url = 'http://operate.test.hobay.com.cn/adminuser/userLogin' # 登录 operate_data = { "__RequestVerificationToken": "fkfh8D89BFqTdrE2iiSdG_L781RSRtdWOH411poVUWhxzA5MzI8es07g6KPYQh9Log-xf84pIR2RIAEkOokZL3Ee3UKmX0Jc8bW8jOdhqo81", "username": "******", "password": 123, "rememberMe": "true" } operate_res = HttpRequest().http_request(operate_url, "post", data=operate_data) print("operate登录结果是:", operate_res.json()) # 审核拍品 data_id = SaveOrder_res.json()['data'] preBeginTime = getTime(start_time) preEndTime = getTime(end_time) url = 'http://operate.test.hobay.com.cn/auctionolproduct/passCheckNew' # 登录 data = { "id": data_id, "saleablePhones": [""], "applyNum": "0", "preBeginTime": preBeginTime, "preEndTime": preEndTime, "browserBaseNum": "0", "remindNum": "0", "categoryName": "电视", "description": "111", "name": goods_name, "normalPrice": "0.00", "price": "1.00", "saleablePhone": "", "unsaleable": "-1", "scope": "1.00", "securityPayment": "1.00", "firstCategory": "1", "categoryId": "101", "checkNote": "", "images": ["/group1/M00/07/A5/wKgAZV8sxDuAbS2cAAD-_goQPAc283!512x150.png"], "detailImages": [] } res = HttpRequest().http_request(url, "post", json=data, cookies=operate_res.cookies) print("审核拍品的结果是:", res.json()) # 卖家设置开拍时间 signed_url = "http://m.test.hobay.com.cn/ribbon-api/auctionOlBid/starAuction" data = { "starTime": preBeginTime + 10000, "endTime": preEndTime - 60000, "auctionProductId": data_id } headers = {"login": ""} signed_res = HttpRequest().http_request(signed_url, "post", data=data, cookies=seller_login_res.cookies, headers=headers) print("卖家设置开拍时间的结果是:", signed_res.json()) # 参与者登录 buyer_login_url = 'http://m.test.hobay.com.cn/api/app/user/login' # 登录 buyer_login_data = { "loginValidateType": "CODE", "phone": buyer_phone, "validateValue": "666666" } buyer_login_res = HttpRequest().http_request(buyer_login_url, "post", json=buyer_login_data) print("参与者登录结果是:", buyer_login_res.json()) # 获取收货地址 address_url = "http://m.test.hobay.com.cn/api/user/graphql/flat" address_data = { "query": "query currentUser{\n currentUser{\n receiveAddress(page:1,pageSize:100){\n numPerPage\n pageNum\n totalCount\n totalPage\n recordList{\n id\n name\n provinceName\n cityName\n areaName\n detailAddress\n phone\n default\n }\n }\n }\n }" } address_headers = {"login": ""} address_res = HttpRequest().http_request(address_url, 'post', json=address_data, cookies=buyer_login_res.cookies, headers=address_headers) print("获取收货地址的结果是:", address_res.json()) # 提交订单 addressId = address_res.json( )['currentUser_receiveAddress_recordList'][0]['id'] SaveOrder_url = "http://m.test.hobay.com.cn/ribbon-api/auctionOlProduct/enrollAndPay" SaveOrder_data = { "auctionOlProductId": data_id, "receivingAddressId": addressId } SaveOrder_headers = {"login": ""} SaveOrder_res = HttpRequest().http_request(SaveOrder_url, "post", data=SaveOrder_data, cookies=buyer_login_res.cookies, headers=SaveOrder_headers) print("提交订单结果是:", SaveOrder_res.json()) # 报名支付 sign_up_order = SaveOrder_res.json()['data']['tradeNum'] sign_up_pay_url = "http://m.test.hobay.com.cn/ribbon-api/pay/payCash" sign_up_pay_data = {"tradeNum": sign_up_order} sign_up_pay_headers = {"login": "", "payPassword": payPassword} sign_up_pay_res = HttpRequest().http_request( sign_up_pay_url, "post", data=sign_up_pay_data, cookies=buyer_login_res.cookies, headers=sign_up_pay_headers) print("支付订单的结果是:", sign_up_pay_res.json()) # 出价 chujia_url = "http://m.test.hobay.com.cn/ribbon-api/auctionOlBid/bidPrice" chujia_data = {"bidPrice": 2, "auctionOlProductId": data_id} chujia_headers = {"login": ""} chujia_res = HttpRequest().http_request(chujia_url, "post", data=chujia_data, cookies=buyer_login_res.cookies, headers=chujia_headers) print("出价的结果是:", chujia_res.json()) # 发起者立即成交 click_url = f"http://m.test.hobay.com.cn/ribbon-api/auctionOlBid/no_get5AuctionOlBids?auctionOlProductId={data_id}" click_headers = {"login": ""} click_res = HttpRequest().http_request(click_url, "get", cookies=seller_login_res.cookies, headers=click_headers) print("点击立即成交的结果是:", click_res.json()) auctionOlBidId = click_res.json()["data"][0]["id"] liji_url = f"http://m.test.hobay.com.cn/ribbon-api/orders/saveOrderForAuction?auctionOlBidId={auctionOlBidId}" liji_headers = {"login": ""} liji_res = HttpRequest().http_request(liji_url, "get", cookies=seller_login_res.cookies, headers=liji_headers) print("立即成交的结果是:", liji_res.json()) # 得拍者拍品支付 pay_order = liji_res.json()['data']['tradeNum'] pay_order_url = "http://m.test.hobay.com.cn/ribbon-api/batchOrders/payAllCBP" pay_order_data = { "tradeNUm": pay_order, "payType": 3, "shareWalletUserId": "", "shareWalletId": "" } pay_order_headers = {"login": "", "payPassword": payPassword} pay_order_res = HttpRequest().http_request(pay_order_url, "post", json=pay_order_data, cookies=buyer_login_res.cookies, headers=pay_order_headers) print("得拍者支付订单的结果是:", pay_order_res.json()) # 发起人立即发货 fahuo_url = 'http://m.test.hobay.com.cn/orders/sendProduct' seller_userId = seller_login_res.json()['userId'] fahou_data = { 'orderId': data_id, 'payType': 3, 'buyerUserId': seller_userId, 'type': 1, 'logisticsCompany': '德邦物流', 'companyNum': 'debangwuliu', 'logisticsNum': '123456789' } fahuo_headers = {'login': ''} fahuo_res = HttpRequest().http_request(fahuo_url, 'post', data=fahou_data, headers=fahuo_headers, cookies=seller_login_res.cookies) print('卖家发货成功', fahuo_res.json()) # 得拍者确认收货 orderId = pay_order_res.json()["data"]["orderId"] buyer_url = 'http://m.test.hobay.com.cn/ribbon-api/orders/recieve' buyer_UserId = seller_login_res.json()['userId'] buyer_data = { 'orderId': orderId, 'payType': 3, 'sellerUserId': buyer_UserId } buyer_headers = {'login': '', 'payPassword': payPassword} buyer_res = HttpRequest().http_request(buyer_url, 'post', data=buyer_data, headers=buyer_headers, cookies=buyer_login_res.cookies) print("得拍者确认收货的结果是:", buyer_res)