【问题标题】:Pass current URL parameters to Cloud Function Python API on IBM Cloud将当前 URL 参数传递给 IBM Cloud 上的 Cloud Function Python API
【发布时间】:2020-07-29 15:13:08
【问题描述】:

我是新手,正在尝试在 IBM Cloud 上创建 Cloud Function。 我的 API 仅在“hello world”上运行良好。我需要将参数从 URL 传递到我的 Python API 中。 喜欢:

网址:https://fa75e0fa.eu-gb.apigw.appdomain.cloud/testapi/test1?id=11

我需要将上述 URL 末尾的 id=11 的值传递到我的 Python 代码(Python 3.70)中。

我现在有这个:

#
#
# main() will be run when you invoke this action
#
# @param Cloud Functions actions accept a single parameter, which must be a JSON object.
#
# @return The output of this action, which must be a JSON object.
#
#
import sys

def main(dict):
    return { 'message': 'Hello world' }

输出是: { “消息”:“你好世界” }

我试过了:

import sys
import urllib3, requests, json
import requests
import os

def main(dict):
    id1=requests.GET.get('id')

    return { 'message': 'Hello world',
             'id': json.loads(id1.text)

    }

输出是:

激活 ID: 4e97b3be9b2b49f397b3be9b2b99f34d 结果: { “错误”:“模块‘请求’没有属性‘获取’” } 日志:

[ "2020-04-16T11:29:34.215661Z stderr: Traceback (最近 最后调用):“,”2020-04-16T11:29:34.215717Z标准错误:文件 \"/action/1/src/exec__.py\",第 66 行,在 ",
"2020-04-16T11:29:34.215722Z stderr: res = main(payload)",
“2020-04-16T11:29:34.215725Z 标准错误:文件 \"/action/1/src/main__.py\",第 10 行,在 main",
“2020-04-16T11:29:34.215728Z 标准错误:id1=requests.GET.get('id')”,
“2020-04-16T11:29:34.215731Z 标准错误:属性错误:模块 'requests' 没有属性 'GET'", "2020-04-16T11:29:34.215734Z
标准错误:" ]

你能帮忙吗? 谢谢。

【问题讨论】:

    标签: python api ibm-cloud ibm-cloud-functions


    【解决方案1】:
    def main(args):
        arg1=args.get("arg1")
        myarg=args.get("anotherarg")
    
        return {"one": arg1, "two": myarg}
    

    参数在您可以轻松访问的环境中传递。它们不是请求结构的一部分。 arg1 将是您的 id

    import sys
    import urllib3, requests, json
    import requests
    import os
    
    def main(dict):
        id1=dict.get('id')
    
        return { 'message': 'Hello world',
                 'id': id1)
    
        }
    

    【讨论】:

    • 但这是否意味着我将在脚本中有两个主要功能?
    • 我的意思是我会有 main(dict) 和 main(args)?请问?
    • 我只用上面的代码尝试了 main(args)。但是,它给了我:{“code”:“5559f9968f11637895386cd3d5ec57d9”,“error”:“请求的资源不存在。” } 启动 URL 时:fa75e0fa.eu-gb.apigw.appdomain.cloud/testapi/test1?id=11
    • 我给它起了不同的名字。您可以将其命名为 dict 或 args 或 params。使用 get() 访问您要查找的变量,该变量作为参数传入。
    • 这是一个从维基百科获取的完整示例:github.com/data-henrik/chatbot-talks/blob/2020letsmake/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2021-01-17
    • 2018-07-03
    • 2023-01-24
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    相关资源
    最近更新 更多