Пример #1
0
 def setup(self):
     # 获取session对象
     self.session = requests.session()
     # 获取Api对象
     self.api = Api(self.session)
     # 获取ApiRealName对象
     self.realname = self.api.api_get_ApiRealName()
Пример #2
0
 def up():
     if Instrument.get_instruments_count() == 0:
         api = Api()
         instruments = api.get_instruments()
         out = []
         for instrument in instruments:
             model = Instrument()
             model.instrument = str(instrument["instrument"])
             model.pip = instrument["pip"]
             model.name = str(instrument["displayName"])
             model.not_working_time = [{
                 "start": {
                     "year": None,
                     "month": None,
                     "day": None,
                     "day_of_week": 4,
                     "hour": 22,
                     "minute": None,
                     "second": None
                 },
                 "end": {
                     "year": None,
                     "month": None,
                     "day": None,
                     "day_of_week": 6,
                     "hour": 22,
                     "minute": None,
                     "second": None
                 }
             }]
             out.append(model)
         if len(out) > 0:
             Instrument.save_many(out)
Пример #3
0
    def test02_mock(self):
        self.api = Api(self.session)
        # 1、注册接口
        self.api.api_get_ApiRegLogin().api_register("13600001115", 8888, "test123", 666666)
        # 2、登录
        self.api.api_get_ApiRegLogin().api_login("13600001115", "test123")
        # 3、认证
        self.api.api_get_ApiRealName().api_realname("张三", "110101199008075399")
        # 4、开户
        result = self.api.api_get_ApiRealName().api_trust()
        # 5、三方开户
        r = parser_html(result)
        result = self.session.post(url=r[0], data=r[1])
        print("开户结果为:", result.text)
        common_assert(result, expect_text="OK")

        # 6、充值验证码
        self.api.api_get_ApiRealName().api_verify_code(123123)
        # 7、充值
        result = self.api.api_get_ApiRealName().api_recharge(1000, 8888)
        # 8、三方充值
        r = parser_html(result)
        result = self.session.post(url=r[0], data=r[1])
        print("充值结果为:", result.text)
        common_assert(result, expect_text="OK")

        # 9、投资
        result = self.api.api_get_ApiTender().api_tender(642, 100, -1)
        # 10、三方投资
        r = parser_html(result)
        result = self.session.post(url=r[0], data=r[1])
        print("投资结果为:", result.text)
        common_assert(result, expect_text="OK")
Пример #4
0
    def __init__(self, settings, api: ApiAbstraction = None):
        MerchantBaseLogic.__init__(self)

        self.settings = settings
        '''
            Internal state handling
        '''
        self.execQueue = []
        '''
            Information store
        '''
        self.products = {}
        self.offers = {}
        '''
            Predefined API token
        '''
        self.merchant_id = settings["merchant_id"]
        self.merchant_token = settings["merchant_token"]
        '''
            Setup API
        '''
        if api is None:
            self.api = Api(self.merchant_token,
                           self.settings["marketplace_url"],
                           self.settings["producer_url"])
        else:
            self.api = api
Пример #5
0
 def setup(self):
     # 获取session
     self.session = requests.session()
     # 获取ApiRegLogin对象
     self.login = Api(self.session).api_get_ApiRegLogin()
     # 获取ApiTender对象
     self.tender = Api(self.session).api_get_ApiTender()
Пример #6
0
class SuperMerchant(MerchantBaseLogic):
    def __init__(self, settings, api: ApiAbstraction = None):
        MerchantBaseLogic.__init__(self)

        self.settings = settings
        '''
            Internal state handling
        '''
        self.execQueue = []
        '''
            Information store
        '''
        self.products = {}
        self.offers = {}
        '''
            Predefined API token
        '''
        self.merchant_id = settings["merchant_id"]
        self.merchant_token = settings["merchant_token"]
        '''
            Setup API
        '''
        if api is None:
            self.api = Api(self.merchant_token,
                           self.settings["marketplace_url"],
                           self.settings["producer_url"])
        else:
            self.api = api

    def update_api_endpoints(self):
        """
        Updated settings may contain new endpoints, so they need to be set in the api client as well.
        However, changing the endpoint (after simulation start) may lead to an inconsistent state
        :return: None
        """
        self.api.update_marketplace_url(self.settings["marketplace_url"])
        self.api.update_producer_url(self.settings["producer_url"])

    '''
        Implement Abstract methods / Interface
    '''

    @abstractmethod
    def execute_logic(self):
        pass

    def get_settings(self):
        return self.settings

    def update_settings(self, new_settings):
        MerchantBaseLogic.update_settings(self, new_settings)
        self.update_api_endpoints()
        return self.settings

    def sold_offer(self, offer):
        pass
