Exemplo n.º 1
0
async def aly_image_check(image_url):
    clt = AcsClient("LTAIMzATsuQaeFBH", "kplNM0IZ7MMO7Gg4dONZ8yWsBNOaTA",
                    'cn-shanghai', 'cn-shanghai')
    region_provider.modify_point('Green', 'cn-shanghai',
                                 'green.cn-shanghai.aliyuncs.com')
    request = ImageSyncScanRequest.ImageSyncScanRequest()
    request.set_accept_format('JSON')
    # 同步检测只支持对单张图片进行检测,即只有一个task
    task1 = {
        "dataId": str(uuid.uuid1()),
        "url": image_url,
        "time": datetime.datetime.now().microsecond
    }
    # 场景参数支持:p**n(色情)、terrorism(暴恐)qrcode(二维码)、ad(图片广告)、ocr(文字识别)
    request.set_content(
        ujson.dumps({
            "tasks": [task1],
            "scenes": ["p**n", 'terrorism', 'ad']
        }))
    response = clt.do_action_with_exception(request)
    result = ujson.loads(response)
    if 200 == result["code"]:
        task_results = result["data"]
        for task_result in task_results:
            if 200 == task_result["code"]:
                scene_results = task_result["results"]
                for scene_result in scene_results:
                    label = scene_result["label"]
                    if label != 'normal':
                        return False
                    return True
            else:
                return False
    else:
        return False
    def setup_class(cls):
        # ignore https credential
        ssl._DEFAULT_CIPHERS = 'ALL'
        if hasattr(ssl, '_create_unverified_context'):
            ssl._create_default_https_context = ssl._create_unverified_context

        cf = configparser.ConfigParser()
        config_file = os.path.expanduser('~') + "/aliyun-sdk.ini"
        cf.read(config_file)

        access_key_id = cf.get('sdk_test_auth_ram_role_arn_credential',
                               'access_key_id')
        access_key_secret = cf.get('sdk_test_auth_ram_role_arn_credential',
                                   'access_key_secret')
        role_arn = cf.get('sdk_test_auth_ram_role_arn_credential', 'role_arn')
        session_role_name = 'python-sdk-test'

        region_provider.modify_point('Sts', 'cn-hangzhou', 'sts.aliyuncs.com')

        ram_role_arn_credential = RamRoleArnCredential(access_key_id,
                                                       access_key_secret,
                                                       role_arn,
                                                       session_role_name)
        cls.acs_client = AcsClient(region_id='cn-hangzhou',
                                   credential=ram_role_arn_credential)
        assert cls.acs_client
Exemplo n.º 3
0
async def aly_text_check(content):
    if content is None or content == '':
        return True
    clt = AcsClient("LTAIMzATsuQaeFBH", "kplNM0IZ7MMO7Gg4dONZ8yWsBNOaTA",
                    'cn-shanghai')
    region_provider.modify_point('Green', 'cn-shanghai',
                                 'green.cn-shanghai.aliyuncs.com')
    request = TextScanRequest.TextScanRequest()
    request.set_accept_format('JSON')
    task1 = {
        "dataId": str(uuid.uuid1()),
        "content": content,
        "time": datetime.datetime.now().microsecond
    }
    request.set_content(ujson.dumps({
        "tasks": [task1],
        "scenes": ["antispam"]
    }))
    response = clt.do_action_with_exception(request)
    result = ujson.loads(response)
    if 200 == result["code"]:
        task_results = result["data"]
        for task_result in task_results:
            if 200 == task_result["code"]:
                scene_results = task_result["results"]
                for sceneResult in scene_results:
                    label = sceneResult["label"]
                    if label != 'normal':
                        return False
                    return True
    return False
Exemplo n.º 4
0
def _handleEndPoint(cmd, regionId, endPoint):
    try:
        from aliyunsdkcore.profile.region_provider import modify_point
        modify_point(cmd, regionId, endPoint)
    except Exception as e:
        print e
        pass
