Best Python code snippet using playwright-python
service.py
Source:service.py
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3# @Time : 2018/5/24 0024 14:164# @Author : Hadrianl5# @File : service.py6# @Contact : 137150224@qq.com7from . import utils as u8from .utils import logger, api_key_get, api_key_post, http_get_request, setUrl, setKey, Singleton9from .utils import DEFAULT_URL, DEFAULT_DM_URL10from dateutil import parser11# from functools import wraps12import datetime as dt13from .core import _AuthWS, _HBWS, _DerivativesAuthWS, _HBDerivativesWS14import warnings15logger.debug(f'<TESTING>LOG_TESTING')16def HBWebsocket(host='api.huobi.br.com', auth=False, isDerivatives=False, reconn=10, interval=3):17 if not isDerivatives:18 if auth:19 return _AuthWS(host, reconn, interval)20 else:21 return _HBWS(host, reconn, interval)22 else:23 if auth:24 return _DerivativesAuthWS(host, reconn, interval)25 else:26 return _HBDerivativesWS(host, reconn, interval)27class HBRestAPI(metaclass=Singleton):28 def __init__(self, url=None, keys=None, get_acc=False):29 """30 ç«å¸REST APIå°è£
31 :param url: ä¼ å
¥urlï¼è¥ä¸ºNoneï¼é»è®¤æ¯https://api.huobi.br.com32 :param keys: ä¼ å
¥(acess_key, secret_key),å¯ç¨setKey设置33 """34 self.url = url if url else DEFAULT_URL35 if keys:36 setKey(*keys)37 if get_acc:38 try:39 accounts = self.get_accounts()['data']40 self.acc_id = self.get_accounts()['data'][0]['id']41 if len(accounts) > 1:42 warnings.warn(f'é»è®¤è®¾ç½®acc_id为{self.acc_id}')43 except Exception as e:44 raise Exception(f'Failed to get account: key may not be set ->{e}')45 def set_acc_id(self, acc_id):46 self.acc_id = acc_id47 def __async_request_exception_handler(self, req, e):48 logger.error(f'async_request:{req}--exception:{e}')49 def async_request(self, reqs:list)->list:50 """51 å¼æ¥å¹¶å请æ±52 :param reqs: 请æ±å表53 :return:54 """55 result = (response.result() for response in reqs)56 ret = [r.json() if r.status_code == 200 else None for r in result]57 return ret58 def get_kline(self, symbol, period, size=150, _async=False):59 """60 è·åKLine61 :param symbol62 :param period: å¯éå¼ï¼{1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year }63 :param size: å¯éå¼ï¼ [1,2000]64 :return:65 """66 params = {'symbol': symbol, 'period': period, 'size': size}67 url = self.url + '/market/history/kline'68 return http_get_request(url, params, _async=_async)69 def get_last_depth(self, symbol, _type, _async=False):70 """71 è·åmarketdepth72 :param symbol73 :param type: å¯éå¼ï¼{ percent10, step0, step1, step2, step3, step4, step5 }74 :return:75 """76 params = {'symbol': symbol, 'type': _type}77 url = self.url + '/market/depth'78 return http_get_request(url, params, _async=_async)79 def get_last_ticker(self, symbol, _async=False):80 """81 è·åtradedetail82 :param symbol83 :return:84 """85 params = {'symbol': symbol}86 url = self.url + '/market/trade'87 return http_get_request(url, params, _async=_async)88 def get_tickers(self, symbol, size=1, _async=False):89 """90 è·ååå²ticker91 :param symbol:92 :param size: å¯é[1,2000]93 :return:94 """95 params = {'symbol': symbol, 'size': size}96 url = self.url + '/market/history/trade'97 return http_get_request(url, params, _async=_async)98 def get_all_last_24h_kline(self, _async=False):99 """100 è·åææ24å°æ¶çæ¦åµ101 :param _async:102 :return:103 """104 params = {}105 url = self.url + '/market/tickers'106 return http_get_request(url, params, _async=_async)107 def get_last_1m_kline(self, symbol, _async=False):108 """109 è·åææ°ä¸åéçk线110 :param symbol:111 :return:112 """113 params = {'symbol': symbol}114 url = self.url + '/market/detail/merged'115 return http_get_request(url, params, _async=_async)116 def get_last_24h_kline(self, symbol, _async=False):117 """118 è·åæè¿24å°æ¶çæ¦åµ119 :param symbol120 :return:121 """122 params = {'symbol': symbol}123 url = self.url + '/market/detail'124 return http_get_request(url, params, _async=_async)125 def get_symbols(self, _async=False):126 """127 è·å æ¯æç交æ对128 :return:129 """130 params = {}131 path = f'/v1/common/symbols'132 return api_key_get(params, path, _async=_async, url=self.url)133 def get_currencys(self, _async=False):134 """135 è·åææå¸ç§136 :return:137 """138 params = {}139 path = f'/v1/common/currencys'140 return api_key_get(params, path, _async=_async, url=self.url)141 def get_timestamp(self, _async=False):142 params = {}143 path = '/v1/common/timestamp'144 return api_key_get(params, path, _async=_async, url=self.url)145 '''146 Trade/Account API147 '''148 def get_accounts(self, _async=False):149 """150 :return:151 """152 path = '/v1/account/accounts'153 params = {}154 return api_key_get(params, path, _async=_async, url=self.url)155 def get_balance(self, acc_id=None, _async=False):156 """157 è·åå½åè´¦æ·èµäº§158 :return:159 """160 acc_id = self.acc_id if acc_id is None else acc_id161 path = f'/v1/account/accounts/{acc_id}/balance'162 # params = {'account-id': self.acct_id}163 params = {}164 return api_key_get(params, path, _async=_async, url=self.url)165 def send_order(self, acc_id, amount, symbol, _type, price=0, _async=False):166 """167 å建并æ§è¡è®¢å168 :param amount:169 :param source: å¦æ使ç¨åè´·èµäº§äº¤æï¼è¯·å¨ä¸åæ¥å£,请æ±åæ°sourceä¸å¡«å'margin-api'170 :param symbol:171 :param _type: å¯éå¼ {buy-marketï¼å¸ä»·ä¹°, sell-marketï¼å¸ä»·å, buy-limitï¼éä»·ä¹°, sell-limitï¼éä»·å, buy-iocï¼IOCä¹°å, sell-iocï¼IOCåå}172 :param price:173 :return:174 """175 assert _type in u.ORDER_TYPE176 params = {177 'account-id': acc_id,178 'amount': amount,179 'symbol': symbol,180 'type': _type,181 'source': 'api'182 }183 if price:184 params['price'] = price185 path = f'/v1/order/orders/place'186 return api_key_post(params, path, _async=_async, url=self.url)187 def cancel_order(self, order_id, _async=False):188 """189 æ¤é订å190 :param order_id:191 :return:192 """193 params = {}194 path = f'/v1/order/orders/{order_id}/submitcancel'195 return api_key_post(params, path, _async=_async, url=self.url)196 def batchcancel_orders(self, order_ids: list, _async=False):197 """198 æ¹éæ¤é订å199 :param order_id:200 :return:201 """202 assert isinstance(order_ids, list)203 params = {'order-ids': order_ids}204 path = f'/v1/order/orders/batchcancel'205 return api_key_post(params, path, _async=_async, url=self.url)206 def batchcancel_openOrders(self, acc_id, symbol=None, side=None, size=None, _async=False):207 """208 æ¹éæ¤éæªæ交订å209 :param acc_id: å¸å·ID210 :param symbol: 交æ对211 :param side: æ¹å212 :param size:213 :param _async:214 :return:215 """216 params = {}217 path = '/v1/order/batchCancelOpenOrders'218 params['account-id'] = acc_id219 if symbol:220 params['symbol'] = symbol221 if side:222 assert side in ['buy', 'sell']223 params['side'] = side224 if size:225 params['size'] = size226 return api_key_post(params, path, _async=_async, url=self.url)227 def get_order_info(self, order_id, _async=False):228 """229 æ¥è¯¢æ个订å230 :param order_id:231 :return:232 """233 params = {}234 path = f'/v1/order/orders/{order_id}'235 return api_key_get(params, path, _async=_async, url=self.url)236 def get_openOrders(self, acc_id=None, symbol=None, side=None, size=None, _async=False):237 """238 æ¥è¯¢æªæ交订å239 :param acc_id: å¸å·ID240 :param symbol: 交æ对ID241 :param side: 交ææ¹åï¼'buy'æè
'sell'242 :param size: è®°å½æ¡æ°ï¼æ大500243 :return:244 """245 params = {}246 path = '/v1/order/openOrders'247 if all([acc_id, symbol]):248 params['account-id'] = acc_id249 params['symbol'] = symbol250 if side:251 assert side in ['buy', 'sell']252 params['side'] = side253 if size:254 params['size'] = size255 return api_key_get(params, path, _async=_async, url=self.url)256 def get_order_matchresults(self, order_id, _async=False):257 """258 æ¥è¯¢æ个订åçæ交æç»259 :param order_id:260 :return:261 """262 params = {}263 path = f'/v1/order/orders/{order_id}/matchresults'264 return api_key_get(params, path, _async=_async, url=self.url)265 def get_orders_info(self,266 symbol,267 states:list,268 types:list=None,269 start_date=None,270 end_date=None,271 _from=None,272 direct=None,273 size=None,274 _async=False):275 """276 æ¥è¯¢å½åå§æãåå²å§æ277 :param symbol:278 :param states: å¯éå¼ {pre-submitted åå¤æ交, submitted å·²æ交, partial-filled é¨åæ交, partial-canceled é¨åæ交æ¤é, filled å®å
¨æ交, canceled å·²æ¤é}279 :param types: å¯éå¼ {buy-marketï¼å¸ä»·ä¹°, sell-marketï¼å¸ä»·å, buy-limitï¼éä»·ä¹°, sell-limitï¼éä»·å}280 :param start_date:281 :param end_date:282 :param _from:283 :param direct: å¯éå¼{prev ååï¼next åå}284 :param size:285 :return:286 """287 states = ','.join(states)288 params = {'symbol': symbol, 'states': states}289 if types:290 params['types'] = ','.join(types)291 if start_date:292 sd = parser.parse(start_date).date()293 params['start-date'] = str(sd)294 if end_date:295 ed = parser.parse(end_date).date()296 params['end-date'] = str(ed)297 if _from:298 params['from'] = _from299 if direct:300 assert direct in ['prev', 'next']301 params['direct'] = direct302 if size:303 params['size'] = size304 path = '/v1/order/orders'305 return api_key_get(params, path, _async=_async, url=self.url)306 def get_recent48hours_order_info(self,307 symbol=None,308 start_time=None,309 end_time=None,310 direct=None,311 size=None,312 _async=False):313 """314 :param symbol:315 :param start_time: datetimeæè
UTC time in millisecond316 :param end_time: datetimeæè
UTC time in millisecond317 :param direct: å¯éå¼{prev ååï¼next åå}318 :param size: [10ï¼ 1000] default: 100319 :param _async:320 :return:321 """322 params = {}323 if symbol:324 params['symbol'] = symbol325 if start_time:326 if isinstance(start_time, dt.datetime):327 start_time = int(start_time.timestamp() * 1000)328 params['start-time'] = start_time329 if end_time:330 if isinstance(end_time, dt.datetime):331 end_time = int(end_time.timestamp() * 1000)332 params['end-time'] = end_time333 if direct:334 assert direct in ['prev', 'next']335 params['direct'] = direct336 if size:337 params['size'] = size338 path = '/v1/order/history'339 return api_key_get(params, path, _async=_async, url=self.url)340 def get_orders_matchresults(self,341 symbol,342 types:list=None,343 start_date=None,344 end_date=None,345 _from=None,346 direct=None,347 size=None,348 _async=False):349 """350 æ¥è¯¢å½åæ交ãåå²æ交351 :param symbol:352 :param types: å¯éå¼ {buy-marketï¼å¸ä»·ä¹°, sell-marketï¼å¸ä»·å, buy-limitï¼éä»·ä¹°, sell-limitï¼éä»·å}353 :param start_date:354 :param end_date:355 :param _from:356 :param direct: å¯éå¼{prev ååï¼next åå}357 :param size:358 :return:359 """360 params = {'symbol': symbol}361 if types:362 params['types'] = ','.join(types)363 if start_date:364 sd = parser.parse(start_date).date()365 params['start-date'] = str(sd)366 if end_date:367 ed = parser.parse(end_date).date()368 params['end-date'] = str(ed)369 if _from:370 params['from'] = _from371 if direct:372 params['direct'] = direct373 if size:374 params['size'] = size375 path = '/v1/order/matchresults'376 return api_key_get(params, path, _async=_async, url=self.url)377 def req_withdraw(self, address, amount, currency, fee=0, addr_tag="", _async=False):378 """379 ç³è¯·æç°èæå¸380 :param address:381 :param amount:382 :param currency:btc, ltc, bcc, eth, etc ...(ç«å¸Proæ¯æçå¸ç§)383 :param fee:384 :param addr_tag:385 :return: {386 "status": "ok",387 "data": 700388 }389 """390 params = {391 'address': address,392 'amount': amount,393 'currency': currency,394 'fee': fee,395 'addr-tag': addr_tag396 }397 path = '/v1/dw/withdraw/api/create'398 return api_key_post(params, path, _async=_async, url=self.url)399 def cancel_withdraw(self, withdraw_id, _async=False):400 """401 ç³è¯·åæ¶æç°èæå¸402 :param withdraw_id:403 :return: {404 "status": "ok",405 "data": 700406 }407 """408 params = {}409 path = f'/v1/dw/withdraw-virtual/{withdraw_id}/cancel'410 return api_key_post(params, path, _async=_async, url=self.url)411 def get_deposit_withdraw_record(self, currency, _type, _from, size, _async=False):412 """413 :param currency:414 :param _type:415 :param _from:416 :param size:417 :return:418 """419 assert _type in ['deposit', 'withdraw']420 params = {421 'currency': currency,422 'type': _type,423 'from': _from,424 'size': size425 }426 path = '/v1/query/deposit-withdraw'427 return api_key_get(params, path, _async=_async, url=self.url)428 '''429 åè´·API430 '''431 def send_margin_order(self, acc_id, amount, symbol, _type, price=0, _async=False):432 """433 å建并æ§è¡å贷订å434 :param amount:435 :param symbol:436 :param _type: å¯éå¼ {buy-marketï¼å¸ä»·ä¹°, sell-marketï¼å¸ä»·å, buy-limitï¼éä»·ä¹°, sell-limitï¼éä»·å}437 :param price:438 :return:439 """440 params = {441 'account-id': acc_id,442 'amount': amount,443 'symbol': symbol,444 'type': _type,445 'source': 'margin-api'446 }447 if price:448 params['price'] = price449 path = '/v1/order/orders/place'450 return api_key_post(params, path, _async=_async, url=self.url)451 def exchange_to_margin(self, symbol, currency, amount, _async=False):452 """453 ç°è´§è´¦æ·åå
¥è³åè´·è´¦æ·454 :param amount:455 :param currency:456 :param symbol:457 :return:458 """459 params = {'symbol': symbol, 'currency': currency, 'amount': amount}460 path = '/v1/dw/transfer-in/margin'461 return api_key_post(params, path, _async=_async, url=self.url)462 def margin_to_exchange(self, symbol, currency, amount, _async=False):463 """464 åè´·è´¦æ·ååºè³ç°è´§è´¦æ·465 :param amount:466 :param currency:467 :param symbol:468 :return:469 """470 params = {'symbol': symbol, 'currency': currency, 'amount': amount}471 path = '/v1/dw/transfer-out/margin'472 return api_key_post(params, path, _async=_async, url=self.url)473 def apply_loan(self, symbol, currency, amount, _async=False):474 """475 ç³è¯·åè´·476 :param amount:477 :param currency:478 :param symbol:479 :return:480 """481 params = {'symbol': symbol, 'currency': currency, 'amount': amount}482 path = '/v1/margin/orders'483 return api_key_post(params, path, _async=_async, url=self.url)484 def repay_loan(self, order_id, amount, _async=False):485 """486 å½è¿åè´·487 :param order_id:488 :param amount:489 :return:490 """491 params = {'order-id': order_id, 'amount': amount}492 path = f'/v1/margin/orders/{order_id}/repay'493 return api_key_post(params, path, _async=_async, url=self.url)494 def get_loan_orders(self,495 symbol,496 states=None,497 start_date=None,498 end_date=None,499 _from=None,500 direct=None,501 size=None,502 _async=False):503 params = {'symbol': symbol}504 if states:505 params['states'] = states506 if start_date:507 sd = parser.parse(start_date).date()508 params['start-date'] = str(sd)509 if end_date:510 ed = parser.parse(end_date).date()511 params['end_date'] = str(ed)512 if _from:513 params['from'] = _from514 if direct and direct in ['prev', 'next']:515 params['direct'] = direct516 if size:517 params['size'] = size518 path = '/v1/margin/loan-orders'519 return api_key_get(params, path, _async=_async, url=self.url)520 def get_margin_balance(self, symbol=None, _async=False):521 """522 åè´·è´¦æ·è¯¦æ
,æ¯ææ¥è¯¢å个å¸ç§523 :param symbol:524 :return:525 """526 params = {}527 path = '/v1/margin/accounts/balance'528 if symbol:529 params['symbol'] = symbol530 return api_key_get(params, path, _async=_async, url=self.url)531 def get_etf_config(self, etf_name, _async=False):532 """533 æ¥è¯¢etfçåºæ¬ä¿¡æ¯534 :param etf_name: etfåºéå称535 :param _async:536 :return:537 """538 params = {}539 path = '/etf/swap/config'540 params['etf_name'] = etf_name541 return api_key_get(params, path, _async=_async, url=self.url)542 def etf_swap_in(self, etf_name, amount, _async=False):543 """544 æ¢å
¥etf545 :param etf_name: etfåºéå称546 :param amount: æ°é547 :param _async:548 :return:549 """550 params = {}551 path = '/etf/swap/in'552 params['etf_name'] = etf_name553 params['amount'] = amount554 return api_key_post(params, path, _async=_async, url=self.url)555 def etf_swap_out(self, etf_name, amount, _async=False):556 """557 æ¢åºetf558 :param etf_name: etfåºéå称559 :param amount: æ°é560 :param _async:561 :return:562 """563 params = {}564 path = '/etf/swap/out'565 params['etf_name'] = etf_name566 params['amount'] = amount567 return api_key_post(params, path, _async=_async, url=self.url)568 def get_etf_records(self, etf_name, offset, limit, _async=False):569 """570 æ¥è¯¢etfæ¢å
¥æ¢åºæç»571 :param etf_name: ethåºéå称572 :param offset: å¼å§ä½ç½®,0为ææ°ä¸æ¡573 :param limit: è¿åè®°å½æ¡æ°(0, 100]574 :param _async:575 :return:576 """577 params = {}578 path = '/etf/list'579 params['etf_name'] = etf_name580 params['offset'] = offset581 params['limit'] = limit582 return api_key_get(params, path, _async=_async, url=self.url)583 def get_quotation_kline(self, symbol, period, limit=None, _async=False):584 """585 è·åetfåå¼586 :param symbol: etfå称587 :param period: K线类å588 :param limit: è·åæ°é589 :param _async:590 :return:591 """592 params = {}593 path = '/quotation/market/history/kline'594 params['symbol'] = symbol595 params['period'] = period596 if limit:597 params['limit'] = limit598 return api_key_get(params, path, _async=_async, url=self.url)599 def transfer(self, sub_uid, currency, amount, transfer_type, _async=False):600 """601 æ¯è´¦æ·æ§è¡åè´¦æ·å转602 :param sub_uid: åè´¦æ·id603 :param currency: å¸ç§604 :param amount: å转éé¢605 :param transfer_type: å转类åï¼master-transfer-inï¼åè´¦æ·å转ç»æ¯è´¦æ·èæå¸ï¼/ master-transfer-out ï¼æ¯è´¦æ·å转ç»åè´¦æ·èæå¸ï¼/master-point-transfer-in ï¼åè´¦æ·å转ç»æ¯è´¦æ·ç¹å¡ï¼/master-point-transfer-outï¼æ¯è´¦æ·å转ç»åè´¦æ·ç¹å¡ï¼606 :param _async: æ¯å¦å¼æ¥æ§è¡607 :return:608 """609 params = {}610 path = '/v1/subuser/transfer'611 params['sub-uid'] = sub_uid612 params['currency'] = currency613 params['amount'] = amount614 params['type'] = transfer_type615 return api_key_post(params, path, _async=_async, url=self.url)616 def get_aggregate_balance(self, _async=False):617 """618 æ¥è¯¢ææåè´¦æ·æ±æ»619 :param _async: æ¯å¦å¼æ¥æ§è¡620 :return:621 """622 params = {}623 path = '/v1/subuser/aggregate-balance'624 return api_key_get(params, path, _async=_async, url=self.url)625 def get_sub_balance(self, sub_uid, _async=False):626 """627 æ¥è¯¢åè´¦æ·åå¸ç§è´¦æ·ä½é¢628 :param sub_uid: åè´¦æ·id629 :param _async:630 :return:631 """632 params = {}633 params['sub-uid'] = sub_uid634 path = f'/v1/account/accounts/{sub_uid}'635 return api_key_get(params, path, _async=_async, url=self.url)636class HBDerivativesRestAPI(metaclass=Singleton):637 def __init__(self, url=None, keys=None):638 """639 ç«å¸å约REST APIå°è£
640 :param url: ä¼ å
¥urlï¼è¥ä¸ºNoneï¼é»è®¤æ¯https://api.hbdm.com641 :param keys: ä¼ å
¥(acess_key, secret_key),å¯ç¨setKey设置642 """643 self.url = url if url else DEFAULT_DM_URL644 if keys:645 setKey(*keys)646 def __async_request_exception_handler(self, req, e):647 logger.error(f'async_request:{req}--exception:{e}')648 def async_request(self, reqs:list)->list:649 """650 å¼æ¥å¹¶å请æ±651 :param reqs: 请æ±å表652 :return:653 """654 result = (response.result() for response in reqs)655 ret = [r.json() if r.status_code == 200 else None for r in result]656 return ret657 def get_contract_info(self, symbol=None, contract_type=None, contract_code=None, _async=False):658 """659 å约信æ¯è·å660 :param symbol:661 :param contract_type:662 :param contract_code:663 :param _async:664 :return:665 """666 params = {}667 if symbol:668 params['symbol'] = symbol669 if contract_type:670 params['contract_type'] = contract_type671 if contract_code:672 params['contract_code'] = contract_code673 path = '/api/v1/contract_contract_info'674 url = self.url + path675 return http_get_request(url, params, _async=_async)676 def get_contract_index(self, symbol, _async=False):677 """678 è·åå约ææ°679 :param symbol:680 :param _async:681 :return:682 """683 params = {'symbol': symbol}684 path = '/api/v1/contract_index'685 url = self.url + path686 return http_get_request(url, params, _async=_async)687 def get_price_limit(self, symbol=None, contract_type=None, contract_code=None, _async=False):688 """689 å约é«ä½éä»·690 :param symbol:691 :param contract_type:692 :param contract_code:693 :param _async:694 :return:695 """696 params = {}697 if symbol:698 params['symbol'] = symbol699 if contract_type:700 params['contract_type'] = contract_type701 if contract_code:702 params['contract_code'] = contract_code703 path = '/api/v1/contract_price_limit'704 url = self.url + path705 return http_get_request(url, params, _async=_async)706 def get_delivery_price(self, symbol, _async=False):707 """708 :param symbol:709 :param _async:710 :return:711 """712 params = {'symbol': symbol}713 path = '/api/v1/contract_delivery_price'714 url = self.url + path715 return http_get_request(url, params, _async=_async)716 def get_open_interest(self, symbol=None, contract_type=None, contract_code=None, _async=False):717 """718 :param symbol:719 :param contract_type:720 :param contract_code:721 :param _async:722 :return:723 """724 params = {}725 if symbol:726 params['symbol'] = symbol727 if contract_type:728 params['contract_type'] = contract_type729 if contract_code:730 params['contract_code'] = contract_code731 path = '/api/v1/contract_open_interest'732 url = self.url + path733 return http_get_request(url, params, _async=_async)734 def get_last_depth(self, symbol, _type, _async=False):735 """736 :param symbol:737 :param _type:738 :param _async:739 :return:740 """741 params = {'symbol': symbol, 'type': _type}742 path = '/market/depth'743 url = self.url + path744 return http_get_request(url, params, _async=_async)745 def get_kline(self, symbol, period, size=150, _async=False):746 """747 :param symbol:748 :param period: {1min, 5min, 15min, 30min, 60min,4hour,1day, 1mon}749 :param size: [1, 2000]750 :param _async:751 :return:752 """753 params = {'symbol': symbol, 'period': period, 'size': size}754 path = '/market/history/kline'755 url = self.url + path756 return http_get_request(url, params, _async=_async)757 def get_last_1m_kline(self, symbol, _async=False):758 """759 :param symbol:760 :param _async:761 :return:762 """763 params = {'symbol': symbol}764 path = '/market/detail/merged'765 url = self.url + path766 return http_get_request(url, params, _async=_async)767 def get_last_ticker(self, symbol, _async=False):768 """769 :param symbol:770 :param _async:771 :return:772 """773 params = {'symbol': symbol}774 path = '/market/trade'775 url = self.url + path776 return http_get_request(url, params, _async=_async)777 def get_tickers(self, symbol, size=1, _async=False):778 """779 :param symbol:780 :param size: [1, 2000]781 :param _async:782 :return:783 """784 params = {'symbol': symbol, 'size': size}785 path = '/market/history/trade'786 url = self.url + path787 return http_get_request(url, params, _async=_async)788 # -----------------éè¦é´æ------------------789 def get_accounts(self, symbol=None, _async=False):790 """791 :param symbol:792 :param _async:793 :return:794 """795 params = {}796 if symbol:797 params['symbol'] = symbol798 path = '/api/v1/contract_account_info'799 return api_key_post(params, path, _async=_async, url=self.url)800 def get_positions(self, symbol=None, _async=False):801 """802 :param symbol:803 :param _async:804 :return:805 """806 params = {}807 if symbol:808 params['symbol'] = symbol809 path = '/api/v1/contract_position_info'810 return api_key_post(params, path, _async=_async, url=self.url)811 @staticmethod812 def create_order_params(*,813 volume,814 direction,815 offset,816 lever_rate,817 order_price_type,818 symbol=None,819 contract_type=None,820 contract_code=None,821 price=None,822 client_order_id=None):823 """824 :param volume:825 :param direction: ['buy', 'sell']826 :param offset: ['open', 'close']827 :param lever_rate:828 :param order_price_type: ['limit', 'opponent', 'post_only',829 :param symbol:830 :param contract_type: ['this_week', 'next_week', 'quarter']831 :param contract_code:832 :param price:833 :param client_order_id:834 :return:835 """836 params = {'volume': volume, 'direction': direction, 'offset': offset,837 'lever_rate': lever_rate, 'order_price_type': order_price_type}838 if order_price_type != 'opponent' and price is None:839 raise ValueError('éopponent订åï¼éè¦å¡«åprice')840 params['price'] = price841 if contract_code is not None:842 params['contract_code'] = contract_code843 else:844 params['symbol'] = symbol845 params['contract_type'] = contract_type846 if client_order_id is not None:847 params['client_order_id'] = client_order_id848 return params849 def send_order(self, order_params, _async=False):850 """851 :param order_params: éè¿create_order_paramså建çåæ°852 :param _async:853 :return:854 """855 path = '/api/v1/contract_order'856 return api_key_post(order_params, path, _async=_async, url=self.url)857 def batchcancel_orders(self, order_params_list:list, _async=False):858 """859 :param order_params_list: éè¿create_order_paramså建çåæ°å表860 :param _async:861 :return:862 """863 path = '/api/v1/contract_batchorder'864 return api_key_post(order_params_list, path, _async=_async, url=self.url)865 def cancel_order(self, symbol, order_ids:list=None, client_order_ids: list=None, _async=False):866 """867 :param symbol:868 :param order_ids:869 :param client_order_ids:870 :param _async:871 :return:872 """873 params = {'symbol': symbol}874 if order_ids:875 params['order_id'] = ','.join(order_ids)876 if client_order_ids:877 params['client_order_id'] = ','.join(client_order_ids)878 path = '/api/v1/contract_cancel'879 return api_key_post(params, path, _async=_async, url=self.url)880 def cancel_all_orders(self, symbol, contract_code=None, contract_type=None, _async=False):881 """882 :param symbol:883 :param contract_code:884 :param contract_type:885 :param _async:886 :return:887 """888 params = {'symbol': symbol}889 if contract_code:890 params['contract_code'] = contract_code891 if contract_type:892 params['contract_type'] = contract_type893 path = '/api/v1/contract_cancelall'894 return api_key_post(params, path, _async=_async, url=self.url)895 def get_order_info(self,symbol, order_ids:list=None, client_order_ids: list=None, _async=False):896 """897 :param symbol:898 :param order_ids:899 :param client_order_ids:900 :param _async:901 :return:902 """903 params = {'symbol': symbol}904 if order_ids:905 params['order_id'] = ','.join(order_ids)906 if client_order_ids:907 params['client_order_id'] = ','.join(client_order_ids)908 path = '/api/v1/contract_order_info'909 return api_key_post(params, path, _async=_async, url=self.url)910 def get_order_detail(self, symbol, order_id, create_at, order_type,911 page_index=None, page_size=20, _async=False):912 """913 :param symbol:914 :param order_id:915 :param create_at:916 :param order_type:917 :param page_index: 页ç ï¼ä¸å¡«é»è®¤ç¬¬1页918 :param page_size: ä¸å¡«é»è®¤20ï¼ä¸å¾å¤äº50 20919 :param _async:920 :return:921 """922 params = {'symbol': symbol, 'order_id': order_id,923 'order_type': order_type, 'page_size': page_size}924 if page_index is not None:925 params['page_index'] = page_index926 if isinstance(create_at, str):927 create_at = int(parser.parse(create_at).timestamp() * 1000)928 elif isinstance(create_at, dt.datetime):929 create_at = int(create_at.timestamp() * 1000)930 params['create_at'] = create_at931 path = '/api/v1/contract_order_detail'932 return api_key_post(params, path, _async=_async, url=self.url)933 def get_open_orders(self, symbol, page_index=None, page_size=20, _async=False):934 """935 :param symbol:936 :param page_index: 页ç ï¼ä¸å¡«é»è®¤ç¬¬1页937 :param page_size: ä¸å¡«é»è®¤20ï¼ä¸å¾å¤äº50 20938 :param _async:939 :return:940 """941 params = {'symbol': symbol, 'page_size': page_size}942 if page_index is not None:943 params['page_index'] = page_index944 path = '/api/v1/contract_openorders'945 return api_key_post(params, path, _async=_async, url=self.url)946 def get_history_orders(self, symbol, trade_type, _type, status, create_date,947 page_index=None, page_size=20, _async=False):948 """949 :param symbol:950 :param trade_type: 0:å
¨é¨,1:ä¹°å
¥å¼å¤,2: ååºå¼ç©º,3: ä¹°å
¥å¹³ç©º,4: ååºå¹³å¤,5: ååºå¼ºå¹³,6: ä¹°å
¥å¼ºå¹³,7:交å²å¹³å¤,8: 交å²å¹³ç©º951 :param _type: 1:ææ订å,2:ç»æç¶æç订å952 :param status: 0:å
¨é¨,3:æªæ交, 4: é¨åæ交,5: é¨åæ交已æ¤å,6: å
¨é¨æ交,7:å·²æ¤å953 :param create_date: 7ï¼90ï¼7天æè
90天ï¼954 :param page_index: 页ç ï¼ä¸å¡«é»è®¤ç¬¬1页955 :param page_size: ä¸å¡«é»è®¤20ï¼ä¸å¾å¤äº50 20956 :param _async:957 :return:958 """959 params = {'symbol': symbol, 'trade_type': trade_type, 'type': _type,960 'status': status, 'create_date': create_date, 'page_size': page_size}961 if page_index is not None:962 params['page_index'] = page_index963 path = '/api/v1/contract_hisorders'964 return api_key_post(params, path, _async=_async, url=self.url)965 def get_order_matchresults(self, symbol, trade_type, create_date,966 page_index=None, page_size=20, _async=False):967 """968 :param symbol:969 :param trade_type: 0:å
¨é¨,1:ä¹°å
¥å¼å¤,2: ååºå¼ç©º,3: ä¹°å
¥å¹³ç©º,4: ååºå¹³å¤,5: ååºå¼ºå¹³,6: ä¹°å
¥å¼ºå¹³970 :param create_date: 7ï¼90ï¼7天æè
90天ï¼971 :param page_index: 页ç ï¼ä¸å¡«é»è®¤ç¬¬1页972 :param page_size: ä¸å¡«é»è®¤20ï¼ä¸å¾å¤äº50973 :param _async:974 :return:975 """976 params = {'symbol': symbol, 'trade_type': trade_type,977 'create_date': create_date, 'page_size': page_size}978 if page_index is not None:979 params['page_index'] = page_index980 path = '/api/v1/contract_matchresults'981 return api_key_post(params, path, _async=_async, url=self.url)982 def transfer_futures(self, currency, amount, _type, _async=False):983 """984 :param currency:985 :param amount:986 :param _type: ä»å约账æ·å°ç°è´§è´¦æ·ï¼âfutures-to-proâï¼ä»ç°è´§è´¦æ·å°å约账æ·ï¼ âpro-to-futuresâ987 :param _async:988 :return:989 """990 params = {'currency': currency, 'amount': amount, 'type': _type}991 path = '/v1/futures/transfer'992 return api_key_post(params, path, _async=_async, url='https://api.huobi.pro')993# class HBRestAPI_DEC():994# def __init__(self, addr=None, key=None, get_acc=False):995# """996# ç«å¸REST APIå°è£
decorationç997# :param addrs: ä¼ å
¥(market_url, trade_url)ï¼è¥ä¸ºNoneï¼é»è®¤æ¯https://api.huobi.br.com998# :param keys: ä¼ å
¥(acess_key, secret_key),å¯ç¨setKey设置999# :param get_acc: 设置æ¯å¦åå§åè·åacc_id,,é»è®¤False1000# """1001# if addr:1002# setUrl(*addr)1003# if key:1004# setKey(*key)1005# if get_acc:1006# @self.get_accounts()1007# def set_acc(msg):1008# self.acc_id = msg['data'][0]['id']1009# set_acc()1010#1011# def set_acc_id(self, acc_id):1012# self.acc_id = acc_id1013#1014# def get_kline(self, symbol, period, size=150):1015# """1016# è·åK线1017# :param symbol1018# :param period: å¯éå¼ï¼{1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year }1019# :param size: å¯éå¼ï¼ [1,2000]1020# :return:1021# """1022# params = {'symbol': symbol, 'period': period, 'size': size}1023# url = u.MARKET_URL + '/market/history/kline'1024#1025# def _wrapper(_func):1026# @wraps(_func)1027# def handle():1028# _func(http_get_request(url, params))1029#1030# return handle1031#1032# return _wrapper1033#1034# def get_last_depth(self, symbol, _type):1035# """1036# è·åmarketdepth1037# :param symbol1038# :param type: å¯éå¼ï¼{ percent10, step0, step1, step2, step3, step4, step5 }1039# :return:1040# """1041# params = {'symbol': symbol, 'type': _type}1042#1043# url = u.MARKET_URL + '/market/depth'1044#1045# def _wrapper(_func):1046# @wraps(_func)1047# def handle():1048# _func(http_get_request(url, params))1049#1050# return handle1051#1052# return _wrapper1053#1054# def get_last_ticker(self, symbol):1055# """1056# è·åææ°çticker1057# :param symbol1058# :return:1059# """1060# params = {'symbol': symbol}1061#1062# url = u.MARKET_URL + '/market/trade'1063#1064# def _wrapper(_func):1065# @wraps(_func)1066# def handle():1067# _func(http_get_request(url, params))1068#1069# return handle1070#1071# return _wrapper1072#1073# def get_ticker(self, symbol, size=1):1074# """1075# è·ååå²ticker1076# :param symbol:1077# :param size: å¯é[1,2000]1078# :return:1079# """1080# params = {'symbol': symbol, 'size': size}1081#1082# url = u.MARKET_URL + '/market/history/trade'1083#1084# def _wrapper(_func):1085# @wraps(_func)1086# def handle():1087# _func(http_get_request(url, params))1088#1089# return handle1090#1091# return _wrapper1092#1093# def get_all_last_24h_kline(self):1094# """1095# è·åææticker1096# :param _async:1097# :return:1098# """1099# params = {}1100# url = u.MARKET_URL + '/market/tickers'1101#1102# def _wrapper(_func):1103# @wraps(_func)1104# def handle():1105# _func(http_get_request(url, params))1106#1107# return handle1108#1109# return _wrapper1110#1111#1112# def get_last_1m_kline(self, symbol):1113# """1114# è·åææ°ä¸åéçkline1115# :param symbol:1116# :return:1117# """1118# params = {'symbol': symbol}1119#1120# url = u.MARKET_URL + '/market/detail/merged'1121#1122# def _wrapper(_func):1123# @wraps(_func)1124# def handle():1125# _func(http_get_request(url, params))1126#1127# return handle1128#1129# return _wrapper1130#1131# def get_last_24h_kline(self, symbol):1132# """1133# è·å Market Detail 24å°æ¶æ交éæ°æ®1134# :param symbol1135# :return:1136# """1137# params = {'symbol': symbol}1138#1139# url = u.MARKET_URL + '/market/detail'1140#1141# def _wrapper(_func):1142# @wraps(_func)1143# def handle():1144# _func(http_get_request(url, params))1145#1146# return handle1147#1148# return _wrapper1149#1150# def get_symbols(self, site='Pro'):1151# """1152# è·åæ¯æç交æ对1153# :param site:1154# :return:1155# """1156# assert site in ['Pro', 'HADAX']1157# params = {}1158# path = f'/v1{"/" if site == "Pro" else "/hadax/"}common/symbols'1159#1160# def _wrapper(_func):1161# @wraps(_func)1162# def handle():1163# _func(api_key_get(params, path))1164#1165# return handle1166#1167# return _wrapper1168#1169# def get_currencys(self, site='Pro'):1170# """1171#1172# :return:1173# """1174# assert site in ['Pro', 'HADAX']1175# params = {}1176# path = f'/v1{"/" if site == "Pro" else "/hadax/"}common/currencys'1177#1178# def _wrapper(_func):1179# @wraps(_func)1180# def handle():1181# _func(api_key_get(params, path))1182#1183# return handle1184#1185# return _wrapper1186#1187# def get_timestamp(self):1188# params = {}1189# path = '/v1/common/timestamp'1190#1191# def _wrapper(_func):1192# @wraps(_func)1193# def handle():1194# _func(api_key_get(params, path))1195#1196# return handle1197#1198# return _wrapper1199#1200# '''1201# Trade/Account API1202# '''1203#1204# def get_accounts(self):1205# """1206# :return:1207# """1208# path = '/v1/account/accounts'1209# params = {}1210#1211# def _wrapper(_func):1212# @wraps(_func)1213# def handle():1214# _func(api_key_get(params, path))1215#1216# return handle1217#1218# return _wrapper1219#1220# def get_balance(self, acc_id, site='Pro'):1221# """1222# è·åå½åè´¦æ·èµäº§1223# :return:1224# """1225# assert site in ['Pro', 'HADAX']1226# path = f'/v1{"/" if site == "Pro" else "/hadax/"}account/accounts/{acc_id}/balance'1227# # params = {'account-id': self.acct_id}1228# params = {}1229#1230# def _wrapper(_func):1231# @wraps(_func)1232# def handle():1233# _func(api_key_get(params, path))1234#1235# return handle1236#1237# return _wrapper1238#1239# def send_order(self, acc_id, amount, symbol, _type, price=0, site='Pro'):1240# """1241# å建并æ§è¡è®¢å1242# :param amount:1243# :param source: å¦æ使ç¨åè´·èµäº§äº¤æï¼è¯·å¨ä¸åæ¥å£,请æ±åæ°sourceä¸å¡«å'margin-api'1244# :param symbol:1245# :param _type: å¯éå¼ {buy-marketï¼å¸ä»·ä¹°, sell-marketï¼å¸ä»·å, buy-limitï¼éä»·ä¹°, sell-limitï¼éä»·å, buy-iocï¼IOCä¹°å, sell-iocï¼IOCåå}1246# :param price:1247# :return:1248# """1249# assert site in ['Pro', 'HADAX']1250# assert _type in u.ORDER_TYPE1251# params = {1252# 'account-id': acc_id,1253# 'amount': amount,1254# 'symbol': symbol,1255# 'type': _type,1256# 'source': 'api'1257# }1258# if price:1259# params['price'] = price1260#1261# path = f'/v1{"/" if site == "Pro" else "/hadax/"}order/orders/place'1262#1263# def _wrapper(_func):1264# @wraps(_func)1265# def handle():1266# _func(api_key_post(params, path))1267#1268# return handle1269#1270# return _wrapper1271#1272# def cancel_order(self, order_id):1273# """1274# æ¤é订å1275# :param order_id:1276# :return:1277# """1278# params = {}1279# path = f'/v1/order/orders/{order_id}/submitcancel'1280#1281# def _wrapper(_func):1282# @wraps(_func)1283# def handle():1284# _func(api_key_post(params, path))1285#1286# return handle1287#1288# return _wrapper1289#1290# def batchcancel_order(self, order_ids: list):1291# """1292# æ¹éæ¤é订å1293# :param order_id:1294# :return:1295# """1296# assert isinstance(order_ids, list)1297# params = {'order-ids': order_ids}1298# path = f'/v1/order/orders/batchcancel'1299#1300# def _wrapper(_func):1301# @wraps(_func)1302# def handle():1303# _func(api_key_post(params, path))1304#1305# return handle1306#1307# return _wrapper1308#1309# def get_order_info(self, order_id):1310# """1311# æ¥è¯¢æ个订å1312# :param order_id:1313# :return:1314# """1315# params = {}1316# path = f'/v1/order/orders/{order_id}'1317#1318# def _wrapper(_func):1319# @wraps(_func)1320# def handle():1321# _func(api_key_get(params, path))1322#1323# return handle1324#1325# return _wrapper1326#1327# def get_order_matchresults(self, order_id):1328# """1329# æ¥è¯¢æ个订åçæ交æç»1330# :param order_id:1331# :return:1332# """1333# params = {}1334# path = f'/v1/order/orders/{order_id}/matchresults'1335#1336# def _wrapper(_func):1337# @wraps(_func)1338# def handle():1339# _func(api_key_get(params, path))1340#1341# return handle1342#1343# return _wrapper1344#1345# def get_orders_info(self,1346# symbol,1347# states,1348# types=None,1349# start_date=None,1350# end_date=None,1351# _from=None,1352# direct=None,1353# size=None):1354# """1355# æ¥è¯¢å½åå§æãåå²å§æ1356# :param symbol:1357# :param states: å¯éå¼ {pre-submitted åå¤æ交, submitted å·²æ交, partial-filled é¨åæ交, partial-canceled é¨åæ交æ¤é, filled å®å
¨æ交, canceled å·²æ¤é}1358# :param types: å¯éå¼ ä¹°åç±»å1359# :param start_date:1360# :param end_date:1361# :param _from:1362# :param direct: å¯éå¼{prev ååï¼next åå}1363# :param size:1364# :return:1365# """1366# params = {'symbol': symbol, 'states': states}1367#1368# if types:1369# params['types'] = types1370# if start_date:1371# sd = parser.parse(start_date).date()1372# params['start-date'] = str(sd)1373# if end_date:1374# ed = parser.parse(end_date).date()1375# params['end_date'] = str(ed)1376# if _from:1377# params['from'] = _from1378# if direct:1379# assert direct in ['prev', 'next']1380# params['direct'] = direct1381# if size:1382# params['size'] = size1383# path = '/v1/order/orders'1384#1385# def _wrapper(_func):1386# @wraps(_func)1387# def handle():1388# _func(api_key_get(params, path))1389#1390# return handle1391#1392# return _wrapper1393#1394# def get_orders_matchresults(self,1395# symbol,1396# types=None,1397# start_date=None,1398# end_date=None,1399# _from=None,1400# direct=None,1401# size=None):1402# """1403# æ¥è¯¢å½åæ交ãåå²æ交1404# :param symbol:1405# :param types: å¯éå¼ {buy-marketï¼å¸ä»·ä¹°, sell-marketï¼å¸ä»·å, buy-limitï¼éä»·ä¹°, sell-limitï¼éä»·å}1406# :param start_date:1407# :param end_date:1408# :param _from:1409# :param direct: å¯éå¼{prev ååï¼next åå}1410# :param size:1411# :return:1412# """1413# params = {'symbol': symbol}1414#1415# if types:1416# params['types'] = types1417# if start_date:1418# sd = parser.parse(start_date).date()1419# params['start-date'] = str(sd)1420# if end_date:1421# ed = parser.parse(end_date).date()1422# params['end_date'] = str(ed)1423# if _from:1424# params['from'] = _from1425# if direct:1426# params['direct'] = direct1427# if size:1428# params['size'] = size1429# path = '/v1/order/matchresults'1430#1431# def _wrapper(_func):1432# @wraps(_func)1433# def handle():1434# _func(api_key_get(params, path))1435#1436# return handle1437#1438# return _wrapper1439#1440# def req_withdraw(self, address, amount, currency, fee=0, addr_tag=""):1441# """1442# ç³è¯·æç°èæå¸1443# :param address_id:1444# :param amount:1445# :param currency:btc, ltc, bcc, eth, etc ...(ç«å¸Proæ¯æçå¸ç§)1446# :param fee:1447# :param addr-tag:1448# :return: {1449# "status": "ok",1450# "data": 7001451# }1452# """1453# params = {1454# 'address': address,1455# 'amount': amount,1456# 'currency': currency,1457# 'fee': fee,1458# 'addr-tag': addr_tag1459# }1460# path = '/v1/dw/withdraw/api/create'1461#1462# def _wrapper(_func):1463# @wraps(_func)1464# def handle():1465# _func(api_key_post(params, path))1466#1467# return handle1468#1469# return _wrapper1470#1471# def cancel_withdraw(self, address_id):1472# """1473# ç³è¯·åæ¶æç°èæå¸1474# :param address_id:1475# :return: {1476# "status": "ok",1477# "data": 7001478# }1479# """1480# params = {}1481# path = f'/v1/dw/withdraw-virtual/{address_id}/cancel'1482#1483# def _wrapper(_func):1484# @wraps(_func)1485# def handle():1486# _func(api_key_post(params, path))1487#1488# return handle1489#1490# return _wrapper1491#1492# def get_deposit_withdraw_record(self, currency, _type, _from, size):1493# """1494#1495# :param currency:1496# :param _type:1497# :param _from:1498# :param size:1499# :return:1500# """1501# assert _type in ['deposit', 'withdraw']1502# params = {1503# 'currency': currency,1504# 'type': _type,1505# 'from': _from,1506# 'size': size1507# }1508# path = '/v1/query/deposit-withdraw'1509#1510# def _wrapper(_func):1511# @wraps(_func)1512# def handle():1513# _func(api_key_get(params, path))1514#1515# return handle1516#1517# return _wrapper1518#1519# '''1520# åè´·API1521# '''1522#1523# def send_margin_order(self, acc_id, amount, symbol, _type, price=0):1524# """1525# å建并æ§è¡å贷订å1526# :param amount:1527# :param symbol:1528# :param _type: å¯éå¼ {buy-marketï¼å¸ä»·ä¹°, sell-marketï¼å¸ä»·å, buy-limitï¼éä»·ä¹°, sell-limitï¼éä»·å}1529# :param price:1530# :return:1531# """1532#1533# params = {1534# 'account-id': acc_id,1535# 'amount': amount,1536# 'symbol': symbol,1537# 'type': _type,1538# 'source': 'margin-api'1539# }1540# if price:1541# params['price'] = price1542#1543# path = '/v1/order/orders/place'1544#1545# def _wrapper(_func):1546# @wraps(_func)1547# def handle():1548# _func(api_key_post(params, path))1549#1550# return handle1551#1552# return _wrapper1553#1554# def exchange_to_margin(self, symbol, currency, amount):1555# """1556# ç°è´§è´¦æ·åå
¥è³åè´·è´¦æ·1557# :param amount:1558# :param currency:1559# :param symbol:1560# :return:1561# """1562# params = {'symbol': symbol, 'currency': currency, 'amount': amount}1563# path = '/v1/dw/transfer-in/margin'1564#1565# def _wrapper(_func):1566# @wraps(_func)1567# def handle():1568# _func(api_key_post(params, path))1569#1570# return handle1571#1572# return _wrapper1573#1574# def margin_to_exchange(self, symbol, currency, amount):1575# """1576# åè´·è´¦æ·ååºè³ç°è´§è´¦æ·1577# :param amount:1578# :param currency:1579# :param symbol:1580# :return:1581# """1582# params = {'symbol': symbol, 'currency': currency, 'amount': amount}1583#1584# path = '/v1/dw/transfer-out/margin'1585#1586# def _wrapper(_func):1587# @wraps(_func)1588# def handle():1589# _func(api_key_post(params, path))1590#1591# return handle1592#1593# return _wrapper1594#1595# def apply_loan(self, symbol, currency, amount):1596# """1597# ç³è¯·åè´·1598# :param amount:1599# :param currency:1600# :param symbol:1601# :return:1602# """1603# params = {'symbol': symbol, 'currency': currency, 'amount': amount}1604# path = '/v1/margin/orders'1605#1606# def _wrapper(_func):1607# @wraps(_func)1608# def handle():1609# _func(api_key_post(params, path))1610#1611# return handle1612#1613# return _wrapper1614#1615# def repay_loan(self, order_id, amount):1616# """1617# å½è¿åè´·1618# :param order_id:1619# :param amount:1620# :return:1621# """1622# params = {'order-id': order_id, 'amount': amount}1623# path = f'/v1/margin/orders/{order_id}/repay'1624#1625# def _wrapper(_func):1626# @wraps(_func)1627# def handle():1628# _func(api_key_post(params, path))1629#1630# return handle1631#1632# return _wrapper1633#1634# def get_loan_orders(self,1635# symbol,1636# currency,1637# states=None,1638# start_date=None,1639# end_date=None,1640# _from=None,1641# direct=None,1642# size=None):1643# """1644# å贷订å1645# :param symbol:1646# :param currency:1647# :param start_date:1648# :param end_date:1649# :param _from:1650# :param direct:1651# :param size:1652# :return:1653# """1654# params = {'symbol': symbol, 'currency': currency}1655# if states:1656# params['states'] = states1657# if start_date:1658# sd = parser.parse(start_date).date()1659# params['start-date'] = str(sd)1660# if end_date:1661# ed = parser.parse(end_date).date()1662# params['end_date'] = str(ed)1663# if _from:1664# params['from'] = _from1665# if direct and direct in ['prev', 'next']:1666# params['direct'] = direct1667# if size:1668# params['size'] = size1669# path = '/v1/margin/loan-orders'1670#1671# def _wrapper(_func):1672# @wraps(_func)1673# def handle():1674# _func(api_key_get(params, path))1675#1676# return handle1677#1678# return _wrapper1679#1680# def get_margin_balance(self, symbol):1681# """1682# åè´·è´¦æ·è¯¦æ
,æ¯ææ¥è¯¢å个å¸ç§1683# :param symbol:1684# :return:1685# """1686# params = {}1687# path = '/v1/margin/accounts/balance'1688# if symbol:1689# params['symbol'] = symbol1690#1691# def _wrapper(_func):1692# @wraps(_func)1693# def handle():1694# _func(api_key_get(params, path))1695#1696# return handle1697#...
__init__.py
Source:__init__.py
1#===============================================================================2# Imports3#===============================================================================4import socket5#===============================================================================6# Globals/Aliases7#===============================================================================8HOSTNAME = socket.gethostname().encode('utf-8')9IPADDR = socket.gethostbyname(HOSTNAME)10class Constant(dict):11 def __init__(self):12 items = self.__class__.__dict__.items()13 for (key, value) in filter(lambda t: t[0][:2] != '__', items):14 try:15 self[value] = key16 except:17 pass18 def __getattr__(self, name):19 return self.__getitem__(name)20 def __setattr__(self, name, value):21 return self.__setitem__(name, value)22class _CachingBehavior(Constant):23 Default = 024 Buffered = 125 RandomAccess = 226 SequentialScan = 327 WriteThrough = 428 Temporary = 529CachingBehavior = _CachingBehavior()30_dict = dict31_list = list32_object = object33# Wrap this in a try/except handler such that we can suppress import errors;34# useful if we're using a normal Python interpreter and we want to import some35# of the other async.* classes.36try:37 import _async38 from _async import *39 _async.refresh_rio_availability()40except ImportError:41 pass42import inspect43def get_classes_in_module(module):44 isclass = inspect.isclass45 attrs = [ getattr(module, name) for name in dir(module) ]46 types = [ t for t in attrs if isclass(t) ]47 return types48def register_module_deallocs(module):49 types = get_classes_in_module(module)50 for t in types:51 _async.register_dealloc(t)52class object:53 def __init__(self, **kwds):54 self.__dict__.update(kwds)55 _async.protect(self)56def call_from_main_thread_and_wait(f):57 def decorator(*_args, **_kwds):58 return _async.call_from_main_thread_and_wait(f, _args, _kwds)59 return decorator60def call_from_main_thread(f):61 def decorator(*_args, **_kwds):62 _async.call_from_main_thread(f, _args, _kwds)63 return decorator64def critical_section(f):65 cs = _async.critical_section()66 def decorator(*_args, **_kwds):67 class _cs_wrap:68 def __enter__(self):69 cs.enter()70 def __exit__(self, *exc):71 cs.leave()72 with _cs_wrap() as _cs:73 return f(*_args, **_kwds)74 return decorator75def synchronized(o=None):76 class _sync:77 def __enter__(self):78 if o:79 _async.debug("write lock 1")80 _async.write_lock(o)81 _async.acquire_gil()82 def __exit__(self, *exc):83 if o:84 _async.debug("write unlock 1")85 _async.write_unlock(o)86 _async.release_gil()87 return _sync()88def write_lock(o):89 class _l:90 def __enter__(self):91 _async.debug("write lock 2")92 _async.write_lock(o)93 def __exit__(self, *exc):94 _async.debug("write unlock 2")95 _async.write_unlock(o)96 return _l()97def read_lock(o):98 class _l:99 def __enter__(self):100 _async.debug("read lock 2")101 _async.read_lock(o)102 def __exit__(self, *exc):103 _async.debug("read unlock 2")104 _async.read_unlock(o)105 return _l()106def submit_work(func, args=None, kwds=None, callback=None, errback=None):107 _async.submit_work(func, args, kwds, callback, errback)108def submit_wait(obj, func=None, args=None, kwds=None,109 callback=None, errback=None, timeout=None):110 _async.submit_wait(obj, timeout, func, args, kwds, callback, errback)111#def submit_write_io(writeiofunc, buf, callback=None, errback=None):112# _async.submit_write_io(writeiofunc, buf, callback, errback)113#def submit_read_io(readiofunc, callback, nbytes=0, errback=None):114# _async.submit_read_io(readiofunc, nbytes, callback, errback)115_open = open116def open(filename, mode, caching=0, size=0, template=None):117 def open_decorator(f):118 def decorator(name, mode, fileobj):119 return f(caching, size, template, name, mode, fileobj)120 return decorator121 @open_decorator122 def fileopener(caching, size, template, name, mode, fileobj):123 return _async.fileopener(caching, size, template, name, mode, fileobj)124 f = _open(125 filename,126 mode=mode,127 opener=fileopener,128 closer=_async.filecloser129 )130 r = _async._rawfile(f)131 p = _async.protect(r)132 return p133_async_open = open134def close(obj):135 _async._close(obj)136 obj.close()137def write(obj, buf, callback=None, errback=None):138 _async.submit_write_io(obj, buf, callback, errback)139def writefile(filename, buf, callback=None, errback=None):140 f = open(filename, 'wb', size=len(buf))141 _async.submit_write_io(f, buf, callback, errback)142 f.close()143def read(obj, callback, nbytes=0, errback=None):144 _async.submit_read_io(obj.write, buf, callback, errback)145def prewait(obj=None):146 if obj is None:147 obj = object()148 return _async.prewait(obj)149def pipe(reader, writer, bufsize=0, callback=None, errback=None):150 raise NotImplementedError151def wait_any(waits):152 raise NotImplementedError153def wait_all(waits):154 raise NotImplementedError155def sendfile(transport=None, before=None, filename=None, after=None):156 if not transport:157 raise ValueError("transport can not be None")158 if not filename:159 raise ValueError("filename can not be None")160 return transport.sendfile(before, filename, after)161QOTD = b'An apple a day keeps the doctor away.\r\n'162class Protocol:163 line_mode = False164 initial_bytes_to_send = None165 def connection_made(self, transport, data):166 pass167 def connection_closed(self, transport, op):168 pass169 def connection_lost(self, transport, op):170 pass171 def connection_timeout(self, transport, op):172 pass173 def connection_error(self, transport, op, syscall, errcode):174 pass175 def data_received(self, transport, data):176 pass177 def line_received(self, transport, line):178 pass179 def data_sent(self, transport, data):180 pass181 def send_failed(self, transport, data):182 pass183 def exception_handler(self, transport, exc):184 pass185class ChattyLineProtocol:186 line_mode = False187 max_line_length = 100188 wait_for_eol = True189 def connection_made(self, transport):190 _async.stdout("connection_made\n")191 def connection_closed(self, transport, op):192 _async.stdout("connection_closed: %d\n" % op)193 def connection_lost(self, transport, op):194 _async.stderr("connection_lost: %d\n" % op)195 def connection_timeout(self, transport, op):196 _async.stderr("connection_lost: %d\n" % op)197 def connection_error(self, transport, op, syscall, errcode):198 _async.stderr("connection_error: %d, %s, %d\n" % op)199 def data_received(self, transport, data):200 _async.stdout("data_received\n")201 _async.stdout(data)202 _async.stdout("\n")203 def line_received(self, transport, line):204 _async.stdout("line_received: %s\n" % line)205 def data_sent(self, transport, data):206 _async.stdout("data_sent: %s\n" % data)207 def send_failed(self, transport, data):208 _async.stderr("send_failed: %s\n", data)209 def initial_connection_error(self, transport, errcode):210 _async.stderr("initial_connection_error: %d\n" % errcode)211 def __exception_handler(self, transport, syscall, exc):212 _async.stderr("exception_handler: %s\n" % repr(exc))213# Server will be one of two types: it either sends data first, or it expects214# the client to send data first (then presumably reacts to sent data). The215# type is determined by the values of the attributes ``initial_bytes_to_send``216# and the ``expect_*`` ones.217class EchoServer:218 def data_received(self, data):219 return data220class QOTD:221 initial_bytes_to_send = QOTD222class BaseChargen:223 def __init__(self):224 self._lineno = -1225 @property226 def lineno(self):227 self._lineno += 1228 return self._lineno229 def chargen(self):230 return chargen(self.lineno)231class Chargen(BaseChargen):232 def initial_bytes_to_send(self):233 return self.chargen()234 def data_sent(self, data):235 return self.chargen()236class ChargenBrute(BaseChargen):237 def connection_made(self, sock):238 async.call_next(self.connection_made)239 return self.chargen()240class Disconnect:241 def connection_made(self, sock):242 sock.disconnect()243class Discard:244 def data_received(self, data):245 pass246class EchoData:247 def data_received(self, data):248 return data249class EchoLine:250 line_mode = True251 def line_received(self, line):252 return line253#===============================================================================254# Misc255#===============================================================================256def sys_stats():257 a = _async258 return (259 # SYSTEM_INFO stuff260 ('min_address_allocation', a._sys_min_address_allocation),261 ("max_address_allocation", a._sys_max_address_allocation),262 ("allocation_granularity", a._sys_allocation_granularity),263 ("cpu_type", a._sys_cpu_type),264 ("num_cpus", a._sys_num_cpus),265 ("active_cpu_mask", a._sys_active_cpu_mask),266 ("page_size", a._sys_page_size),267 ("cpu_level", a._sys_cpu_level),268 ("cpu_revision", a._sys_cpu_revision),269 # Misc stuff270 ("large_page_minimum", a._sys_large_page_minimum),271 ("large_pages_available", a._sys_large_pages_available),272 ("registered_io_available", a._sys_registered_io_available),273 ("min_filesystem_cache_size", a._sys_min_filesystem_cache_size),274 ("max_filesystem_cache_size", a._sys_max_filesystem_cache_size),275 ("file_cache_min_hard_enable", a._sys_file_cache_max_hard_enable),276 ("file_cache_max_hard_enable", a._sys_file_cache_max_hard_enable),277 )278def socket_stats(s):279 return (280 ('sem_acquired', s.sem_acquired),281 ('sem_released', s.sem_released),282 ('sem_timeout', s.sem_timeout),283 ('sem_count', s.sem_count),284 ('sem_release_err', s.sem_release_err),285 ('num_children', s.num_children),286 ('accepts_posted', s.accepts_posted),287 ('retired_clients', s.retired_clients),288 ('fd_accept_count', s.fd_accept_count),289 ('clients_connected', s.clients_connected),290 ('clients_disconnecting', s.clients_disconnecting),291 ('num_accepts_to_post', s.num_accepts_to_post),292 ('total_clients_reused', s.total_clients_reused),293 ('total_clients_recycled', s.total_clients_recycled),294 ('target_accepts_posted', s.target_accepts_posted),295 ('client_connected_count', s.client_connected_count),296 ('total_accepts_attempted', s.total_accepts_attempted),297 ('negative_accepts_to_post_count', s.negative_accepts_to_post_count),298 ('recvbuf_size', s.recvbuf_size),299 ('sendbuf_size', s.sendbuf_size),300 ('send_id', s.send_id),301 ('recv_id', s.recv_id),302 ('ioloops', s.ioloops),303 ('last_thread_id', s.last_thread_id),304 ('this_thread_id', s.this_thread_id),305 ('num_bytes_just_sent', s.num_bytes_just_sent),306 ('num_bytes_just_received', s.num_bytes_just_received),307 ('total_bytes_sent', s.total_bytes_sent),308 ('total_bytes_received', s.total_bytes_received),309 )310def context_stats():311 return (312 ('active_hogs', active_hogs()),313 ('active_contexts', active_contexts()),314 ('active_io_loops', active_io_loops()),315 ('seh_eav_in_io_callback', seh_eav_in_io_callback()),316 )317def memory_stats():318 return (319 ('load', _async._memory_load),320 ('total_virtual', _async._memory_total_virtual),321 ('avail_virtual', _async._memory_avail_virtual),322 ('total_physical', _async._memory_total_physical),323 ('avail_physical', _async._memory_avail_physical),324 ('total_page_file', _async._memory_total_page_file),325 ('avail_page_file', _async._memory_avail_page_file),326 )327#===============================================================================328# Helpers during interactive testing/debugging329#===============================================================================330def _tefb_json(port=8080):331 import techempower_frameworks_benchmark as tefb332 server = _async.server('0.0.0.0', port)333 _async.register(transport=server, protocol=tefb.BaseHttpServer)334 #_async.run_once()335 return server336def _t2(port=8080):337 import techempower_frameworks_benchmark as tefb338 server = _async.server('0.0.0.0', port)339 _async.register(transport=server, protocol=tefb.FastHttpServer)340 #_async.run_once()341 return server342def _j1(port=8080):343 import techempower_frameworks_benchmark as tefb344 server = _async.server('0.0.0.0', port)345 _async.register(transport=server, protocol=tefb.JsonHttpServer)346 #_async.run_once()347 return server348def _j2(port=8080):349 import techempower_frameworks_benchmark as tefb350 server = _async.server('0.0.0.0', port)351 _async.register(transport=server, protocol=tefb.JsonGmtimeHttpServer)352 #_async.run_once()353 return server354def _j3(port=8080):355 import techempower_frameworks_benchmark as tefb356 server = _async.server('0.0.0.0', port)357 _async.register(transport=server, protocol=tefb.JsonGmtimeHttpServerSlow)358 #_async.run_once()359 return server360def _j4(port=8080):361 import techempower_frameworks_benchmark as tefb362 server = _async.server('0.0.0.0', port)363 _async.register(transport=server, protocol=tefb.TestSync)364 #_async.run_once()365 return server...
transport.py
Source:transport.py
1# -----------------------------------------------------------------------------2# transport.py - Test for transports3#4# November 2015, Matthew Earl5#6# Copyright (c) 2015-2016 by Cisco Systems, Inc.7# All rights reserved.8# -----------------------------------------------------------------------------9from __future__ import absolute_import10from __future__ import division11from __future__ import print_function12from __future__ import unicode_literals13"""Tests for transports."""14from . import _utils15from .. import _async16from .. import _transport17from .._async import From, Return18try:19 import unittest.mock as mock20except ImportError:21 # For Python 2, try importing the backport.22 import mock23# Mutable versions of _async._DummyFile and _DummyProc, useful so that their24# attributes can be patched.25class _DummyFile(object):26 def __init__(self, read, write):27 self.read = read28 self.write = write29class _DummyProc(object):30 """31 Wrapper around _TestSubProcess to make `read` and `write` objects appear32 under `stdout` and `stdin` attributes, respectively.33 """34 def __init__(self, proc):35 self.stdin = _DummyFile(read=None, write=proc.write)36 self.stdout = _DummyFile(read=proc.read, write=None)37 self.terminate = proc.terminate38 self.wait = proc.wait39 self._proc = proc40 def __repr__(self):41 return "{}({!r})".format(type(self).__name__, self._proc)42class _TestSubProcess(object):43 """44 SubProcess work-a-like for testing.45 Each asynchronous method will create a future in its attributes. The test46 routine is expected to complete the future attributes to trigger particular47 callbacks, as appropriate.48 As futures are completed they are removed from the attributes.49 """50 def __init__(self):51 self._loop = None52 self.spawn_future = None53 self.wait_future = None54 self.read_future = None55 def spawn(self, args, loop):56 self._loop = loop57 self.spawn_future = _async.Future(loop=loop)58 self.spawn_future.add_done_callback(self._spawn_future_done)59 return self.spawn_future60 def _spawn_future_done(self, f):61 self.spawn_future = None62 if not f.exception():63 self.wait_future = _async.Future(loop=self._loop)64 def wait(self):65 return self.wait_future66 def terminate(self):67 pass68 def read(self, n):69 # Concurrent reads should not happen.70 assert self.read_future is None71 self.read_future = _async.Future(loop=self._loop)72 self.read_future.add_done_callback(self._read_future_done)73 return self.read_future74 def _read_future_done(self, f):75 self.read_future = None76 def write(self, d):77 pass78class _TestException(Exception):79 pass80class _SubProcessTransportBaseTest(_utils.BaseTest):81 @_async.make_task82 @_async.coroutine83 def _test_spawn_subprocess(self, args, loop=None):84 self._proc = _TestSubProcess()85 yield From(self._proc.spawn(args, loop=loop))86 # Store the dummy proc so that it can be used for attribute patching.87 self._dummy_proc = _DummyProc(self._proc)88 raise Return(self._dummy_proc)89 def setUp(self):90 super(_SubProcessTransportBaseTest, self).setUp()91 self.patcher = mock.patch.object(_async, 'spawn_subprocess',92 new=self._test_spawn_subprocess)93 self.patcher.start()94 # If extending this method, ensure `self.patcher` gets stopped.95 def tearDown(self):96 self.patcher.stop()97 super(_SubProcessTransportBaseTest, self).tearDown()98class SubProcessTransportTests(_SubProcessTransportBaseTest):99 """100 SubProcessTransport tests101 """102 def test_connect(self):103 """Basic connect / disconnect test."""104 transport = _transport.SubProcessTransport(['test_prog'])105 self.assertEqual(transport.state, _transport.State.DISCONNECTED)106 connect_fut = _async.Task(transport.connect(loop=self._loop),107 loop=self._loop)108 _async.run_until_callbacks_invoked(loop=self._loop)109 self.assertNotEqual(self._proc.spawn_future, None)110 self.assertFalse(connect_fut.done())111 self.assertEqual(transport.state, _transport.State.CONNECTING)112 self._proc.spawn_future.set_result(None)113 _async.run_until_callbacks_invoked(loop=self._loop)114 self.assertEqual(connect_fut.result(), None)115 self.assertEqual(transport.state, _transport.State.CONNECTED)116 disconnect_fut = _async.Task(transport.disconnect(),117 loop=self._loop)118 _async.run_until_callbacks_invoked(loop=self._loop)119 self.assertFalse(disconnect_fut.done())120 self.assertEqual(transport.state, _transport.State.CONNECTED)121 self._proc.wait_future.set_result(None)122 _async.run_until_callbacks_invoked(loop=self._loop)123 self.assertEqual(disconnect_fut.result(), None)124 self.assertEqual(transport.state, _transport.State.DISCONNECTED)125 126 def test_connect_error(self):127 """Connection failure."""128 transport = _transport.SubProcessTransport(['test_prog'])129 connect_fut = _async.Task(transport.connect(loop=self._loop),130 loop=self._loop)131 _async.run_until_callbacks_invoked(loop=self._loop)132 self.assertNotEqual(self._proc.spawn_future, None)133 self.assertFalse(connect_fut.done())134 self.assertEqual(transport.state, _transport.State.CONNECTING)135 self._proc.spawn_future.set_exception(_TestException)136 _async.run_until_callbacks_invoked(loop=self._loop)137 with self.assertRaises(_transport.TransportConnectionError):138 self.assertEqual(connect_fut.result(), None)139 self.assertEqual(transport.state, _transport.State.DISCONNECTED)140 connect_fut = None141 def test_connect_while_connecting_or_connected(self):142 # Start the first connection.143 transport = _transport.SubProcessTransport(['test_prog'])144 connect_fut = _async.Task(transport.connect(loop=self._loop),145 loop=self._loop)146 _async.run_until_callbacks_invoked(loop=self._loop)147 self.assertEqual(transport.state, _transport.State.CONNECTING)148 # Try and connect again while the first is in progress. Check it fails.149 connect_fut2 = _async.Task(transport.connect(loop=self._loop),150 loop=self._loop)151 _async.run_until_callbacks_invoked(loop=self._loop)152 self.assertTrue(connect_fut2.done())153 with self.assertRaises(_transport.TransportConnectionError):154 connect_fut2.result()155 del connect_fut2156 self.assertEqual(transport.state, _transport.State.CONNECTING)157 # Complete the first connection (succesfully).158 self._proc.spawn_future.set_result(None)159 _async.run_until_callbacks_invoked(loop=self._loop)160 self.assertEqual(connect_fut.result(), None)161 self.assertEqual(transport.state, _transport.State.CONNECTED)162 # Try and connect again. Check it fails.163 connect_fut2 = _async.Task(transport.connect(loop=self._loop),164 loop=self._loop)165 _async.run_until_callbacks_invoked(loop=self._loop)166 self.assertTrue(connect_fut2.done())167 with self.assertRaises(_transport.TransportConnectionError):168 connect_fut2.result()169 del connect_fut2170 self.assertEqual(transport.state, _transport.State.CONNECTED)171 # Disconnect.172 disconnect_fut = _async.Task(transport.disconnect(),173 loop=self._loop)174 _async.run_until_callbacks_invoked(loop=self._loop)175 self._proc.wait_future.set_result(None)176 _async.run_until_callbacks_invoked(loop=self._loop)177 self.assertEqual(disconnect_fut.result(), None)178 self.assertEqual(transport.state, _transport.State.DISCONNECTED)179 def test_disconnect_when_disconnected(self):180 transport = _transport.SubProcessTransport(['test_prog'])181 disconnect_fut = _async.Task(transport.disconnect(),182 loop=self._loop)183 _async.run_until_callbacks_invoked(loop=self._loop)184 with self.assertRaises(_transport.TransportNotConnected):185 disconnect_fut.result()186 self.assertEqual(transport.state, _transport.State.DISCONNECTED)187 def test_disconnect_when_connecting(self):188 # Start the first connection.189 transport = _transport.SubProcessTransport(['test_prog'])190 connect_fut = _async.Task(transport.connect(loop=self._loop),191 loop=self._loop)192 _async.run_until_callbacks_invoked(loop=self._loop)193 self.assertEqual(transport.state, _transport.State.CONNECTING)194 # Start a disconnection.195 disconnect_fut = _async.Task(transport.disconnect(),196 loop=self._loop)197 _async.run_until_callbacks_invoked(loop=self._loop)198 self.assertEqual(transport.state, _transport.State.CONNECTING)199 # Complete the connection, and check that afterwards disconnection has200 # completed.201 self._proc.spawn_future.set_result(None)202 _async.run_until_callbacks_invoked(loop=self._loop)203 self._proc.wait_future.set_result(None)204 _async.run_until_callbacks_invoked(loop=self._loop)205 self.assertEqual(connect_fut.result(), None)206 self.assertEqual(disconnect_fut.result(), None)207 self.assertEqual(transport.state, _transport.State.DISCONNECTED)208 def test_read_when_disconnected(self):209 transport = _transport.SubProcessTransport(['test_prog'])210 read_fut = _async.Task(transport.read(), self._loop)211 _async.run_until_callbacks_invoked(loop=self._loop)212 with self.assertRaises(_transport.TransportNotConnected):213 read_fut.result()214 def test_write_when_disconnected(self):215 transport = _transport.SubProcessTransport(['test_prog'])216 with self.assertRaises(_transport.TransportNotConnected):217 transport.write(b'')218 def test_concurrent_reads(self):219 # Connect.220 transport = _transport.SubProcessTransport(['test_prog'])221 self.assertEqual(transport.state, _transport.State.DISCONNECTED)222 _async.Task(transport.connect(loop=self._loop),223 loop=self._loop)224 _async.run_until_callbacks_invoked(loop=self._loop)225 self.assertNotEqual(self._proc.spawn_future, None)226 self._proc.spawn_future.set_result(None)227 _async.run_until_callbacks_invoked(loop=self._loop)228 self.assertEqual(transport.state, _transport.State.CONNECTED)229 # Start two concurrent reads.230 read_fut1 = _async.Task(transport.read(), loop=self._loop)231 _async.run_until_callbacks_invoked(loop=self._loop)232 read_fut2 = _async.Task(transport.read(), loop=self._loop)233 _async.run_until_callbacks_invoked(loop=self._loop)234 # Check the first is still pending, but the second has asserted.235 self.assertFalse(read_fut1.done())236 with self.assertRaises(AssertionError):237 read_fut2.result()238 # Complete the first read.239 self._proc.read_future.set_result(b'Data')240 _async.run_until_callbacks_invoked(loop=self._loop)241 self.assertEqual(read_fut1.result(), b'Data')242 # Disconnect.243 disconnect_fut = _async.Task(transport.disconnect(),244 loop=self._loop)245 _async.run_until_callbacks_invoked(loop=self._loop)246 self._proc.wait_future.set_result(None)247 _async.run_until_callbacks_invoked(loop=self._loop)248 self.assertEqual(disconnect_fut.result(), None)249 self.assertEqual(transport.state, _transport.State.DISCONNECTED)250class SubProcessTransportTestsNoGCCheck(_SubProcessTransportBaseTest):251 """252 SubProcessTransport tests which result in cycles due to `MagicMock`.253 """254 _gc_checks = False255 def test_write_error(self):256 # Set up a connection.257 transport = _transport.SubProcessTransport(['test_prog'])258 self.assertEqual(transport.state, _transport.State.DISCONNECTED)259 connect_fut = _async.Task(transport.connect(loop=self._loop),260 loop=self._loop)261 _async.run_until_callbacks_invoked(loop=self._loop)262 self.assertNotEqual(self._proc.spawn_future, None)263 self._proc.spawn_future.set_result(None)264 _async.run_until_callbacks_invoked(loop=self._loop)265 self.assertEqual(connect_fut.result(), None)266 self.assertEqual(transport.state, _transport.State.CONNECTED)267 # Attempt a write, but inject an error.268 with mock.patch.object(self._dummy_proc.stdin, 'write',269 side_effect=_TestException):270 with mock.patch.object(self._dummy_proc,271 'terminate') as mock_terminate:272 transport.write(b'')273 mock_terminate.assert_called_once_with()274 275 # Expect the transport to disconnect.276 self._proc.wait_future.set_result(None)277 _async.run_until_callbacks_invoked(loop=self._loop)278 self.assertEqual(transport.state, _transport.State.DISCONNECTED)...
test_async.py
Source:test_async.py
1import os2import sys3import atexit4import unittest5import tempfile6import async7import _async8import socket9from socket import (10 AF_INET,11 SOCK_STREAM,12)13def tcpsock():14 return socket.socket(AF_INET, SOCK_STREAM)15CHARGEN = [16r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg""",17r"""!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefgh""",18r""""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghi""",19r"""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghij""",20r"""$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijk""",21]22QOTD = 'An apple a day keeps the doctor away.\r\n'23ECHO_HOST = ('echo.snakebite.net', 7)24QOTD_HOST = ('qotd.snakebite.net', 17)25DISCARD_HOST = ('discard.snakebite.net', 9)26DAYTIME_HOST = ('daytime.snakebite.net', 13)27CHARGEN_HOST = ('chargen.snakebite.net', 19)28SERVICES_IP = socket.getaddrinfo(*ECHO_HOST)[0][4][0]29ECHO_IP = (SERVICES_IP, 7)30DISCARD_IP = (SERVICES_IP, 9)31DAYTIME_IP = (SERVICES_IP, 13)32CHARGEN_IP = (SERVICES_IP, 19)33NO_CB = None34NO_EB = None35HOST = '127.0.0.1'36ADDR = (HOST, 0)37TEMPDIR = None38def rmtempdir():39 if TEMPDIR:40 TEMPDIR.cleanup()41def tempfile():42 if not TEMPDIR:43 TEMPDIR = tempfile.TemporaryDirectory()44 assert os.path.isdir(TEMPDIR)45 atexit.register(rmtempdir)46 assert os.path.isdir(TEMPDIR)47 f = tempfile.NamedTemporaryFile(dir=TEMPDIR, delete=False)48 assert os.path.isfile(f)49 return f50def tempfilename():51 f = tempfile()52 f.close()53 return f.name54class TestBasic(unittest.TestCase):55 def test_calling_run_with_no_events_fails(self):56 self.assertRaises(AsyncRunCalledWithoutEventsError, _async.run_once)57class TestSubmitWork(unittest.TestCase):58 def test_submit_simple_work(self):59 def f(i):60 return i * 261 def cb(r):62 _async.call_from_main_thread(63 self.assertEqual,64 (r, 4),65 )66 _async.submit_work(f, 2, None, cb, None)67 _async.run()68 def test_value_error_in_callback(self):69 def f():70 return laksjdflaskjdflsakjdfsalkjdf71 _async.submit_work(f, None, None, None, None)72 self.assertRaises(NameError, _async.run)73 def test_value_error_in_callback_then_run(self):74 def f():75 return laksjdflaskjdflsakjdfsalkjdf76 _async.submit_work(f, None, None, None, None)77 self.assertRaises(NameError, _async.run)78 _async.run()79 def test_multiple_value_errors_in_callback_then_run(self):80 def f():81 return laksjdflaskjdflsakjdfsalkjdf82 _async.submit_work(f, None, None, None, None)83 _async.submit_work(f, None, None, None, None)84 self.assertRaises(NameError, _async.run)85 self.assertRaises(NameError, _async.run)86 _async.run()87 def test_call_from_main_thread(self):88 d = {}89 def f(i):90 _async.call_from_main_thread_and_wait(91 d.__setitem__,92 ('foo', i*2),93 )94 return _async.call_from_main_thread_and_wait(95 d.__getitem__, 'foo'96 )97 def cb(r):98 _async.call_from_main_thread(99 self.assertEqual,100 (r, 4),101 )102 _async.submit_work(f, 2, None, cb, None)103 _async.run()104 def test_call_from_main_thread_decorator(self):105 @async.call_from_main_thread106 def f():107 self.assertFalse(_async.is_parallel_thread)108 _async.submit_work(f, None, None, None, None)109 _async.run()110 def test_submit_simple_work_errback_invoked(self):111 def f():112 return laksjdflaskjdflsakjdfsalkjdf113 def test_e(et, ev, eb):114 try:115 f()116 except NameError as e2:117 self.assertEqual(et, e2.__class__)118 self.assertEqual(ev, e2.args[0])119 self.assertEqual(eb.__class__, e2.__traceback__.__class__)120 else:121 self.assertEqual(0, 1)122 def cb(r):123 _async.call_from_main_thread(self.assertEqual, (0, 1))124 def eb(e):125 _async.call_from_main_thread_and_wait(test_e, e)126 _async.submit_work(f, None, None, cb, eb)127 _async.run()128class TestSubmitFileIO(unittest.TestCase):129 def test_write(self):130 n = tempfilename()131 f = open(n, 'w')132 _async.submit_io(f.write, b'foo', None, None, None)133 _async.run()134 f.close()135 with open(n, 'w') as f:136 self.assertEqual(f.read(), b'foo')137 def test_read(self):138 @async.call_from_main_thread139 def cb(d):140 self.assertEqual(d, b'foo')141 n = tempfilename()142 with open(n, 'w') as f:143 f.write(b'foo')144 f = open(n, 'r')145 _async.submit_io(f.read, None, None, cb, None)146 _async.run()147class TestConnectSocketIO(unittest.TestCase):148 def test_backlog(self):149 sock = tcpsock()150 port = sock.bind(ADDR)151 sock.listen(100)152 self.assertEqual(sock.backlog, 100)153 sock.close()154 def test_connect(self):155 @async.call_from_main_thread156 def cb():157 self.assertEqual(1, 1)158 sock = tcpsock()159 _async.connect(sock, DISCARD_IP, 1, None, cb, NO_EB)160 _async.run()161 def test_connect_with_data(self):162 @async.call_from_main_thread163 def cb(sock):164 self.assertEqual(1, 1)165 sock = tcpsock()166 _async.connect(sock, DISCARD_IP, 1, b'buf', cb, NO_EB)167 _async.run()168 def test_connect_with_data(self):169 @async.call_from_main_thread170 def cb(sock):171 self.assertEqual(1, 1)172 sock = tcpsock()173 _async.connect(sock, DISCARD_IP, 1, b'buf', cb, NO_EB)174 _async.run()175 def test_connect_then_recv(self):176 @async.call_from_main_thread177 def _check(data):178 self.assertEqual(data, QOTD)179 def read_cb(sock, data):180 _check(data)181 def connect_cb(sock):182 _async.recv(sock, read_cb, NO_EB)183 sock = tcpsock()184 _async.connect(sock, QOTD_IP, 1, None, connect_cb, NO_EB)185 _async.run()186 def test_connect_with_data_then_recv(self):187 @async.call_from_main_thread188 def _check(data):189 self.assertEqual(data, b'hello')190 def read_cb(sock, data):191 _check(data)192 def connect_cb(sock):193 _async.recv(sock, read_cb, NO_EB)194 sock = tcpsock()195 _async.connect(sock, ECHO_IP, 1, b'hello', connect_cb, NO_EB)196 _async.run()197 def test_connect_then_send_then_recv(self):198 @async.call_from_main_thread199 def _check(data):200 self.assertEqual(data, b'hello')201 def read_cb(sock, data):202 _check(data)203 def connect_cb(sock):204 _async.recv(sock, read_cb, NO_EB)205 _async.send(sock, b'hello', NO_CB, NO_EB)206 sock = tcpsock()207 _async.connect(sock, ECHO_IP, 1, None, connect_cb, NO_EB)208 _async.run()209 def test_recv_before_connect_with_data_then_recv(self):210 @async.call_from_main_thread211 def _check(data):212 self.assertEqual(data, b'hello')213 def read_cb(sock, data):214 _check(data)215 sock = tcpsock()216 _async.recv(sock, read_cb, NO_EB)217 _async.connect(sock, ECHO_IP, 1, b'hello', NO_CB, NO_EB)218 _async.run()219 def test_recv_before_connect_then_send_then_recv(self):220 @async.call_from_main_thread221 def _check(data):222 self.assertEqual(data, b'hello')223 def read_cb(sock, data):224 _check(data)225 def connect_cb(sock):226 _async.send(sock, b'hello', NO_CB, NO_EB)227 sock = tcpsock()228 _async.recv(sock, read_cb, NO_EB)229 _async.connect(sock, ECHO_IP, 1, None, connect_cb, NO_EB)230 _async.run()231class TestAcceptSocketIO(unittest.TestCase):232 def test_accept(self):233 @async.call_from_main_thread234 def new_connection(sock, data):235 self.assertEqual(data, b'hello')236 sock = tcpsock()237 port = sock.bind(ADDR)238 addr = sock.getsockname()239 sock.listen(1)240 _async.accept(sock, new_connection, NO_EB)241 client = tcpsock()242 _async.connect(client, addr, 1, b'hello', NO_CB, NO_EB)243 _async.run()244 sock.close()245 def test_accept_backlog2(self):246 counter = 0247 @async.call_from_main_thread248 def new_connection(sock, data):249 self.assertEqual(data, b'hello')250 counter += 1251 sock = tcpsock()252 port = sock.bind(ADDR)253 addr = sock.getsockname()254 sock.listen(2)255 _async.accept(sock, new_connection, NO_EB)256 client = tcpsock()257 _async.connect(client, addr, 2, b'hello', NO_CB, NO_EB)258 _async.run()259 self.assertEqual(counter, 2)260if __name__ == '__main__':261 unittest.main()...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!