1

我发现了一些类似于我的问题,但我无法解决这个问题。

我正在尝试通过 Google Books 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

终端向我返回以下几行:

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>
4

1 回答 1

1

我相信这是你需要的:

@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")
            ...
        ...
    ...
于 2021-06-04T01:00:10.580 回答