【问题标题】:String Concatenation in URLURL 中的字符串连接
【发布时间】:2019-12-27 05:46:31
【问题描述】:

TypeError:只能将str(不是“builtin_function_or_method”)连接到str

在第 5 行:

resp = requests.get(BASE_URL + ENDPOINT + id + '/')

我的代码:

import requests
BASE_URL = 'http://127.0.0.1:8000/'
ENDPOINT = 'api/'
def get_resource(id):
    resp = requests.get(BASE_URL + ENDPOINT + id + '/')
    print(resp.status_code)
    data = resp.json()
    print(data)
get_resource(id)

【问题讨论】:

  • id 的值是多少?
  • id 持有整数
  • 使用str(id)函数转换整数值。

标签: rest django-rest-framework active-model-serializers


【解决方案1】:

您的代码的问题是您使用参数id 调用get_resource(),而id 的值未在任何地方定义。

您需要为 id 分配一个字符串。如果您传递的是整数,则使用str(id) 将其转换为字符串。

resp = requests.get(BASE_URL + ENDPOINT + str(id) + '/')

【讨论】:

    【解决方案2】:

    您需要将id作为字符串传递,如果您使用python> 3.6,您可以使用f字符串作为字符串连接

    resp = requests.get(f"{BASE_URL}{ENDPOINT}{id}/")
    

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      • 2014-03-31
      • 2017-12-17
      • 1970-01-01
      • 2017-04-24
      相关资源
      最近更新 更多