Exemplo n.º 5
0
def verifying_code(
        url='https://paulzhangcc.oss-cn-beijing.aliyuncs.com/1.png'):
    # 请替换成你自己的accessKeyId、accessKeySecret, 您可以类似的配置在配置文件里面,也可以直接明文替换
    clt = client.AcsClient('LTAII8NOKvwoEvIF',
                           'd0iICqgwutXUMzTQ7uKwsezxTTq1AF', 'cn-shanghai')
    region_provider.modify_point('Green', 'cn-shanghai',
                                 'green.cn-shanghai.aliyuncs.com')
    request = ImageSyncScanRequest.ImageSyncScanRequest()
    request.set_accept_format('JSON')

    # 同步现支持单张图片,即一个task
    task1 = {
        "dataId": str(uuid.uuid1()),
        "url": url,
        "time": datetime.datetime.now().microsecond
    }

    request.set_content(
        bytearray(json.dumps({
            "tasks": [task1],
            "scenes": ["ocr"]
        }), "utf-8"))

    response = clt.do_action_with_exception(request)
    result = json.loads(response)
    print("识别图片阿里云返回的结果:", result)
    if 200 == result["code"]:
        taskResults = result["data"]
        for taskResult in taskResults:
            if (200 == taskResult["code"]):
                print(taskResult['results'][0])
            if (taskResult['results'][0]['label'] == 'ocr'):
                return taskResult['results'][0]['ocrData'][0]
    return ''
Exemplo n.º 6
0
 def __init__(self):
     cf = configparser.ConfigParser()
     cf.read("aliyun.ak.conf")
     # 请替换成你自己的accessKeyId、accessKeySecret, 您可以类似的配置在配置文件里面,也可以直接明文替换
     self.clt = client.AcsClient(cf.get("AK", "accessKeyId"), cf.get("AK", "accessKeySecret"),'cn-shanghai')
     region_provider.modify_point('Green', 'cn-shanghai', 'green.cn-shanghai.aliyuncs.com')
     self.request = ImageSyncScanRequest.ImageSyncScanRequest()
     self.request.set_accept_format('JSON')
Exemplo n.º 7
0
 def __init__(self):
     key = appconfig.key
     key_id = appconfig.key_id
     region = appconfig.region
     domain = 'green.' + region + '.aliyuncs.com'
     self.clt = client.AcsClient(key_id, key, region)
     region_provider.modify_point('Green', region, domain)
     self.request = TextScanRequest.TextScanRequest()
     self.request.set_accept_format('JSON')
Exemplo n.º 8
0
 def __init__(self):
     cf = ConfigParser.ConfigParser()
     config_path = os.path.join(root, "aliyun.conf")
     cf.read(config_path)
     self.__clt = client.AcsClient(cf.get("config", "accessKeyId"),
                                   cf.get("config", "accessKeySecret"),
                                   cf.get("config", "server"))
     region_provider.modify_point('Green', cf.get("config", "server"),
                                  cf.get("config", "domain"))
     # 场景参数支持:p**n(色情)、terrorism(暴恐)qrcode(二维码)、ad(图片广告)、ocr(文字识别)
     self.__scene = "p**n"
