Unexpected return from JSON lookup when using request.form.get

83 views Asked by At

I found some questions similar to mine but I couldn't solve this problem.

I'm trying to perform a search via the Google Books API, but I can't get what the user types.

<form action="/search">
  <input type="text" id="search" name="seek" placeholder="Search you book..." />
  <button type="submit">Search</button>
</form>

After the submit I call def search and try to get what the user typed using request.form.get("seek"). I'm doing it as follows:

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

The terminal returns the following lines to me:

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

In HTML, I just display it by calling it this way:

<p>{{ search['totalItems'] }}</p>
<p>{{ search['items'] }}</p>
1

There are 1 answers

0
ARNON On BEST ANSWER

I believe this is what you need:

@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")
            ...
        ...
    ...