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.
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!!
– user238776