Пример #7
0
    def get_tweets(self):

        api = Api.twitter_api()
        tweets_ = []
        created = []
        hashtag = []

        for search_word in self.search_words:

            new_search = search_word + " -filter:retweets"  # Filter retweets
            tweets = tw.Cursor(api.search, q=new_search,
                               lang='en').items(self.n_tweets)

            for tweet in tweets:
                tweets_.append(tweet.text)  # Get tweets
                created.append(tweet.created_at)  # Get timestamp
                hashtag.append(search_word)

        dataset = pd.DataFrame({
            "hashtag": hashtag,
            "created_at": created,
            "tweet": tweets_
        })
        store_data = DataHandler('twitter', self.search_words)
        store_data.store_network_dataset(dataset)
Пример #8
0
    def search_device_status(self, mid, result, log):
        i = 0
        apiobj = Api()
        log.info('开始获取设备状态。。。。。。{}'.format(datetime.datetime.now()))
        count = 3
        while i < count:
            time.sleep(1)
            jsonvalue = apiobj.post(mid)
            if jsonvalue.get("code") == 200:
                log.info('第{}次获取设备状态成功。。。。。。{}'.format(
                    i, datetime.datetime.now()))
                result["device_status"] = jsonvalue
                break
            elif i == count - 1:
                result["device_status"] = jsonvalue

            i = i + 1
Пример #9
0
    def test_hrm_create_employee(self):
        # emp_id = random.randint(10000, 99999)

        emp_id = str(int(time.time() * 100))[-6::]

        api = Api()
        api.sign_in()
        resp = api.add_employee(emp_id,
                                "Billy",
                                "Elliot",
                                file=f'{PROJ_PATH}/empty.png')

        self.write_to_file(self._testMethodName, resp.text)

        self.assertIn('/pim/viewPersonalDetails/empNumber/', resp.url)

        emp_number = resp.url.split('/')[-1]
Пример #10
0
 def __init__(self):
     Resource.__init__(self)
     self.putChild("ajax", App())
     self.putChild("api", Api())
     self.putChild("", AuthWeiXin(back_data))
     self.putChild("search", Serch())
     self.putChild("static", StaticFile())
     self.putChild("logo", Logo())
Пример #11
0
def main():
    api = Api()

    app = web.Application()
    app.on_startup.append(api.init_connection)
    app.router.add_routes(get_routes(api))
    app.router.add_static('/static/', './front/')

    web.run_app(app, port=3000)
Пример #12
0
    async def on_ready(self):
        if self.on:
            return
        load_custom_emojis(self)
        self._define_shared()
        self.api = Api(self)
        await self.load_modules()
        await self.module_method('on_ready')
        self._on = True

        self.loop.create_task(self.voice_handler())
        self.loop.create_task(self.panel_auto_remover())
        print("Muron ON")
def test_api_add_subscription_negative(email, name, time, comment,
                                       finally_clear_subscriptions):
    """ Параметризованный негативный тест проверяет через API создание
        новых подписок с разными параметрами.
        Тестовые данные лежат в папке tests/test_data/test_incorrect_data.json
        """
    logging.info(f'API тест: {comment}')

    data = {'email': email, 'name': name, 'time': time, 'comment': comment}

    #   Отправка POST запроса для создания новой подписки
    status_code, json_data = Api.add_subscription(data)
    #   Проверка что POST запрос отработал
    assert status_code == 200
    assert 'error' in json_data
    logging.info(str(json_data))
Пример #14
0
    def __init__(self, exchange_key_list):
#         self.exchange = exchange
#         self.routing_key = key
        self.exchange_key_list = exchange_key_list
        
        #event variables
        self.eventMap = {}
        
        #cherrypy interface
        self.ui = Ui(self)
        self.ui.api = Api(self)
        
        #reading config
        self.config = JSONObject(file(os.path.join(os.path.dirname(__file__), "..", "", "config.json"), "rb"))
        self.host = str(self.config.rabbitmq.host)
        self.port = self.config.rabbitmq.port
        self.websocketport = str(self.config.websocket.port)
        self.websockethost = self.config.websocket.host
