将示例 Python 待办事项列表重构为 Web 服务,类型错误:JSON 对象必须是 str,而不是'bytes'



这是 sample.py:

from flask import Flask, render_template, jsonify
import urllib.request
import sqlite3
import json
app = Flask(__name__)
app.config.from_object(__name__)
@app.route("/")
def show_list():
with urllib.request.urlopen('http://localhost:6000/api/items') as response:
resp = response.read()
resp = json.loads(resp)
return render_template('index.html', todolist=resp)

if __name__ == "__main__":
app.debug = True
app.run(port=5000)

这是 sampleapi.py

from flask import Flask, render_template, redirect, g, request, url_for, jsonify
import sqlite3
import urllib.request
DATABASE = 'todolist.db'
app = Flask(__name__)
app.config.from_object(__name__)
@app.route("/api/items")
def get_items():
db = get_db()
cur = db.execute('SELECT what_to_do, due_date, status FROM entries')
entries = cur.fetchall()
tdlist = [dict(what_to_do=row[0], due_date=row[1], status=row[2])
for row in entries]
return jsonify(tdlist)
def get_db():
"""open new db connection.
"""
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = sqlite3.connect(app.config['DATABASE'])
return g.sqlite_db
@app.teardown_appcontext
def close_db(error):
"""Close db at the end of the request."""
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
if __name__ == "__main__":
app.run("0.0.0.0", port=6000)

这是我得到的错误:

File "sample.py", line 14, in show_list
TypeError: the JSON object must be str, not 'bytes'

所以我相信我必须改变urllib.request.urlopen('http://localhost:6000/api/items') as response:

因为我们无法使用 urllib 库来发送 POST 请求,因为它以字节而不是 JSON 的形式发送数据。那么如何使用请求库,它可以通过 http 协议以 json 的形式发送数据呢?

你的问题绝对可以在没有requests的情况下解决,但它比urllib更容易使用,所以我推荐它。以下是您要执行的操作:

import requests
resp = requests.get('http://localhost:6000/api/items').json()

最新更新