【问题标题】:Pass functions output as another functions argument in designed format以设计格式将函数输出作为另一个函数参数传递
【发布时间】:2021-11-29 03:19:12
【问题描述】:

我有以下函数,我将输出存储到一个名为 post 的变量中。

jobs = ('Cook', 'Vet', 'Doctor', 'Pilot')
def careers():
    output_of_careers = "Heres a list of jobs\n\n"
    for j in jobs:
        output_of_careers += f"This person is a {j}.\n"
    output_of_careers += "\nAre you interested in any of these as careers?"
    return output_of_careers
post = careers()

我需要将它传递给另一个名为(例如)apicall的函数

apicall(argument1,argument2,post)

最终发生的事情是我得到None 作为函数中post 参数的响应,即使我使用print(post)print(careers())

我需要让post 显示函数careers() 的以下输出

Heres a list of jobs

This person is a Cook.
This person is a Vet.
This person is a Doctor.
This person is a Pilot.

Are you interested in any of these as careers?

在 Python 中完成此任务的正确方法是什么?谢谢

编辑添加apicall()函数供参考

def apicall(arugment1,arugment2,post):
    apikey = 'Key here'
    headers = {'X-API-Key' : apikey}
    uri = 'urihere'
    
    # Set Query
    query = 'mutation {windowUpdate(guid: "' + arugment1 + '", window: {id: "' + arugment2 +'", configuration: {combobox: {text: "' + str(post) + '"}}, {errors {description}}}'


    response = requests.post(uri, headers = headers, data=query)
    print(response)

【问题讨论】:

  • 你能指定apicall函数的调用位置吗?
  • 你必须在函数中传递jobs才能在循环中使用
  • 我认为您应该在 requests.post() 之前添加 print(query) 以查看最终查询的样子。
  • @MelvinAbraham 我已添加该功能以供参考。我需要 apicall 函数中的 post 参数以上面打印的格式显示函数 careers() 的输出。谢谢!

标签: python scripting


【解决方案1】:

您的代码看起来非常正确,只是您可能希望将 jobs 参数传递给 careers(),以便该函数的输出可以根据您传递的作业而改变。

jobs = ('Cook', 'Vet', 'Doctor', 'Pilot')

def careers(jobs):
    output_of_careers = ""
    output_of_careers += output_of_careers +"Heres a list of jobs\n\n"
    for j in jobs:
        output_of_careers = output_of_careers +"This person is a " + j + ".\n"
    
    output_of_careers = output_of_careers +"\nAre you interested in any of these as careers?"
    return output_of_careers

post = careers(jobs)

def apicall(argument1, argument2, post_argument):
    print(post_argument)

apicall(post)
# Output:
# Heres a list of jobs
#
# This person is a Cook.
# This person is a Vet.
# This person is a Doctor.
# This person is a Pilot.
# 
# Are you interested in any of these as careers?

如果您的 apicall 函数返回的响应中没有任何内容,则很可能您没有将正确的数据发布到 API。我们将不得不查看函数以确定那里出了什么问题。

【讨论】:

  • 感谢您,但我添加了 apicall() 函数以供参考。我需要显示函数 careers() 的输出
  • 感谢更新,能否给我们看看 apicall 的状态码和响应?此外,如果您在 response = requests.post(....) 上方添加了 1 行 print(query) ,您是否获得了预期发送到 API 的输出?
  • 所以当我打印出查询时,我发现了问题。查询正是我想要的方式,但显然文本需要用括号括起来三重才能让 GraphQL 提取它。感谢您对此的帮助。
猜你喜欢
  • 1970-01-01
  • 2022-12-09
  • 2017-08-07
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-23
相关资源
最近更新 更多