Exemplo n.º 9
0
def main():
    conn = None

    device_opt = [
        "port", "no_password", "region", "access_key", "secret_key", "ram_role"
    ]

    atexit.register(atexit_handler)

    define_new_opts()

    all_opt["power_timeout"]["default"] = "60"

    options = check_input(device_opt, process_input(device_opt))

    docs = {}
    docs["shortdesc"] = "Fence agent for Aliyun (Aliyun Web Services)"
    docs["longdesc"] = "fence_aliyun is an I/O Fencing agent for Aliyun"
    docs["vendorurl"] = "http://www.aliyun.com"
    show_docs(options, docs)

    run_delay(options)

    if "--region" in options:
        region = options["--region"]
        if "--access-key" in options and "--secret-key" in options:
            access_key = options["--access-key"]
            secret_key = options["--secret-key"]
            conn = client.AcsClient(access_key, secret_key, region)
        elif "--ram-role" in options:
            ram_role = options["--ram-role"]
            role = EcsRamRoleCredential(ram_role)
            conn = client.AcsClient(region_id=region, credential=role)
        else:
            fail_usage(
                "Failed: User credentials are not set. Please set the Access Key and the Secret Key, or configure the RAM role."
            )

        # Use intranet endpoint to access ECS service
        try:
            region_provider.modify_point('Ecs', region,
                                         'ecs.%s.aliyuncs.com' % region)
        except Exception as e:
            logging.warn(
                "Failed: failed to modify endpoint to 'ecs.%s.aliyuncs.com': %s"
                % (region, e))

    # Operate the fencing device
    result = fence_action(conn, options, set_power_status, get_power_status,
                          get_nodes_list)
    sys.exit(result)
 def test_bug_with_18034796(self):
     from aliyunsdkgreen.request.v20180509 import ImageAsyncScanRequest
     region_provider.modify_point(
         'Green', 'cn-shanghai', 'green.cn-shanghai.aliyuncs.com')
     request = ImageAsyncScanRequest.ImageAsyncScanRequest()
     image_url = 'https://gss2.bdstatic.com/-fo3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D790/' \
                 'sign=b51ba990a68b87d65042a91637092860/' \
                 '6c224f4a20a446230ff0bec39f22720e0cf3d75c.jpg'
     task1 = {"dataId": str(uuid.uuid1()),
              "url": image_url,
              "time": datetime.datetime.now().microsecond
              }
     request.set_content(json.dumps({"tasks": [task1], "scenes": ["p**n"]}))
     response = self.client.do_action_with_exception(request)
     response = self.get_dict_response(response)
     self.assertEqual(200, response.get("code"))
Exemplo n.º 11
0
    def __init__(self, configFile, clientPath):
        
        config = ConfigParser.RawConfigParser()
        config.read(configFile)
        self.accessKey = config.get('alidns', 'accessKey')
        self.accessSecret = config.get('alidns', 'accessSecret')
        self.regionId = config.get('alidns', 'regionId')
        self.productName = config.get('alidns', 'productName')
        self.serviceAddr = config.get('alidns', 'serviceAddr')
        self.domainName = config.get('alidns', 'domainName')
        self.rrSuffix = config.get('alidns', 'rrSuffix')
        
        self.clientPath = clientPath

        if not region_provider.find_product_domain(self.regionId, self.productName):
            print("We need to update endpoint.xml since you don't have Alidns in it.")
            region_provider.modify_point(self.productName, self.regionId, self.serviceAddr)
        self.ac = AliyunClient.AcsClient(self.accessKey, self.accessSecret, self.regionId)
Exemplo n.º 12
0
    def setup_class(cls):
        # ignore https credential
        ssl._DEFAULT_CIPHERS = 'ALL'
        if hasattr(ssl, '_create_unverified_context'):
            ssl._create_default_https_context = ssl._create_unverified_context

        cf = ConfigParser.ConfigParser()
        config_file = os.path.expanduser('~') + "/aliyun-sdk.ini"
        cf.read(config_file)

        public_key_id = cf.get('sdk_test_auth_v2_credential', 'public_key_id')
        private_key = cf.get('sdk_test_auth_v2_credential', 'private_key')

        region_provider.modify_point('Sts', 'cn-hangzhou', 'sts.aliyuncs.com')
        cls.public_key_id = public_key_id
        cls.private_key = private_key
        credential = RsaKeyPairCredential(public_key_id, private_key, 3600)
        cls.acs_client = AcsClient(region_id='cn-hangzhou', credential=credential)
        assert cls.acs_client
