使用 request.form.get 时 JSON 查找中的意外 return
Unexpected return from JSON lookup when using request.form.get
我发现了一些与我相似的问题,但我无法解决这个问题。
我正在尝试通过 Google 图书 API 执行搜索,但我无法获取用户键入的内容。
<form action="/search">
<input type="text" id="search" name="seek" placeholder="Search you book..." />
<button type="submit">Search</button>
</form>
提交后我调用 def search
并尝试获取用户使用 request.form.get("seek")
键入的内容。我是这样做的:
import requests
from flask import Flask, render_template, redirect, request, session
@app.route('/search')
@login_required
def search():
"""Look up search for books."""
seek = request.form.get("seek")
try:
url = f'https://www.googleapis.com/books/v1/volumes?q={seek}'
response = requests.get(url)
response.raise_for_status()
except requests.RequestException:
return None
# Parse response
try:
search = response.json()
return render_template("search.html", search={
"totalItems": int(search["totalItems"]),
"items": search["items"]
})
except (KeyError, TypeError, ValueError):
return None
终端returns下面几行给我:
DEBUG: Starting new HTTPS connection (1): www.googleapis.com:443
DEBUG: https://www.googleapis.com:443 "GET /books/v1/volumes?q=None HTTP/1.1" 200 None
在HTML中,我就是这样调用显示的:
<p>{{ search['totalItems'] }}</p>
<p>{{ search['items'] }}</p>
我相信这就是您所需要的:
@app.route('/search', methods=["GET", "POST"])
@login_required
def search():
"""Look up search for books."""
if request.method == "POST":
try:
seek = request.form.get("seek")
...
...
...
我发现了一些与我相似的问题,但我无法解决这个问题。
我正在尝试通过 Google 图书 API 执行搜索,但我无法获取用户键入的内容。
<form action="/search">
<input type="text" id="search" name="seek" placeholder="Search you book..." />
<button type="submit">Search</button>
</form>
提交后我调用 def search
并尝试获取用户使用 request.form.get("seek")
键入的内容。我是这样做的:
import requests
from flask import Flask, render_template, redirect, request, session
@app.route('/search')
@login_required
def search():
"""Look up search for books."""
seek = request.form.get("seek")
try:
url = f'https://www.googleapis.com/books/v1/volumes?q={seek}'
response = requests.get(url)
response.raise_for_status()
except requests.RequestException:
return None
# Parse response
try:
search = response.json()
return render_template("search.html", search={
"totalItems": int(search["totalItems"]),
"items": search["items"]
})
except (KeyError, TypeError, ValueError):
return None
终端returns下面几行给我:
DEBUG: Starting new HTTPS connection (1): www.googleapis.com:443
DEBUG: https://www.googleapis.com:443 "GET /books/v1/volumes?q=None HTTP/1.1" 200 None
在HTML中,我就是这样调用显示的:
<p>{{ search['totalItems'] }}</p>
<p>{{ search['items'] }}</p>
我相信这就是您所需要的:
@app.route('/search', methods=["GET", "POST"])
@login_required
def search():
"""Look up search for books."""
if request.method == "POST":
try:
seek = request.form.get("seek")
...
...
...