Пример #15
0
 def test_add_desktop(self):
     # res = self.add_desktop.add_desktop()
     data = yaml.safe_load(open('D:/script/fastapp/data/add_desktop.yaml'))
     # res = AddDesktop().add_desktop(data)
     # res = LogIn().login(data)
     res = Api().api(data)
     print('请求url:' + res.url)
     print('requestId:' + res.headers['requestId'])
     print(res.json())
     assert res.status_code == 200
     assert res.json()['retCode'] == 0
     assert res.json()['isExpire'] == 1
     assert res.json()['data']['status'] == 2
Пример #16
0
def find_train_size(csv, data_type, r2_min, target, features, indices):
    splitter = Splitter("csvs/" + csv, data_type)
    train_size = 0.2
    #splitter.split(data_type)
    new_filename = splitter.make_csv(csv[:-4], data_type)
    degree = 6
    i = 0
    while train_size < 0.7 and i < 10:
        # print "Train Set = " + str(train_size)
        #print "Data amount = " + str(data_amount)
        # print "R2_min = " + str(r2_min)
        result, reg = \
            Api.start("csvs/" + csv, data_type, train_size, new_filename, degree, r2_min=r2_min, target=target, features=features, indices=indices)
        if result == True:
            # print train_size
            success.add(tuple([csv, data_type]))
            return reg
        if result == False and i == 9:
            i = 0
            train_size +=0.01
        i+=1
Пример #17
0
    def __init__(self):
        self.api = Api()
        self.websocket = Websocket()
        self.image_util = ImageUtil("btcf")

        self.last_source = None
        self.update = None
        self.source = sources[0]
        self.symbol = 'btcusdt'
        self.app = 'update_setting'
        self.alert = Alert()

        self.path = currpath
        self.indicator = AppIndicator3.Indicator.new(
            self.app, currpath + "/icons/btc.png",
            AppIndicator3.IndicatorCategory.SYSTEM_SERVICES)
        self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
        self.create_menu()

        self.start_source()

        notify.init(self.app)
