-2

I've been banging my head against the wall to figure this one out. I am writing an app which, ideally, when an onclick happens in HTML runs a python script from FLASK. The problem is nothing I do seems to work. I don't get errors anymore but the program doesn't run.

I've tried accessing the python script through AJAX, I tried calling the python script through jscript in the HTML, I created a separate file for the python script instead of running it through Flask....

</style>
<h1>Book Roulette</h1>
<h2>Discover Something New</h2>
<h3>Click the image to download a surprise book</h3>
<a href="/static/gut.py"> <button class="button" style="background: url(/static/images/stack.jpg)" onclick="button();" action="/button"></a>
</button>
<script>

$(function() {
    $('button').click(function() {
        $.ajax({
            url: 'static/gut.py',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
                console.log(response);
            },
            error: function(error) {
                console.log(error);
            }
        });
    });
});

</script>
</body>
</html>

Here is my Flask/Python Document

from flask import Flask, render_template
from gutenberg.acquire import load_etext
from gutenberg.cleanup import strip_headers
import random


app = Flask(__name__, static_url_path='/static')



@app.route('/books')
def books():
    return render_template("main.html")


@app.route('/button', methods=["GET", "POST"])
def button():
    f = open("GutProject.txt", "w")
    for x in range(1):
        y = (random.randint(0, 59000))
        text = strip_headers(load_etext(y)).strip()
        f.write(text)



if __name__ == "__main__":
    app.run(debug=True)

What I want to do is have the python code run when I click my HTML button generating a new file on the user's computer. So far I've reached the point where when I click on the button nothing happens.

  • Have you looked in the Developer Tools of your browser? You can open them by pressing F12. Go to the tab 'Console'. Are there any error messages? – Developer Aug 10 '19 at 18:48

3 Answers3

0

What you're actually trying to achieve here is create a client / server project. Your html is your client or frontend, and python is your server, or backend. The way to make the two communicate is through an api. Then, you should start your Flask app beforehand, and not calling the script from the frontend, but instead sending requests to the right endpoint. Assuming you're running Flask on your local machine on the default port, try on the front end side replacing url: 'static/gut.py' with the following value: url: 'http://localhost:5000/button'

This should trigger the associated function whenever you click your button.

paupaulaz
  • 937
  • 1
  • 11
  • 20
  • $(function() { $('button').click(function() { $.ajax({ url:'http://localhost:5000/button', data: $('form').serialize(), type: 'POST', success: function(response) { console.log(response); }, error: function(error) { console.log(error); } }); }); }); – Jordan Brandes Aug 10 '19 at 17:18
  • have you launched your flask server from a terminal before opening the html page? If yes, what is the output on the terminal? – paupaulaz Aug 10 '19 at 17:23
  • Here is the full output when I load the page and click the button – Jordan Brandes Aug 10 '19 at 17:46
  • * Serving Flask app "app" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 284-389-406 127.0.0.1 - - [10/Aug/2019 12:46:18] "GET /books HTTP/1.1" 200 - – Jordan Brandes Aug 10 '19 at 17:47
0

For the functionality that you want to reach, you would need a second server additional to you Flask app. Because the POST request needs to be handled by an already running web application, it's impossible to achieve your goal without having a second service that receives this POST request, and runs your Flask app as a child process.

Sergio Pulgarin
  • 869
  • 8
  • 20
  • How would I go about doing that? – Jordan Brandes Aug 10 '19 at 18:02
  • It can be a Flask application that inside a route, uses the `subprocess` module to spawn the process of the second Flask application (see https://stackoverflow.com/questions/24787106/run-a-child-process-free-of-the-parent-in-python). In any case, this use case sounds a bit backwards so I would explore other approaches. I couldn't suggest any because I don't know what is the end goal here. – Sergio Pulgarin Aug 11 '19 at 01:18
0

UPDATE: I actually managed to figure it out without using jquery or PHP.

</script>
<a href="/roulette"><input type="button" name="button" class="button" style="background: url(/static/images/stack.jpg)"></input></a>
</body>
</html>

Thank you guys for your help.

xxx
  • 1,153
  • 1
  • 11
  • 23