Exemplo n.º 13
0
def main():
    conn = None

    device_opt = [
        "port", "no_password", "region", "access_key", "secret_key", "ram_role"
    ]

    atexit.register(atexit_handler)

    define_new_opts()

    all_opt["power_timeout"]["default"] = "60"

    options = check_input(device_opt, process_input(device_opt))

    docs = {}
    docs["shortdesc"] = "Fence agent for Aliyun (Aliyun Web Services)"
    docs["longdesc"] = "fence_aliyun is an I/O Fencing agent for Aliyun"
    docs["vendorurl"] = "http://www.aliyun.com"
    show_docs(options, docs)

    run_delay(options)

    if "--region" in options:
        region = options["--region"]
        if "--access-key" in options and "--secret-key" in options:
            access_key = options["--access-key"]
            secret_key = options["--secret-key"]
            conn = client.AcsClient(access_key, secret_key, region)
        elif "--ram-role" in options:
            ram_role = options["--ram-role"]
            _check_role(ram_role)
            role = EcsRamRoleCredential(ram_role)
            conn = client.AcsClient(region_id=region, credential=role)
        region_provider.modify_point('Ecs', region,
                                     'ecs.%s.aliyuncs.com' % region)

    # Operate the fencing device
    result = fence_action(conn, options, set_power_status, get_power_status,
                          get_nodes_list)
    sys.exit(result)
    def test_resolve_endpoint(self):
        region_provider.modify_point('Ft', 'cn-hangzhou', 'ft.aliyuncs.com')
        request = CommonRequest()
        request.set_product('Ft')
        request.set_version('2016-01-02')
        request.set_action_name('TestRoaApi')
        request.set_uri_pattern('/web/cloudapi')
        request.set_method('POST')
        request.add_header('HeaderParam', 'headerValue')
        request.add_query_param('QueryParam', 'queryValue')
        request.add_body_params('BodyParam', 'bodyValue')

        body = self.acs_client.do_action_with_exception(request)
        assert body

        response = json.loads(body)
        assert response

        assert response.get("Params").get("QueryParam") == 'queryValue'
        assert response.get("Headers").get("HeaderParam") == 'headerValue'
        assert response.get("Params").get("BodyParam") == 'bodyValue'
Exemplo n.º 15
0
def main():
    fDic = {
        "accountbalance": getAccountBalance,
        "reminingcdnflow": getReMiningCDNFlow,
        "reminingcdn": getReMiningCDN
    }
    region_provider.modify_point('BssOpenApi', 'business',
                                 'business.aliyuncs.com')
    try:
        aid = sys.argv[2]
        akey = sys.argv[3]
        client = AcsClient(aid, akey, "business")
    except:
        print "please input accessid & accesskey."
    try:
        arg = sys.argv[1]
        print fDic[arg](client)
    except ServerException:
        print "accessid accesskey error or server time is not correct."
    except KeyError:
        print "unkown args.please input [accountbalance|reminingcdnflow|reminingcdn]"
Exemplo n.º 16
0
def handler(event, context):
    # Your account access key id/secret are stored in context.credentials
    # Replace the "your_access_key_id" and "your_access_key_secret"
    clt = client.AcsClient("your_access_key_id", "your_access_key_secret",
                           'cn-shanghai')
    region_provider.modify_point('Green', 'cn-shanghai',
                                 'green.cn-shanghai.aliyuncs.com')
    request = ImageSyncScanRequest.ImageSyncScanRequest()
    request.set_accept_format('JSON')

    # set tasks and scenes for p**n detection
    img_url = event.decode("utf-8")
    task = {
        "dataId": str(uuid.uuid1()),
        "url": img_url,
        "time": datetime.datetime.now().microsecond
    }
    request.set_content(
        bytearray(json.dumps({
            "tasks": [task],
            "scenes": ["p**n"]
        }), "utf-8"))
    response = clt.do_action(request)
    return response
Exemplo n.º 17
0
 def __init__(self, access_key_id, access_key_secret, domain, server):
     super(Aliyun, self).__init__()
     self.__clt = client.AcsClient(access_key_id, access_key_secret, server)
     region_provider.modify_point('Green', server, domain)
Exemplo n.º 18
0
        code_list.append(random_lowercase_letter)
        code_list.append(random_lowercase_letter)
    verification_code = ''.join(code_list)
    return verification_code


# 配置部分(不会变更)
REGION = "cn-hangzhou"
PRODUCT_NAME = "SMSapi"
DOMAIN = "dysmsapi.aliyuncs.com"
ACCESS_KEY_ID = ''  # 必填
ACCESS_KEY_SECRET = ''  # 必填

# 初始化
acs_client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET, REGION)
region_provider.modify_point(PRODUCT_NAME, REGION, DOMAIN)