Пример #18
0
    def get_tweets(self):

        api = Api.twitter_api()
        tweets = api.user_timeline(screen_name=self.tt_user,
                                   count=200,
                                   tweet_mode='extended',
                                   include_rts=False,
                                   exclude_replies=True)
        last_id = tweets[-1].id
        while (True):
            more_tweets = api.user_timeline(screen_name=self.tt_user,
                                            count=200,
                                            include_rts=False,
                                            exclude_replies=True,
                                            max_id=last_id - 1)
            if (len(more_tweets) == 0):
                break
            else:
                last_id = more_tweets[-1].id - 1
                tweets = tweets + more_tweets

        created = []
        tweet_id = []
        text = []
        hashtags = []
        symbols = []
        image_url = []
        user_mentions = []
        user_id = []
        user_name = []
        user_screen_name = []
        user_location = []
        user_description = []
        user_protected = []
        user_followers_count = []
        user_friends_count = []
        user_listed_count = []
        user_created_at = []
        user_favourites_count = []
        user_utc_offset = []
        user_timezone = []
        user_geo_enabled = []
        user_verified = []
        user_statuses_count = []
        user_lang = []
        user_contributors_enabled = []
        user_is_translator = []
        user_is_translation_enabled = []
        quoted_status = []
        quoted_text = []
        quoted_media = []
        quoted_user_id = []

        for tweet in tweets:

            created.append(tweet.created_at)
            tweet_id.append(tweet.id)
            try:
                text.append(tweet.full_text)
            except AttributeError:
                text.append(tweet.text)
            hashtags.append(tweet.entities['hashtags'])
            symbols.append(tweet.entities['symbols'])
            user_mentions.append(tweet.entities['user_mentions'])
            user_id.append(tweet.user.id)
            user_name.append(tweet.user.name)
            user_screen_name.append(tweet.user.screen_name)
            user_location.append(tweet.user.location)
            user_description.append(tweet.user.description)
            user_protected.append(tweet.user.protected)
            user_followers_count.append(tweet.user.followers_count)
            user_friends_count.append(tweet.user.friends_count)
            user_listed_count.append(tweet.user.listed_count)
            user_created_at.append(tweet.user.created_at.strftime("%Y-%m-%d"))
            user_favourites_count.append(tweet.user.favourites_count)
            user_utc_offset.append(tweet.user.utc_offset)
            user_timezone.append(tweet.user.time_zone)
            user_geo_enabled.append(tweet.user.geo_enabled)
            user_verified.append(tweet.user.verified)
            user_statuses_count.append(tweet.user.statuses_count)
            user_lang.append(tweet.user.lang)
            user_contributors_enabled.append(tweet.user.contributors_enabled)
            user_is_translator.append(tweet.user.is_translator)
            user_is_translation_enabled.append(
                tweet.user.is_translation_enabled)

            if tweet.is_quote_status == True:

                try:
                    quoted_text.append(tweet.quoted_status.text)
                except AttributeError:
                    quoted_text.append(np.nan)
                try:
                    quoted_user_id.append(tweet.quoted_status.user.id)
                except AttributeError:
                    quoted_user_id.append(np.nan)
                try:
                    quoted_media.append(
                        tweet.quoted_status.entities['media'][0]['media_url'])
                except Exception:
                    quoted_media.append(np.nan)
            else:
                quoted_text.append(np.nan)
                quoted_user_id.append(np.nan)
                quoted_media.append(np.nan)

            try:
                image_url.append(tweet.entities['media'][0]['media_url'])
            except:
                image_url.append(np.nan)

        dataset = pd.DataFrame({
            "created_at": created,
            "tweet_id": tweet_id,
            "text": text,
            "hashtags": hashtags,
            "symbols": symbols,
            "image_url": image_url,
            "user_mentions": user_mentions,
            "user_id": user_id,
            "user_name": user_name,
            "user_screen_name": user_screen_name,
            "user_location": user_location,
            "user_description": user_description,
            "user_protected": user_protected,
            "user_followers_count": user_followers_count,
            "user_friends_count": user_friends_count,
            "user_listed_count": user_listed_count,
            "user_created_at": user_created_at,
            "user_favourites_count": user_favourites_count,
            "user_utc_offset": user_utc_offset,
            "user_timezone": user_timezone,
            "user_geo_enabled": user_geo_enabled,
            "user_verified": user_verified,
            "user_statuses_count": user_statuses_count,
            "user_lang": user_lang,
            "user_contributors_enabled": user_contributors_enabled,
            "user_is_translator": user_is_translator,
            "user_is_translation_enabled": user_is_translation_enabled,
            "quoted_text": quoted_text,
            "quoted_media": quoted_media,
            "quoted_user_id": quoted_user_id,
        })

        store_data = DataHandler('twitter', self.tt_user)
        store_data.store_network_dataset(dataset)
        import pdb
        pdb.set_trace()
        print('a')
Пример #19
0
 def setup(self):
     # 获取session对象
     self.session = requests.session()
     # 获取ApiRegLogin对象
     self.reg = Api(self.session).api_get_ApiRegLogin()
     self.result = None
Пример #20
0
def post_details(request, id):
    post = PostsApi.post_by_id(PostsApi, id)
    replies = Api.get_all(Api, reply_url, user_id=None,
                          search=None, post_id=id)
    return render(request, 'post_details.html', {'post': post, 'replies': replies})
