【问题标题】:How to check if the url contains JSON file如何检查 url 是否包含 JSON 文件
【发布时间】:2016-03-05 19:28:01
【问题描述】:

我正在使用 League of Legends API,我正在尝试从 JSON 文件中获取排名数据。但是,如果玩家不是30级,他就没有他的档案。 所以这里

def getRankedData(region, ID, APIkey):
    URL = "https://" + region + ".api.pvp.net/api/lol/" + region + "/v2.5/league/by-summoner/" + ID + "/entry?api_key=" + APIkey
    response = requests.get(URL)
    return response.json()

它不会得到 JSON 文件,因为它不存在。我该怎么做,如果 URL 不存在并且没有 JSON 文件,它会返回字符串。

在这里,我将数据返回到 HTML 页面。但这也行不通。

 region = request.form['region']
 summonerName = request.form['summonerName']
 APIkey = "45afde27-b628-473f-9a94-feec8eb86094"
 types = request.form['types']
 responseJSON = getData(region, summonerName, APIkey)
 ID = responseJSON[summonerName]['id']
 ID = str(ID)
 responseJSON2 = getRankedData(region, ID, APIkey)
 if not responseJSON2:
     divisionName = "Unranked"
 else: 
     divisionName = responseJSON2[ID][0]['name']
 responseJSON3 = getChallengerPlayers(region, str(types), APIkey)
 challengerPlayers = responseJSON3['entries'][0]['wins']
 #print challengerPlayers

 return render_template('form_action.html', ID = ID, divisionName = divisionName, challengerPlayers = challengerPlayers)

我收到此错误:

Traceback (most recent call last)
File "C:\Python27\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python27\lib\site-packages\flask\app.py", line 1403, in      handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1477, in     full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1381, in  handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1475, in     full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1461, in  dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Hanisek\Documents\Visual Studio     2015\Projects\FlaskWebProject2\FlaskWebProject2\FlaskWebProject2\views.py", line 53, in hello
responseJSON2 = getRankedData(region, ID, APIkey)
File "C:\Users\Hanisek\Documents\Visual Studio 2015\Projects\FlaskWebProject2\FlaskWebProject2\FlaskWebProject2\views.py", line 21, in getRankedData
Open an interactive python shell in this framereturn response.json()
File "C:\Python27\lib\requests\models.py", line 805, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Python27\lib\json\__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

【问题讨论】:

  • 能否请您提供回复的 sn-p?
  • @albert 你是什么意思?
  • 由于无法将响应解码为 json 对象而引发错误。因此,查看响应可能会有所帮助

标签: python json api flask python-requests


【解决方案1】:

通过在浏览器中运行来检查 api url 返回的内容总是一个好主意。我猜它会返回 404 错误,因为该信息不存在。

在这种情况下,我建议在继续进行 JSON 解析之前检查是否存在 404 错误。

Request 有一个名为 status_code 的函数,如果存在 404 错误,它将返回。 示例代码:

r = request.get("API STRING")
if r.status_code != 404:
    r.json()

【讨论】:

    【解决方案2】:

    对LOL不太了解,但是否有理由让您的程序无法使用if/then语句来检查播放器的级别,然后仅在播放器级别足够高时才检查json文件有吗?

    【讨论】:

    • 非常感谢您的回答。优于 100 行编码。
    • 没问题,通常最简单的答案就是正确的一个~occams razor
    【解决方案3】:

    您可以尝试检查 URL 是否存在、JSON 格式是否正确或页面是否抛出 40X 状态代码

    try:
        r = requests.get("URL")
        assert r.status_code < 400
        return r.json()
    except (ValueError, ConnectionError, AssertionError):
        return ''
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多