class SendSmsRequest(RpcRequest):
    def __init__(self):
        RpcRequest.__init__(self, 'Dysmsapi', '2017-05-25', 'SendSms')

    def set_TemplateCode(self, TemplateCode):
        """ 模板CODE """
        self.add_query_param('TemplateCode', TemplateCode)

    def set_TemplateParam(self, TemplateParam):
        """ 模板参数,变量 """
        self.add_query_param('TemplateParam', TemplateParam)

    def set_PhoneNumbers(self, PhoneNumbers):
Exemplo n.º 19
0
def get_ip():
    '''
    Query specified domain myip.opends.com from resolver1.opendns.com & 
    resolver2.opendns.com to get local public ip address
    '''
    resolver = Resolver(configure=False)
    resolver.nameservers = ['208.67.222.222', '208.67.220.220']
    answers = resolver.query('myip.opendns.com', 'A')
    for rdata in answers:
        return str(rdata)

PROD = 'DNS'
VERSION = '2015-01-09'
REGION_ID = 'cn-beijing'

region_provider.modify_point('DNS', REGION_ID, 'dns.aliyuncs.com')
domain = region_provider.find_product_domain(REGION_ID, 'DNS')
client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECURE, REGION_ID)

def get_record():
    req = RpcRequest(PROD, VERSION, 'DescribeDomainRecords', 'JSON')
    req.add_query_param('DomainName', DOMAIN_NAME)
    resp = json.loads(client.do_action(req))

    record_id = None
    record_value = None
    for record in resp['DomainRecords']['Record']:
        if record['RR'] == DOMAIN_RECORD:
            record_id = record['RecordId']
            if record['Type'] != RECORD_TYPE:
                raise Exception('The record is already exsits and the type not same.')
Exemplo n.º 20
0
from aliyunsdkcore.client import AcsClient as connection
from aliyunsdkcore.profile import region_provider
from flask import current_app

from app.libs.alidayu import SendSmsRequest

sign_name = current_app.config['ALI_NAME']
template_code = current_app.config['ALI_CODE']

acs_client = connection(current_app.config['ALI_ID'],
                        current_app.config['ALI_KEY'],
                        current_app.config['ALI_REGION'])

region_provider.modify_point(current_app.config['ALI_PRODUCT_NAME'],
                             current_app.config['ALI_REGION'],
                             current_app.config['ALI_DOMAIN'])


def send_sms(phone_numbers, param=None):
    __business_id = uuid.uuid1()
    sms_request = SendSmsRequest()
    sms_request.set_template_code(template_code)

    # 短信模板变量参数
    if param is not None:
        sms_request.set_template_param(param)

    # 设置业务请求流水号,必填。
    sms_request.set_out_id(__business_id)
    # 短信签名
Exemplo n.º 21
0
#!/usr/bin/env python
#coding=utf-8
#这个脚本是用来获取dts延迟数字的
from aliyunsdkcore import client
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcore.profile import region_provider
import time
import json
import sys
sys.path.append('/tmp/aliyunsdkdts/request/v20160801/')
import DescribeSynchronizationJobStatusRequest

region_provider.modify_point('Dts', '这里输入地域', 'dts.aliyuncs.com')
# 创建 Client 实例
clt = client.AcsClient('这里输入ak', '这里输入SK', '这里输入地域')

# 创建 request,并设置参数
request = DescribeSynchronizationJobStatusRequest.DescribeSynchronizationJobStatusRequest(
)
request.set_SynchronizationJobId("dtsu7oi1gvjocwy")

response = clt.do_action_with_exception(request)
#print response
delay = json.loads(response)
print "===================================================="
print(time.strftime("%H"))
print "当前延迟是:" + str(delay["DataSynchronizationStatus"]["Delay"])
print "当前同步速度是:" + str(delay["Performance"]["FLOW"])
rate = str(delay["Performance"]["FLOW"])[0:4]
Exemplo n.º 22
0
# coding: utf-8
import requests
from aliyunsdkcore import client
from aliyunsdkjaq.request.v20161123 import AfsCheckRequest
from aliyunsdkcore.profile import region_provider
from app.libs.configure import config

region_provider.modify_point('Jaq', 'cn-hangzhou', 'jaq.aliyuncs.com')