Пример #21
0
def main():
    inputClient = InputClient()
    api = Api()
    usage = "usage: %prog [options] [arg]"
    parser = OptionParser(usage)
    parser.add_option('-l',
                      '--list',
                      action='store_true',
                      dest="iflist",
                      help=u"列出所有的ssh连接")
    parser.add_option('-a',
                      '--add',
                      action='store_true',
                      dest="ifadd",
                      help=u"添加ssh连接")
    parser.add_option('-i',
                      '--host',
                      action="store",
                      dest="host",
                      help=u"连接的host")
    parser.add_option('-d', action='store', dest='del_host', help=u"删除ssh连接")
    parser.add_option('-D',
                      '--delete-by-index',
                      action='store_true',
                      dest='del_by_index',
                      help=u"通过index删除ssh连接")
    parser.add_option('-u', '--update', action="store_true", dest="ifupdate")
    # parser.add_option('-')

    (option, args) = parser.parse_args()
    opt_dict = eval(str(option))
    opt_values = opt_dict.values()
    param_len = len(opt_values) - opt_values.count(None)
    output = OutputClient()
    output.set_header(['index', 'Host', 'UserName'], [7, 17, 15])
    if param_len > 1:
        raise ParamsException('参数错误')
    elif param_len == 0:
        if len(args) > 0:
            host = args[0]
            ssh_conn = api.get_ssh_connect(host)
            if ssh_conn is not None:
                api.login(ssh_conn.get('host'), ssh_conn.get('name'),
                          ssh_conn.get('passwd'))
            else:
                ssh_conns = api.login_fuzzy(host)
                con_len = len(ssh_conns)
                if con_len == 0:
                    sys.stdout.write("没有匹配的Host!\n")
                    return
                elif con_len == 1:
                    api.login(ssh_conns[0].get('host'),
                              ssh_conns[0].get('name'),
                              ssh_conns[0].get('passwd'))
                    return
                else:
                    output.set_values(ssh_conns)
                    sys.stdout.write(output.show())
                    sys.stdout.write('\n')
                    ssh_conn = output.select()
                    api.login(ssh_conn.get('host'), ssh_conn.get('name'),
                              ssh_conn.get('passwd'))
                    return
            return
        else:
            ssh_conns = api.list_ssh_connects()
            output.set_values(ssh_conns)
            # print output.show()
            sys.stdout.write(output.show())
            sys.stdout.write('\n')
            if len(ssh_conns) > 0:
                ssh_conn = output.select()
                api.login(ssh_conn.get('host'), ssh_conn.get('name'),
                          ssh_conn.get('passwd'))
            return
    else:
        iflist = option.iflist
        ifadd = option.ifadd
        host = option.host
        ifupdate = option.ifupdate
        del_host = option.del_host
        del_by_index = option.del_by_index
        try:
            if iflist:
                ssh_conns = api.list_ssh_connects()
                # print ssh_conns
                output.set_values(ssh_conns)
                sys.stdout.write(output.show())
                sys.stdout.write('\n')
                return
            if ifadd:
                host = inputClient.input_host()
                username = inputClient.input_username()
                password = inputClient.input_password()
                api.add_ssh_connect(host, username, password)
                # print host, username, password
                return
            if host:
                ssh_conn = api.get_ssh_connect(host)
                if ssh_conn is None:
                    raise Exception("错误: 主机 %s 不存在!" % host)
                else:
                    api.login(ssh_conn.get('host'), ssh_conn.get('name'),
                              ssh_conn.get('passwd'))
            if ifupdate:
                ssh_conns = api.list_ssh_connects()
                # print ssh_conns
                output.set_values(ssh_conns)
                sys.stdout.write(output.show())
                sys.stdout.write('\n')
                if len(ssh_conns) > 0:
                    ssh_conn = output.select_to_update()
                    username = inputClient.input_username()
                    password = inputClient.input_password()
                    api.update_ssh_connect(ssh_conn.get('host'), username,
                                           password)
                    sys.stdout.write('更新成功!\n')
            if del_host:
                ssh_conn = api.get_ssh_connect(del_host)
                if ssh_conn is None:
                    raise Exception("错误: 主机 %s 不存在!" % host)
                api.del_ssh_connect(del_host)
                sys.stdout.write('删除成功!\n')
            if del_by_index:
                ssh_conns = api.list_ssh_connects()
                # print ssh_conns
                output.set_values(ssh_conns)
                sys.stdout.write(output.show())
                sys.stdout.write('\n')
                if len(ssh_conns) > 0:
                    ssh_conn = output.select_to_del()
                    api.del_ssh_connect(ssh_conn.get('host'))
                    sys.stdout.write('删除成功!\n')
                return
        except ParamsException as e:
            sys.stdout.write(e.msg)
            sys.stdout.write('\n')
        except TIMEOUT as e:
            sys.stdout.write("连接超时!\n")
        except Exception as e:
            sys.stdout.write(e.message)
            sys.stdout.write('\n')
