我有此代码:
from flask import Flask, flash, redirect, render_template, request, session, abort
import os
import json
from urllib.request import urlopen
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app = Flask(__name__, template_folder=tmpl_dir)
def getExchangeRates():
rates = []
response = urlopen('https://data.fixer.io/api/latest?access_key=my_key')
data = response.read()
rdata = json.loads(data, parse_float=float)
rates.append( rdata['rates']['USD'] )
rates.append( rdata['rates']['GBP'] )
rates.append( rdata['rates']['HKD'] )
rates.append( rdata['rates']['AUD'] )
return rates
@app.route("/")
def index():
rates = getExchangeRates()
return render_template('test.html',**locals())
@app.route("/hello")
def hello():
return "Hello World!"
但是它把我扔了
Traceback (most recent call last):
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/home/kristian/.virtualenvs/usio_flask/lib/python3.4/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "app/app.py", line 23, in index
rates = getExchangeRates()
File "app/app.py", line 13, in getExchangeRates
rdata = json.loads(data, parse_float=float)
File "/usr/lib/python3.4/json/__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'
违规行是这一行:
rdata = json.loads(data, parse_float=float)
我只是想从fixer.io
API中获得一些收益,有什么想法吗?
如果名称 ==“ 主要”: app.run()
答案 0 :(得分:2)
使用此str将s(包含JSON文档的conversion table实例)反序列化为Python对象。
urllib.request.urlopen
返回一个http.client.HTTPResponse
对象。
根据[Python 3.5]: HTTPResponse.read([amt]):
读取并返回响应正文,或直至下一个 amt 字节。
因此,为了使这项工作有效,您必须将 bytes 转换为 str
(通过[Python 3.5]: bytes.decode(encoding="utf-8", errors="strict")):
rdata = json.loads(data.decode(), parse_float=float)
注意:
json.loads
还能处理字节 关于您的其他错误,我记得(当我曾经与 Flask 一起工作过),{<1>}对象只有Response
方法,如果 HTTP < / em>状态代码为 200 (确定)。但由于我使用的是 requests 模块,所以我不确定它与我们正在讨论的对象是同一对象。