clt = client.AcsClient(config.ALIYUN_OSS_ACCESS_KEY,
                       config.ALIYUN_OSS_ACCESS_SECRET, 'cn-hangzhou')


def check_aliyun_captcha(session, sig, token, scene):
    request = AfsCheckRequest.AfsCheckRequest()
    # 必填参数:请求来源: 1:Android端; 2:iOS端; 3:PC端及其他
    request.set_Platform(3)
    request.set_Session(session)
    request.set_Sig(sig)
    request.set_Token(token)
    request.set_Scene(scene)
    result = clt.do_action_with_exception(request)
    print result
Exemplo n.º 23
0
 def __init__(self):
     super(Aliyunsms, self).__init__()
     self.acs_client = AcsClient(Aliyunsms.ACCESS_KEY_ID, Aliyunsms.ACCESS_KEY_SECRET, Aliyunsms.REGION)
     region_provider.modify_point(Aliyunsms.PRODUCT_NAME,Aliyunsms.REGION,Aliyunsms.DOMAIN)
Exemplo n.º 24
0
#coding=utf-8
# 同步图片检测服务接口, 会实时返回检测的结果

from aliyunsdkcore import client
from aliyunsdkcore.profile import region_provider
from aliyunsdkgreen.request.v20170112 import ImageSyncScanRequest
import json
import uuid
import datetime

import ConfigParser
cf = ConfigParser.ConfigParser()
cf.read("F:/ComputerNetwork/sample/aliyun.ak.conf")
clt = client.AcsClient(cf.get("AK", "accessKeyId"),
                       cf.get("AK", "accessKeySecret"), 'cn-shanghai')
region_provider.modify_point('Green', 'cn-shanghai',
                             'green.cn-shanghai.aliyuncs.com')
request = ImageSyncScanRequest.ImageSyncScanRequest()
request.set_accept_format('JSON')

task1 = {
    "dataId": str(uuid.uuid1()),
    "url": "http://tupian.enterdesk.com/2015/mxy/5/20/41/10.jpg",
    "time": datetime.datetime.now().microsecond
}

request.set_content(
    bytearray(json.dumps({
        "tasks": [task1],
        "scenes": ["ocr"]
    }), "utf-8"))
Exemplo n.º 25
0
    '''
    Query specified domain myip.opends.com from resolver1.opendns.com &
    resolver2.opendns.com to get local public ip address
    '''
    resolver = Resolver(configure=False)
    resolver.nameservers = ['208.67.222.222', '208.67.220.220']
    answers = resolver.query('myip.opendns.com', 'A')
    for rdata in answers:
        return str(rdata)

PROD = 'DNS'
VERSION = '2015-01-09'
REGION_ID = 'cn-beijing'
IP = None

region_provider.modify_point('DNS', REGION_ID, 'dns.aliyuncs.com')
domain = region_provider.find_product_domain(REGION_ID, 'DNS')
client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECURE, REGION_ID)

def get_all_record():
    req = RpcRequest(PROD, VERSION, 'DescribeDomainRecords', 'JSON')
    req.add_query_param('DomainName', DOMAIN_NAME)
    resp = json.loads(client.do_action(req))
    return resp

def get_record(resp, domain_record):
    record_id = None
    record_value = None
    for record in resp['DomainRecords']['Record']:
        if record['RR'] == domain_record:
            record_id = record['RecordId']