Пример #22
0
class TestRealName:
    # 初始化
    def setup(self):
        # 获取session对象
        self.session = requests.session()
        # 获取Api对象
        self.api = Api(self.session)
        # 获取ApiRealName对象
        self.realname = self.api.api_get_ApiRealName()

    # 结束
    def teardown(self):
        # 关闭session对象
        self.session.close()

    # 1、认证接口测试方法
    @pytest.mark.parametrize(("realname", "card_id", "expect_msg"),
                             read_json("realname.json", "realname"))
    def test01_realname(self, realname, card_id, expect_msg):
        # 调用登录
        self.api.api_get_ApiRegLogin().api_login("13600001111", "test123")
        # 调用认证接口
        result = self.realname.api_realname(realname, card_id)
        try:
            print("响应结果为:", result.json())
            # 断言
            common_assert(result, expect_msg=expect_msg)
        except Exception as e:
            # 日志
            log.error(e)
            # 抛异常
            raise

    # 2、开户接口测试方法
    @pytest.mark.parametrize(("status", "expect_msg"),
                             read_json("realname.json", "trust"))
    def test02_trust(self, status, expect_msg):
        if status == "登录":
            # 调用登录
            self.api.api_get_ApiRegLogin().api_login("13600001111", "test123")
            # 调用开户接口
            result = self.realname.api_trust()
            # 如果开户成功 则需要三方开户
            r = parser_html(result)
            # 三方开户
            result = self.session.post(url=r[0], data=r[1])
            try:
                print("开户响应结果为:", result.text)
                # 断言
                common_assert(result, expect_text=expect_msg)
            except Exception as e:
                # 日志
                log.error(e)
                # 抛异常
                raise
        else:
            # 调用开户接口
            result = self.realname.api_trust()
            # 如果开户成功 则需要三方开户
            # 三方开户
            try:
                print("开户响应结果为:", result.text)
                # 断言
                common_assert(result, expect_text=expect_msg)
            except Exception as e:
                # 日志
                log.error(e)
                # 抛异常
                raise

    # 3、充值验证码接口测试方法
    @pytest.mark.parametrize(("random", "expect_code"),
                             read_json("realname.json", "vericy_code"))
    def test03_verify_code(self, random, expect_code):
        # 调用充值验证码接口
        result = self.realname.api_verify_code(random)
        try:
            # 断言
            common_assert(result, expect_code=expect_code)
        except Exception as e:
            # 日志
            log.error(e)
            # 抛异常
            raise

    # 4、充值接口 测试方法
    @pytest.mark.parametrize(("amount", "valicode", "expect_text"),
                             read_json("realname.json", "recharge"))
    def test04_recharge(self, amount, valicode, expect_text):
        # 登录
        self.api.api_get_ApiRegLogin().api_login("13600001111", "test123")
        # 充值验证码
        self.realname.api_verify_code(123123)
        # 充值
        result = self.realname.api_recharge(amount=amount, img_code=valicode)
        if expect_text == "OK":
            # 三方充值
            r = parser_html(result)
            result = self.session.post(r[0], data=r[1])
            print("充值结果为:", result.text)
            try:
                common_assert(result, expect_text=expect_text)
            except Exception as e:
                # 日志
                log.error(e)
                # 抛异常
                raise
        else:
            try:
                common_assert(result, expect_text=expect_text)
            except Exception as e:
                # 日志
                log.error(e)
                # 抛异常
                raise
 def update_budget(self, user_id, savings_money, budget_id):
     url = budget_url + 'update.php?budgetId=' + str(budget_id)
     data = {'userId' : user_id, 'savingsMoney' : savings_money}
     Api.json_encode(self, url, data=data)
