Beispiel #1
0
def MSTrigUpdate_Master(AnotherFunctionName, AnotherRegion, AnotherNamespace,
                        TriggerName, FunctionName, Namespace):
    global SecretId, SecretKey, Region
    try:
        cred = credential.Credential(SecretId, SecretKey)
        client = scf_client.ScfClient(cred, AnotherRegion)
    except TencentCloudSDKException as err:
        print(err)
    # 启动从函数
    pass_params = {
        "FunctionName": FunctionName,
        "Region": Region,
        "Namespace": Namespace,
        "TriggerName": TriggerName,
        "SecretId": SecretId,
        "SecretKey": SecretKey
    }
    pass_params_str = json.dumps(pass_params)
    req = models.InvokeRequest()
    params = '{"FunctionName":"' + AnotherFunctionName + '",'
    params += '"InvocationType":"Event",'
    params += '"ClientContext":"' + pass_params_str + '",'
    params += '"Namespace":"' + AnotherNamespace + '"}'
    req.from_json_string(params)
    return
Beispiel #2
0
def saveNewsToCos():
    global articlesList
    articlesList = getMaterialsList("news",
                                    getTheTotalOfAllMaterials()['news_count'])
    try:
        cosClient.put_object(Bucket=bucket,
                             Body=json.dumps(articlesList).encode("utf-8"),
                             Key=key,
                             EnableMD5=False)
        req = scf_models.InvokeRequest()
        params = '{"FunctionName":"Weixin_GoServerless_GetIndexFile", "ClientContext":"{\\"key\\": \\"%s\\", \\"index_key\\": \\"%s\\"}"}' % (
            key, indexKey)
        req.from_json_string(params)
        resp = scfClient.Invoke(req)
        resp.to_json_string()
        response = cosClient.get_object(
            Bucket=bucket,
            Key=key,
        )
        response['Body'].get_stream_to_file('/tmp/content.json')
        with open('/tmp/content.json') as f:
            articlesList = json.loads(f.read())
        return True
    except Exception as e:
        print(e)
        return False
Beispiel #3
0
 def call(self, url: str, method: str, function_name: str = None):
     assert (self._func_name or function_name), "function_nam is None"
     req = models.InvokeRequest()
     params = {
         "FunctionName": self._func_name or function_name,
         "ClientContext": json.dumps({"url": url, "method": method})
     }
     req.from_json_string(json.dumps(params))
     resp = self.client.Invoke(req)
     return resp.Result
Beispiel #4
0
def searchNews(sentence):
    req = scf_models.InvokeRequest()
    params = '{"FunctionName":"Weixin_GoServerless_SearchNews", "ClientContext":"{\\"sentence\\": \\"%s\\", \\"key\\": \\"%s\\"}"}' % (
        sentence, indexKey)
    req.from_json_string(params)
    resp = scfClient.Invoke(req)
    print(json.loads(json.loads(resp.to_json_string())['Result']["RetMsg"]))
    media_id = json.loads(
        json.loads(json.loads(
            resp.to_json_string())['Result']["RetMsg"])["result"])
    return media_id if media_id else None
def run_function(secret_info: Dict[str, str]):
    try:
        client = get_scf_client(secret_info)
        req = models.InvokeRequest()
        params = {
            "FunctionName": config.QCLOUD_FUNCTION_NAME,
            "LogType": "None",
        }
        req.from_json_string(json.dumps(params))

        resp = client.Invoke(req)
        response_json = json.loads(resp.to_json_string())
        response_json["Result"]["RetMsg"] = json.loads(
            response_json["Result"]["RetMsg"])
        response_json = json.dumps(response_json, indent=2, ensure_ascii=False)
        print(response_json)
    except TencentCloudSDKException as err:
        print(err)
Beispiel #6
0
 def invoke_func(self, functionName, namespace, eventdata, invocationType,
                 logtype):
     try:
         req = models.InvokeRequest()
         req.FunctionName = functionName
         req.Namespace = namespace
         req.ClientContext = eventdata
         req.InvocationType = invocationType
         req.LogType = logtype
         resp = self._client.Invoke(req)
         return True, resp.to_json_string()
     except TencentCloudSDKException as err:
         Operation(err, err_msg=traceback.format_exc(),
                   level="ERROR").no_output()
         if sys.version_info[0] == 3:
             s = err.get_message()
         else:
             s = err.get_message().encode("UTF-8")
     return False, s
Beispiel #7
0
def kafka_consumer_api_handler(cred, partition_id, region, consumer_function_name, namespace):
    try:

        # 实例化要请求产品的client对象,以及函数所在的地域
        client = scf_client.ScfClient(cred, region)
        # 接口参数,输入需要调用的函数名,RequestResponse(同步) 和 Event(异步)
        function_name = consumer_function_name
        logger.debug('Start Hello World function')
        # 调用接口,发起请求,并打印返回结果
        req = scf_models.InvokeRequest()
        req.FunctionName = function_name
        req.Namespace = namespace
        req.InvocationType = "Event"
        client_param = {"partition_id": partition_id}
        req.ClientContext = json.dumps(client_param)
        ret = client.Invoke(req)
        ret_value = json.loads(s=ret.to_json_string())
        logger.debug("ret_value: %s", str(ret_value["Result"]))

    except TencentCloudSDKException as err:
        logger.error(err)
Beispiel #8
0
def addTags(mapper, connection, target):
    print("add tags")
    try:
        cred = credential.Credential(os.environ.get('tencent_secret_id'),
                                     os.environ.get('tencent_secret_key'))
        httpProfile = HttpProfile()
        httpProfile.endpoint = "scf.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = scf_client.ScfClient(cred, os.environ.get("region"),
                                      clientProfile)

        req = models.InvokeRequest()
        params = '{"FunctionName":"Blog_Admin_updateArticle","InvocationType":"Event","ClientContext":"{\\"id\\": %s}","Namespace":"default"}' % (
            target.aid)
        req.from_json_string(params)
        resp = client.Invoke(req)
        print(resp)

    except TencentCloudSDKException as err:
        print(err)
    print("end add")
 def invokeFunction(self, functionname):
     params = '''{"Namespace":"%s","FunctionName":"%s"}''' % (QC_NAMESPACE, functionname)
     invo = models.InvokeRequest()
     invo.from_json_string(params)
     resp = self.client.Invoke(invo)
     return resp
 def invokeFunctionGetDuration(self, functionname):
     params = '''{"FunctionName": "%s","Namespace":"%s"}''' % (functionname,QC_NAMESPACE)
     invo = models.InvokeRequest()
     invo.from_json_string(params)
     resp = self.client.Invoke(invo)
     return resp, resp.Result.Duration, float(resp.Result.MemUsage / 1024.00 / 1024.00)