Exemplo n.º 26
0
"""
import oss2
import logging
from dataclasses import dataclass
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.profile import region_provider

from kubrick.initialize import (
    IS_DEV_ENV, IS_PROD_ENV, ENV_PREFIX,
    ALIYUN_AK, ALIYUN_SECRET, ALIYUN_RAMUSR,
    ALIOSS_BUCKET_NAME, ALIOSS_CDN_HOST_URL,
    ALIOSS_ENDPOINT_PUBLIC, ALIOSS_ENDPOINT_INTERNAL,
)

logger = logging.getLogger('kubrick.debug')
region_provider.modify_point('Green', 'cn-hangzhou', 'green.cn-hangzhou.aliyuncs.com')

###########################
# AK 配置 #############
###########################


@dataclass
class AKConfig:
    """ AK 配置 """
    ak: str
    secret: str
    ramusr: str


ak_cfg = AKConfig(
Exemplo n.º 27
0
 def _init_connection_aliyun(self, PRODUCT_NAME, REGION, DOMAIN):
     acs_client = AcsClient(self.ACCESS_KEY_ID, self.ACCESS_KEY_SECRET,
                            REGION)
     region_provider.modify_point(PRODUCT_NAME, REGION, DOMAIN)
     return acs_client
Exemplo n.º 28
0
# -*- coding: utf-8 -*-
import json
import uuid
import random

from aliyunsdkdysmsapi.request.v20170525 import SendSmsRequest
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.profile import region_provider
from arrplat.config import config

Conf = config.get('message')

acs_client = AcsClient(Conf.get('ACCESS_KEY_ID'), Conf.get('ACCESS_KEY_SECRET'), Conf.get('REGION'))
region_provider.modify_point(Conf.get('PRODUCT_NAME'), Conf.get('REGION'), Conf.get('DOMAIN'))


def send_sms(business_id, phone_numbers, sign_name, template_code, template_param=None):
    sms_request = SendSmsRequest.SendSmsRequest()
    sms_request.set_TemplateCode(template_code)

    if template_param is not None:
        sms_request.set_TemplateParam(template_param)

    sms_request.set_OutId(business_id)
    sms_request.set_SignName(sign_name)
    sms_request.set_PhoneNumbers(phone_numbers)
    sms_response = acs_client.do_action_with_exception(sms_request)

    return sms_response

Exemplo n.º 29
0
import json
import os
import logging
import urllib.request
from threading import Timer

from flask_cors import *

from aliyunsdkcore import client
from aliyunsdkafs.request.v20180112 import AuthenticateSigRequest
from aliyunsdkcore.profile import region_provider
from flask import Flask, render_template, jsonify, request

region_provider.modify_point('afs', 'cn-hangzhou', 'afs.aliyuncs.com')

env_dist = os.environ

# ACCESS_KEY、ACCESS_SECRET请替换成您的阿里云accesskey id和secret
ACCESS_KEY = env_dist.get('ACCESS_KEY', '')
ACCESS_SECRET = env_dist.get('ACCESS_SECRET', '')
APP_KEY = env_dist.get('APP_KEY', 'FFFF0N000000000063E3')
NAME = env_dist.get('NAME', 'faucet')
CHAIN_ID = env_dist.get('CHAIN_ID', 'test-chain-Bf61kJ')
PASSWORD = env_dist.get('PASSWORD', '1234567890')
ACCOUNT = env_dist.get('ACCOUNT', 'faa1x8xj4jdwa3sptwuu6daseeney3jluu39qn8rdm')

REST_URL = 'http://localhost:1317'
SEQUENCE = 0
ACCOUNT_NUMBER = 0

# clt = client.AcsClient('YOUR ACCESSKEY', 'YOUR ACCESS_SECRET', 'cn-hangzhou')
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.profile import region_provider
from .ft import TestRoaApiRequest

parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)

headerParam = "hdParam"
queryParam = "queryParam"
bodyParam = "bodyContent"

cf = ConfigParser.ConfigParser()
config_file = os.path.expanduser('~') + "/aliyun-sdk.ini"
cf.read(config_file)

region_provider.modify_point('Ft', 'cn-hangzhou', 'ft.aliyuncs.com')
client = AcsClient(cf.get("daily_access_key", "id"),
                   cf.get("daily_access_key", "secret"), 'cn-hangzhou')
assert client

request = TestRoaApiRequest.TestRoaApiRequest()
request.set_header_param(headerParam)
request.set_query_param(queryParam)
request.set_body_param(bodyParam)
request.add_header('Content-Type', "text/plain")


class TestRoaApi(object):

    acs_client = client
Exemplo n.º 31
0
 def connect(self):
     region_provider.modify_point('Green', 'cn-shanghai', 'green.cn-shanghai.aliyuncs.com')
     request = ImageSyncScanRequest.ImageSyncScanRequest()
     request.set_accept_format('JSON')
     return request