限制 python 请求的响应长度
Limiting the lenght of response with python requests
我正在设置一个视图,通过单击按钮将 API 中的数据保存到我的数据库中,我很难弄清楚如何限制请求响应的大小按以下方式获取产品描述:
如果描述的长度超过 2000,请删除其末尾的一些字母,直到达到 2000 的限制,但不要将其从请求中完全删除。
截至目前,我已经能够实现的是,如果长度高于 2000,则完全删除产品信息,如下所示。
我的 django 视图函数:
def api_data(request):
if request.GET.get('mybtn'): # to improve, == 'something':
resp_1 = requests.get(
"https://www.test-headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000¤cyCode=CAD",
headers={
"Headout-Auth": HEADOUT_TEST_API_KEY
})
resp_1_data = resp_1.json()
base_url_2 = "https://www.test-headout.com/api/public/v1/product/get/"
for item in resp_1_data['items']:
# concat ID to the URL string
url = '{}{}'.format(base_url_2, item['id'] + '?language=fr')
# make the HTTP request
resp_2 = requests.get(
url,
headers={
"Headout-Auth": HEADOUT_TEST_API_KEY
})
resp_2_data = resp_2.json()
if len(resp_2_data['contentListHtml'][0]['html']) < 2000: #represent the description of a product
Product.objects.get_or_create(
title=item['name'],
destination=item['city']['name'],
description=resp_2_data['contentListHtml'][0]['html'],
link=item['canonicalUrl'],
image=item['image']['url']
)
return render(request, "form.html")
但是我通过这样做删除了很多行,所以我想知道如何解决这个问题?
请帮忙。
您可以使用切片运算符来指定描述的字符限制,而不是使用条件语句。使用这种方法,您可以重构代码的相关部分:
resp_2_data = resp_2.json()
Product.objects.get_or_create(title=item['name'],
destination=item['city']['name'],
description=resp_2_data['contentListHtml'][0]['html'][0:2000],
....
)
我正在设置一个视图,通过单击按钮将 API 中的数据保存到我的数据库中,我很难弄清楚如何限制请求响应的大小按以下方式获取产品描述:
如果描述的长度超过 2000,请删除其末尾的一些字母,直到达到 2000 的限制,但不要将其从请求中完全删除。
截至目前,我已经能够实现的是,如果长度高于 2000,则完全删除产品信息,如下所示。
我的 django 视图函数:
def api_data(request):
if request.GET.get('mybtn'): # to improve, == 'something':
resp_1 = requests.get(
"https://www.test-headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000¤cyCode=CAD",
headers={
"Headout-Auth": HEADOUT_TEST_API_KEY
})
resp_1_data = resp_1.json()
base_url_2 = "https://www.test-headout.com/api/public/v1/product/get/"
for item in resp_1_data['items']:
# concat ID to the URL string
url = '{}{}'.format(base_url_2, item['id'] + '?language=fr')
# make the HTTP request
resp_2 = requests.get(
url,
headers={
"Headout-Auth": HEADOUT_TEST_API_KEY
})
resp_2_data = resp_2.json()
if len(resp_2_data['contentListHtml'][0]['html']) < 2000: #represent the description of a product
Product.objects.get_or_create(
title=item['name'],
destination=item['city']['name'],
description=resp_2_data['contentListHtml'][0]['html'],
link=item['canonicalUrl'],
image=item['image']['url']
)
return render(request, "form.html")
但是我通过这样做删除了很多行,所以我想知道如何解决这个问题?
请帮忙。
您可以使用切片运算符来指定描述的字符限制,而不是使用条件语句。使用这种方法,您可以重构代码的相关部分:
resp_2_data = resp_2.json()
Product.objects.get_or_create(title=item['name'],
destination=item['city']['name'],
description=resp_2_data['contentListHtml'][0]['html'][0:2000],
....
)