Пример #24
0
Файл: msh.py Проект: Ape-See/msh
def main():
    inputClient = InputClient()
    api = Api()
    usage = "usage: %prog [options] [arg]"
    parser = OptionParser(usage)
    parser.add_option('-l', '--list', action='store_true', dest="iflist", help=u"list all ssh information")
    parser.add_option('-a', '--add', action='store', dest="ifadd",
                      help=u"Add ssh information.<name>@<ip>[:<ssh port>][@<alias>]. Example: root:1.1.1.1:1010-home1 or root:1.1.1.2")
    parser.add_option('-i', '--host', action="store", dest="host", help=u"Connect remote with the host ip")
    parser.add_option('-d', action='store', dest='del_host', help=u"Remove ssh information")
    parser.add_option('-D', '--delete-by-index', action='store_true', dest='del_by_index',
                      help=u"Remove ssh information by index id")
    parser.add_option('-u', '--update', action="store_true", dest="ifupdate")
    # parser.add_option('-')

    (option, args) = parser.parse_args()
    opt_dict = eval(str(option))
    opt_values = opt_dict.values()
    param_len = len(opt_values) - opt_values.count(None)
    output = OutputClient()
    output.set_header(['Index','UserName', 'Host', 'Port', 'Alias'], [7, 17, 15, 10, 30])
    if param_len > 1:
        raise ParamsException('Param Error')
    elif param_len == 0:
        try:
            if len(args) > 0:
                host = args[0]
                ssh_conn = api.get_ssh_connect(host)
                if ssh_conn is not None:
                    api.login(ssh_conn.get('host'), ssh_conn.get('name'), ssh_conn.get('passwd'), ssh_conn.get('port'))
                else:
                    ssh_conns = api.login_fuzzy(host)
                    con_len = len(ssh_conns)
                    if con_len == 0:
                        sys.stdout.write(redStr('No Matched Host\n'))
                        return
                    elif con_len == 1:
                        api.login(ssh_conns[0].get('host'), ssh_conns[0].get('name'), ssh_conns[0].get('passwd'),ssh_conns[0].get('port') )
                        return
                    else:
                        output.set_values(ssh_conns)
                        sys.stdout.write(output.show())
                        sys.stdout.write('\n')
                        ssh_conn = output.select()
                        api.login(ssh_conn.get('host'), ssh_conn.get('name'), ssh_conn.get('passwd'), ssh_conn.get('port'))
                        return
                return
            else:
                ssh_conns = api.list_ssh_connects()
                output.set_values(ssh_conns)
                # print output.show()
                sys.stdout.write(output.show())
                sys.stdout.write('\n')
                if len(ssh_conns) > 0:
                    ssh_conn = output.select()
                    api.login(ssh_conn.get('host'), ssh_conn.get('name'), ssh_conn.get('passwd'), ssh_conn.get('port'))
                return
        except ParamsException as e:
            sys.stdout.write(e.msg)
            sys.stdout.write('\n')
        except TIMEOUT as e:
            sys.stdout.write("Connection Timeout!\n")
        except Exception as e:
            sys.stdout.write(e.message)
            sys.stdout.write('\n')
    else:
        iflist = option.iflist
        add = option.ifadd
        host = option.host
        ifupdate = option.ifupdate
        del_host = option.del_host
        del_by_index = option.del_by_index
        try:
            if iflist:
                ssh_conns = api.list_ssh_connects()
                # print ssh_conns
                output.set_values(ssh_conns)
                sys.stdout.write(output.show())
                sys.stdout.write('\n')
                return
            if add:
                s_l = add.split('@')
                if len(s_l) < 2:
                    sys.stdout.write(
                        redStr('The data format is not correct. Example: <name>@<ip>[:<ssh port>][@<alias>]'))
                    return

                username = s_l[0]
                port = 22
                alias = ''

                if len(s_l) == 3:
                    alias = s_l[2]

                ip_port_arr = s_l[1].split(':')
                host = ip_port_arr[0]
                try:
                    if len(ip_port_arr) == 2:
                        port = int(ip_port_arr[1])
                except Exception, e:
                    sys.stdout.write(
                        redStr('The data format is not correct. Example: <name>@<ip>[:<ssh port>][@<alias>]'))
                    return

                password = getpass.getpass('Input Your Password:'******'host'), ssh_conn.get('name'), ssh_conn.get('passwd'), ssh_conn.get('port'))
            if ifupdate:
                ssh_conns = api.list_ssh_connects()
                # print ssh_conns
                output.set_values(ssh_conns)
                sys.stdout.write(output.show())
                sys.stdout.write('\n')
                if len(ssh_conns) > 0:
                    ssh_conn = output.select_to_update()
                    username = inputClient.input_username()
                    password = inputClient.input_password()
                    api.update_ssh_connect(ssh_conn.get('host'), username, password)
                    sys.stdout.write(greenStr('Update Successfully!\n'))
            if del_host:
                ssh_conn = api.get_ssh_connect(del_host)
                if ssh_conn is None:
                    # raise Exception("错误: 主机 %s 不存在!" % host)
                    raise Exception("Error: Host %s is not exist!" % host)
                api.del_ssh_connect(del_host)
                # sys.stdout.write('删除成功!\n')
                sys.stdout.write(greenStr('Delete Successfully!'))
            if del_by_index:
                ssh_conns = api.list_ssh_connects()
                # print ssh_conns
                output.set_values(ssh_conns)
                sys.stdout.write(output.show())
                sys.stdout.write('\n')
                if len(ssh_conns) > 0:
                    ssh_conn = output.select_to_del()
                    api.del_ssh_connect(ssh_conn.get('host'))
                    sys.stdout.write(greenStr('Delete Successfully!\n'))
                return
        except ParamsException as e:
            sys.stdout.write(e.msg)
            sys.stdout.write('\n')
