使用Python 3,我从URL请求json文档.
response = urllib.request.urlopen(request)
Run Code Online (Sandbox Code Playgroud)
该response对象是一个类似文件的对象read和readline方法.通常,可以使用以文本模式打开的文件创建JSON对象.
obj = json.load(fp)
Run Code Online (Sandbox Code Playgroud)
我想做的是:
obj = json.load(response)
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用,因为urlopen以二进制模式返回文件对象.
当然,解决方法是:
str_response = response.read().decode('utf-8')
obj = json.loads(str_response)
Run Code Online (Sandbox Code Playgroud)
但这感觉很糟糕......
有没有更好的方法可以将字节文件对象转换为字符串文件对象?或者我错过任何参数urlopen或json.load给出编码?
我正在为将返回渲染模板的函数编写 Flask 单元测试。我尝试了几种方法,但似乎不起作用。这是函数:
@app.route('/', methods=['POST'])
@lti(request='initial', error=error, app=app)
def chooser(lti=lti):
return_url = request.form.get('launch_presentation_return_url', '#')
return render_template(
'chooser.html'
)
Run Code Online (Sandbox Code Playgroud)
我一直在尝试的几种方法:
# 1st way
rv = self.app.post('/')
self.assertTrue('Choose an Icon to Insert' in rv.get_data(as_text=True))
# Error
self.assertTrue('Choose an Icon to Insert' in rv.get_data(as_text=True))
AssertionError: False is not true
# 2nd way
rv = self.app.post('/chooser.html')
assert '<h1>Choose an Icon to Insert</h1>' in rv.data
# Error
assert 'Choose an Icon to Insert' in rv.data
AssertionError
Run Code Online (Sandbox Code Playgroud)
选择器.html
<body>
<h1>Choose an Icon to Insert</h1>
</body>
Run Code Online (Sandbox Code Playgroud)
感谢您的所有帮助。