Python 为什么为_status()引发_未捕获错误?
正在尝试检查当前_track()函数中的none 200响应。有什么问题吗?它引发了JSONDecodeError错误。但是如果我正确理解raise_for_u状态,它应该阻止函数尝试从错误的网页加载JSON?如果我在没有此检查的情况下运行脚本,并且使用未注释的行check_playback(),它将成功捕获JSONDecodeError 该脚本正在从Spotify获取数据,并将其置于vk.com上的状态Python 为什么为_status()引发_未捕获错误?,python,python-3.x,python-requests,spotify,api-design,Python,Python 3.x,Python Requests,Spotify,Api Design,正在尝试检查当前_track()函数中的none 200响应。有什么问题吗?它引发了JSONDecodeError错误。但是如果我正确理解raise_for_u状态,它应该阻止函数尝试从错误的网页加载JSON?如果我在没有此检查的情况下运行脚本,并且使用未注释的行check_playback(),它将成功捕获JSONDecodeError 该脚本正在从Spotify获取数据,并将其置于vk.com上的状态 import config import webbrowser import reques
import config
import webbrowser
import requests
import furl
import secrets
import string
import time
import os
import simplejson as json
URL_CODE_BASE_VK = 'https://oauth.vk.com/authorize'
URL_CODE_BASE_SP = 'https://accounts.spotify.com/authorize'
URL_TOKEN_VK = 'https://oauth.vk.com/access_token'
URL_TOKEN_SP = 'https://accounts.spotify.com/api/token'
URL_TRACK = 'https://api.spotify.com/v1/me/player/currently-playing'
URL_STATUS = 'https://api.vk.com/method/status.set'
EXP_IN_TOKEN_SP = 3400
EXP_IN_TOKEN_VK = 86400
FILE_TOKEN_VK = 'vk_token.json'
FILE_TOKEN_SP = 'sp_token.json'
def get_auth_code_vk():
url_code_params = {
'client_id': config.CLIENT_ID_VK,
'response_type': 'code',
'redirect_uri': 'https://oauth.vk.com/blank.html',
'v': 5.92,
'scope': 'status',
'state': gen_state(),
'display': 'page'
}
code = url_open(URL_CODE_BASE_VK, url_code_params)
return parse_code(code)
def get_auth_code_sp():
url_code_params = {
'client_id': config.CLIENT_ID_SP,
'response_type': 'code',
'redirect_uri': 'https://www.spotify.com/',
'scope': 'user-read-currently-playing',
'state': gen_state()
}
code = url_open(URL_CODE_BASE_SP, url_code_params)
return parse_code(code)
def gen_state():
symbols = string.ascii_lowercase + string.digits
return ''.join(secrets.choice(symbols) for _ in range(12))
def url_open(url_base, url_params):
url_code_full = furl.furl(url_base).add(url_params).url
webbrowser.open_new_tab(url_code_full)
input_url = input('Enter the whole URL, that you have been redirected on: ')
return input_url
def parse_code(url):
return (url.split("code=")[1]).split("&state=")[0]
def get_token_vk():
data = {
'grant_type': 'authorization_code',
'code': get_auth_code_vk(),
'redirect_uri': 'https://oauth.vk.com/blank.html',
'client_id': 6782333,
'client_secret': config.CLIENT_SECRET_VK
}
response = requests.post(url=URL_TOKEN_VK, data=data).json()
write_file(FILE_TOKEN_VK, response)
def get_token_sp():
data = {
'grant_type': 'authorization_code',
'code': get_auth_code_sp(),
'redirect_uri': 'https://www.spotify.com/',
'client_id': config.CLIENT_ID_SP,
'client_secret': config.CLIENT_SECRET_SP
}
response = requests.post(url=URL_TOKEN_SP, data=data).json()
write_file(FILE_TOKEN_SP, response)
def write_file(tkn_file, response):
dict = {}
dict['token'] = response["access_token"]
dict['time'] = time.time()
with open(tkn_file, 'w') as file:
file.write(json.dumps(dict))
def load_file(tkn_file):
with open(tkn_file) as file:
data = json.load(file)
return data
def set_status():
params = {
'v': 5.92,
'access_token': load_file(FILE_TOKEN_VK)['token'],
'text': current_track()
}
set_status = requests.get(url=URL_STATUS, params=params)
def track_data():
tkn_file = load_file(FILE_TOKEN_SP)['token']
headers = {
'Accept': 'application/json',
'Authorization': f'Bearer {tkn_file}'
}
return requests.get(url=URL_TRACK, headers=headers)
def current_track():
response = track_data()
print(response)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
return "Error: " + str(e)
# data = track_data().json()
data = response.json()
artist = data['item']['artists'][0]['name']
track = data['item']['name']
return(f'{artist} - {track}')
def check_playback():
set_status()
print(current_track())
# try:
# set_status()
# print(current_track())
# except json.decoder.JSONDecodeError:
# print('Not playing')
def token_missing(file):
return not os.path.isfile(file)
def token_expired(file, exp_in):
return time.time() - load_file(file)['time'] > exp_in
def token_not_valid(file, exp_in):
return token_missing(file) or token_expired(file, exp_in)
def run_script():
if token_not_valid(FILE_TOKEN_VK, EXP_IN_TOKEN_VK):
get_token_vk()
if token_not_valid(FILE_TOKEN_SP, EXP_IN_TOKEN_SP):
get_token_sp()
check_playback()
if __name__ == "__main__":
run_script()
只有在服务器向您报告错误时才会引发异常(即使如此,也只有在服务器实际遵循HTTP规范并返回HTTP错误代码时才会引发异常)
库无法知道响应不正确。即使它是格式正确的JSON,它也不知道您希望它遵循什么模式(应该出现什么字段,以及这些字段应该有什么类型)。即使它知道并验证了模式,也无法知道数据实际上是正确的,并且不是当场生成的。请注意,页面可以返回200状态,但包含“断开”的JSON。在尝试解析之前,您应该检查响应的内容是否为原始文本。请尝试提供一个最简单的示例来说明您的问题。如果它在VK位运行之前崩溃,则将其删除。如果您依赖于需要身份验证的外部API,那么您可以将其替换为对的调用,等等。很抱歉没有提供所有信息,@Bakuriu,@Teo Klestrup Röijezon我实际上在
current_track
函数中打印响应,它说有204个状态。因此没有JSON,但实际上它不是一个错误。只是一个“没有数据”的回答。出于某种原因,我错误地认为,raise\u For_status
在每次没有200响应时都会引发异常。所以问题是,我真的需要在这个脚本的任何地方使用raise\u For_status
。HTTP有几十个状态代码。所有2XX状态代码表示成功。通常3XX状态码也是成功的,尽管它们告诉您重定向。只有4XX和5XX状态代码是错误<代码>为_状态提升_仅将4XX和5XX视为错误<代码>204无内容是一个很好的响应,因此您应该正确处理它。