How to send a Javascript parameter to Python?

Asked

Viewed 49 times

0

How I send a parameter to be read by a function in Python?

I have the following function in Python:

@app.route("/add")
def add(book_id):
    """Atribui o ID de um livro ao ID do usuário"""
    db.execute("""
        INSERT INTO reading (user_id, book_id, price)
        VALUES (:user_id, :symbol, :book_id, :price)
        """,
        user_id = session["user_id"],
        book_id = book_id,
        price = 20 # TODO
    )
    return redirect("/")

To get to this function I use the following script:

var result = document.getElementById("result");
var cover, title, author;

function handleResponse(response) {
  for (var i = 0; i < response.items.length; i++) {
    var item = response.items[i];
    // Cria elementos
    figure = document.createElement("figure");
    add = document.createElement("a");
    img = document.createElement("img");
    figcap = document.createElement("figcaption");
    // Recebe dados do JSON
    try {
      cover = item.volumeInfo.imageLinks.thumbnail;
      title = item.volumeInfo.title;
      author = item.volumeInfo.authors;
    } catch (error) {
      continue;
    } finally {
      // Atribui valores aos elementos e insere no HTML
      result.appendChild(figure);
      add.href = "/add"; // AQUI EU ACESSO O @app.route no PYTHON
      figure.appendChild(add);
      img.src = cover;
      add.appendChild(img);
      figcap.innerHTML += `${title}<br>${author}`;
      add.appendChild(figcap);
    }
  }
}
document.querySelector("form").addEventListener("submit", function(e) {
  result.innerHTML = "";
  search = document.getElementById("search").value;
  var script = document.createElement("script");
  script.src = `https://www.googleapis.com/books/v1/volumes?q=${search}&callback=handleResponse`;
  document.body.appendChild(script);
  e.preventDefault();
});
<form>
  <input type="text" id="search" placeholder="Pesquise por título, autor, editora, lançamento, ISBN..." />
  <button type="submit">Buscar</button>
</form>
<div id="result"></div>

I would like to know how I pass the parameter book_id in Javascript to receive it in Python.

1 answer

2


You can pass the book_id through the URL by doing the following: @app.route('/add/<int:book_id>')

Within your handleResponse function change to add.href = `/add/${item.book_id}`.

I’m assuming that the item has a book_id attribute, because in its code I only found cover, title, Author.

Reference: https://flask.palletsprojects.com/en/1.1.x/quickstart/

  • Python seems to receive the parameter very well, What you showed is right according to the documentation, but Javascript returned 404. Then I realized that I should use crase instead of quotation marks. Thank you very much!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.