Python—缩短请求API所需的时间
我使用以下代码从API调用不同的方法:Python—缩短请求API所需的时间,python,python-3.x,python-requests,Python,Python 3.x,Python Requests,我使用以下代码从API调用不同的方法: import requests import json from unidecode import unidecode from datetime import datetime temp_county = 'County' temp_locality = 'Locality' # Function - login session = requests.Session() def login(): # Application header
import requests
import json
from unidecode import unidecode
from datetime import datetime
temp_county = 'County'
temp_locality = 'Locality'
# Function - login
session = requests.Session()
def login():
# Application header
header = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': 'b4ed4ab7ebe84f0db79d42633771b741'
}
# User's credentials
body_login = {
'username': 'user',
'password': 'pass'
}
# Make the login request and return the token
request_url = requests.post(
'https://urgentcargus.azure-api.net/api/LoginUser', json=body_login, headers=header)
# Parse the token and remove double quotes
token = 'Bearer ' + request_url.text.strip('"')
return token
# Get country code. Since it's a local product, the request will return only the code for RO
def countries():
# Application header
header = {
'Authorization': login(),
'Ocp-Apim-Subscription-Key': 'b4ed4ab7ebe84f0db79d42633771b741'
}
# Make the request and return the country code
request_url = requests.get(
'https://urgentcargus.azure-api.net/api/Countries', headers=header
)
countries_dictionary = request_url.json()
for country in countries_dictionary:
if country['Abbreviation'] == 'RO':
countryId = str(country['CountryId'])
return countryId
def counties():
# Application header
header = {
'Authorization': login(),
'Ocp-Apim-Subscription-Key': 'b4ed4ab7ebe84f0db79d42633771b741'
}
# Load the country id
params = {
'countryId': countries()
}
# Make the request and return the county code based on the city
request_url = requests.get(
'https://urgentcargus.azure-api.net/api/Counties', params=params, headers=header
)
counties_dictionary = request_url.json()
# Parse the city description and transliterate it to ASCII
county = unidecode(temp_county)
# print(county)
# Return the county code
for countyName in counties_dictionary:
if countyName['Name'] == county:
countyId = str(countyName['CountyId'])
return countyId
def localities():
# Application header
header = {
'Authorization': login(),
'Ocp-Apim-Subscription-Key': 'b4ed4ab7ebe84f0db79d42633771b741'
}
# Load the country id and county id
params = {
'countryId': countries(),
'countyId': counties()
}
# Make the request and return the county code based on the city
request_url = requests.get(
'https://urgentcargus.azure-api.net/api/Localities', params=params, headers=header, stream=True
)
localities_dictionary = request_url.json()
# Parse the city description and transliterate it to ASCII
locality = unidecode(temp_locality)
# print(county)
# Return the locality code
for localityName in localities_dictionary:
if localityName['Name'] == locality:
localityId = str(localityName['LocalityId'])
return localityId
#
print(login())
print(countries())
print(counties())
print(localities())
这些函数运行良好,没有错误或其他问题。问题是(在我看来)它需要很多时间来完成所有功能并返回它必须返回的内容
为了节省时间,我使用了requests.Session()
来创建一个持久会话,但不知何故,这是相同的行为
我已经监控了需要多少时间,例如,大约需要5-6秒才能完成:
print('Process start! ' + str(datetime.now()))
# here are all the functions
print('Process ended! ' + str(datetime.now()))
终端响应:
Process start! 2019-10-18 13:26:09.796132
Bearer 8JCAOoSSevSpcNDydLHSAmZORL0RGgDXV110IUhxIRWABX0TNj
1
26
163
Process ended! 2019-10-18 13:26:14.663092
有什么办法可以改进吗
修改代码
# Function - login
session = requests.Session()
print('Process start! ' + str(datetime.now()))
def login():
# Application header
header = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': 'b4ed4ab7ebe84f0db79d42633771b741'
}
# User's credentials
body_login = {
'username': 'user',
'password': 'pass'
}
# Make the login request and return the token
request_url = session.post(
'https://urgentcargus.azure-api.net/api/LoginUser', json=body_login, headers=header)
# Parse the token and remove double quotes
temp_token = 'Bearer ' + request_url.text.strip('"')
return temp_token
token = login()
# Get country code. Since it's a local product, the request will return only the code for RO
def countries():
# Application header
header = {
'Authorization': token,
'Ocp-Apim-Subscription-Key': 'b4ed4ab7ebe84f0db79d42633771b741'
}
# Make the request and return the country code
request_url = session.get(
'https://urgentcargus.azure-api.net/api/Countries', headers=header
)
countries_dictionary = request_url.json()
for country in countries_dictionary:
if country['Abbreviation'] == 'RO':
countryId = str(country['CountryId'])
return countryId
def counties():
# Application header
header = {
'Authorization': token,
'Ocp-Apim-Subscription-Key': 'b4ed4ab7ebe84f0db79d42633771b741'
}
# Load the country id
params = {
'countryId': countries()
}
# Make the request and return the county code based on the city
request_url = session.get(
'https://urgentcargus.azure-api.net/api/Counties', params=params, headers=header
)
counties_dictionary = request_url.json()
# Parse the city description and transliterate it to ASCII
county = unidecode(temp_county)
# print(county)
# Return the county code
for countyName in counties_dictionary:
if countyName['Name'] == county:
countyId = str(countyName['CountyId'])
return countyId
def localities():
# Application header
header = {
'Authorization': token,
'Ocp-Apim-Subscription-Key': 'b4ed4ab7ebe84f0db79d42633771b741'
}
# Load the country id and county id
params = {
'countryId': countries(),
'countyId': counties()
}
# Make the request and return the county code based on the city
request_url = session.get(
'https://urgentcargus.azure-api.net/api/Localities', params=params, headers=header
)
localities_dictionary = request_url.json()
# Parse the city description and transliterate it to ASCII
locality = unidecode(temp_locality)
# print(county)
# Return the locality code
for localityName in localities_dictionary:
if localityName['Name'] == locality:
localityId = str(localityName['LocalityId'])
return localityId
也许您可以使用items dict方法更改所有词典中的词典迭代次数
for k , v in counties_dictionary.items():
if k == 'Name':
countyId = str(countyName['CountyId']) if v == locality else "Whatever you want"
您可以调用每个函数一次,并将输出作为其他函数的参数重用:
import requests
import json
from unidecode import unidecode
from datetime import datetime
temp_county = 'County'
temp_locality = 'Locality'
session = requests.Session()
def login():
# Application header
header = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': 'b4ed4ab7ebe84f0db79d42633771b741'
}
# User's credentials
body_login = {
'username': 'user',
'password': 'pass'
}
# Make the login request and return the token
request_url = session.post(
'https://urgentcargus.azure-api.net/api/LoginUser', json=body_login, headers=header)
# Parse the token and remove double quotes
temp_token = 'Bearer ' + request_url.text.strip('"')
return temp_token
# Get country code. Since it's a local product, the request will return only the code for RO
def countries(token):
# Application header
header = {
'Authorization': token,
'Ocp-Apim-Subscription-Key': 'b4ed4ab7ebe84f0db79d42633771b741'
}
# Make the request and return the country code
request_url = session.get(
'https://urgentcargus.azure-api.net/api/Countries', headers=header
)
countries_dictionary = request_url.json()
for country in countries_dictionary:
if country['Abbreviation'] == 'RO':
countryId = str(country['CountryId'])
return countryId
def counties(token, countryId):
# Application header
header = {
'Authorization': token,
'Ocp-Apim-Subscription-Key': 'b4ed4ab7ebe84f0db79d42633771b741'
}
# Load the country id
params = {
'countryId': countryId
}
# Make the request and return the county code based on the city
request_url = session.get(
'https://urgentcargus.azure-api.net/api/Counties', params=params, headers=header
)
counties_dictionary = request_url.json()
# Parse the city description and transliterate it to ASCII
county = unidecode(temp_county)
# print(county)
# Return the county code
for countyName in counties_dictionary:
if countyName['Name'] == county:
countyId = str(countyName['CountyId'])
return countyId
def localities(token, countryId, countyId):
# Application header
header = {
'Authorization': token,
'Ocp-Apim-Subscription-Key': 'b4ed4ab7ebe84f0db79d42633771b741'
}
# Load the country id and county id
params = {
'countryId': countryId,
'countyId': countyId
}
# Make the request and return the county code based on the city
request_url = session.get(
'https://urgentcargus.azure-api.net/api/Localities', params=params, headers=header
)
localities_dictionary = request_url.json()
# Parse the city description and transliterate it to ASCII
locality = unidecode(temp_locality)
# print(county)
# Return the locality code
for localityName in localities_dictionary:
if localityName['Name'] == locality:
localityId = str(localityName['LocalityId'])
return localityId
token = login()
countryId = countries(token)
countyId = counties(token, countryId)
localityId = localities(token, countryId, countyId)
可能吧?看起来您实际上并没有使用您创建的会话对象。使用
session.post()
和session.get()
另外,您在每个函数中调用login()
。我对azure了解不多,但我相信你只需要登录一次。只需将令牌保存到一个变量中并重新使用它。@Mosheperez-它确实将时间缩短到最多3秒。但我知道会更好,对吗?@cdrrr你到底改变了什么?您是否尝试将令牌保存在变量中并重用它?如果你愿意的话,我相信进步会更大。你也可以尝试对countries()
和countries()
@Mosheperez()的输出执行同样的操作。我已经编辑并粘贴了修改后的代码。它不是一个命令,而是一个列表。现在速度快多了,1-2秒,这当然取决于与服务器的通信,而服务器无法控制。谢谢