将示例Python待办事项列表重构为web服务,TypeError:JSON对象必须是str,而不是';字节';
下面是sample.py:将示例Python待办事项列表重构为web服务,TypeError:JSON对象必须是str,而不是';字节';,python,flask,Python,Flask,下面是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://localho
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“)作为响应:
因为我们不能使用urllib库发送POST请求,因为它以字节而不是JSON发送数据。那么我该如何使用请求库,它可以通过http协议将数据作为json发送?您的问题肯定可以在没有
请求的情况下得到解决,但无论如何,它比urllib
更易于使用,所以我推荐它。以下是您将要做的:
import requests
resp = requests.get('http://localhost:6000/api/items').json()
谢谢@alex hall。你知道我如何增强表单以创建或删除条目吗?@RobbieTheK这是一个涉及多个部分的非常广泛的问题,你需要缩小范围。