下面是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的形式发送数据。那么,如何使用请求库,它可以作为json通过http协议发送数据呢?
发布于 2018-04-24 14:43:39
你的问题肯定可以在没有requests
的情况下解决,但无论如何它比urllib
更容易使用,所以我推荐它。下面是你要做的事情:
import requests
resp = requests.get('http://localhost:6000/api/items').json()
https://stackoverflow.com/questions/50004382
复制相似问题