Пример #25
0
 def __init__(self, task):
     self.task = task
     self.api = Api()
     self.quotation.instrument_id = self.task.setting.instrument_id
Пример #26
0
class TestTender:
    # 初始化
    def setup(self):
        # 获取session
        self.session = requests.session()
        # 获取ApiRegLogin对象
        self.login = Api(self.session).api_get_ApiRegLogin()
        # 获取ApiTender对象
        self.tender = Api(self.session).api_get_ApiTender()

    # 结束
    def teardown(self):
        self.session.close()

    def teardown_class(self):
        # 注意:只能放到类方法中
        clear_data()

    # 投资接口测试方法
    @pytest.mark.parametrize(("tender_id", "amount", "depositCertificate", "expect_msg"),
                             read_json("tender.json", "tender"))
    def test01_tender(self, tender_id, amount, depositCertificate, expect_msg):
        # 1、登录
        self.login.api_login("13600001111", "test123")
        # 2、调用投资接口
        result = self.tender.api_tender(tender_id, amount, depositCertificate)
        if expect_msg == "OK":
            # 3、三方投资
            # 提取三方投资所需数据
            r = parser_html(result)
            # 请求方法投资
            result = self.session.post(url=r[0], data=r[1])
            print(result.text)
            try:
                common_assert(result, expect_text=expect_msg)
            except Exception as e:
                # 日志
                log.error(e)
                # 抛异常
                raise
        else:
            try:
                common_assert(result, expect_msg=expect_msg)
            except Exception as e:
                # 日志
                log.error(e)
                # 抛异常
                raise

    # 投资业务方法
    def test02_mock(self):
        self.api = Api(self.session)
        # 1、注册接口
        self.api.api_get_ApiRegLogin().api_register("13600001115", 8888, "test123", 666666)
        # 2、登录
        self.api.api_get_ApiRegLogin().api_login("13600001115", "test123")
        # 3、认证
        self.api.api_get_ApiRealName().api_realname("张三", "110101199008075399")
        # 4、开户
        result = self.api.api_get_ApiRealName().api_trust()
        # 5、三方开户
        r = parser_html(result)
        result = self.session.post(url=r[0], data=r[1])
        print("开户结果为:", result.text)
        common_assert(result, expect_text="OK")

        # 6、充值验证码
        self.api.api_get_ApiRealName().api_verify_code(123123)
        # 7、充值
        result = self.api.api_get_ApiRealName().api_recharge(1000, 8888)
        # 8、三方充值
        r = parser_html(result)
        result = self.session.post(url=r[0], data=r[1])
        print("充值结果为:", result.text)
        common_assert(result, expect_text="OK")

        # 9、投资
        result = self.api.api_get_ApiTender().api_tender(642, 100, -1)
        # 10、三方投资
        r = parser_html(result)
        result = self.session.post(url=r[0], data=r[1])
        print("投资结果为:", result.text)
        common_assert(result, expect_text="OK")
 def create_budget(self, user_id):
     url = budget_url + 'create.php'
     data = {'userId' :user_id}
     Api.json_encode(self, url, data=data)
Пример #28
0
    def get_by_id(self, loan_id):
        url = loan_url + 'get.php?loanId=' + str(loan_id)

        return Api.read_data(Api, url)
Пример #29
0
def community_index(request):
    search = request.GET.get('search')
    all_posts = Api.get_all(Api, posts_url, user_id=None,
                            search=search, post_id=None)
    return render(request, 'community_index.html', {'posts': all_posts, 'search': search})
Пример #30
0
from os import environ, getcwd, path
from dotenv import load_dotenv
from db.db import Db
from api.api import Api

env_path = path.join(getcwd(), ".env")
if path.isfile(env_path):
    load_dotenv(env_path)

hostname = environ.get('SQL_HOSTNAME')
unix_socket = environ.get('SQL_CONNECTION_NAME')
database = environ.get('SQL_DATABASE_NAME')
user = environ.get('SQL_USERNAME')
password = environ.get('SQL_PASSWORD')

db = Db(hostname, database, user, password, unix_socket)
api = Api(db)
app = api.app()

if __name__ == '__main__':
    app.run(host="127.0.0.1", port=8080),