-2

I am new to Flask and even though I have read through the documentation, I am still very confused on the relationship between Python functions and HTML. Specifically, I am unsure of how a function can be called within an HTML page. For example, I have the following code on my route.py file:

from flask import Flask, render_template
import requests
app = Flask(__name__) 

@app.route('/placement_debugger')
def placementDebugger():
    return render_template('placement_debugger.html')
def get_data():
    return requests.get('http://example.com'+placementID).content

Here is the code from my "placement_debugger.html" file. Basically, I am trying to obtain an ID from a user and use that ID within an HTTP GET request:

<p1>
<form action="/action_page.php">
    <strong>Placement ID: </strong><input type="text" name="Placement ID" 
     value=""><br>
    <input type="submit" value="Submit">
</form>
</p1>

How can I call my "get_data()" function within the "placement_debugger.html" page?

user7681184
  • 893
  • 2
  • 12
  • 24
  • You can't directly do that. You CAN make a REST call to the get_data() function from Javascript from your web page and get the return data. The Python code runs on the web server, and the HTML runs on the client's machine -- they can only communicate via HTTP -- a stateless protocol. – Matt Runion Sep 03 '18 at 03:20
  • Please notice that `render_template()` accepts additional keyword arguments as context. This is the way to pass data (not functions) to the template. – Klaus D. Sep 03 '18 at 03:30
  • You could do that with Jinja2 https://stackoverflow.com/questions/6036082/call-a-python-function-from-jinja2. But I dont recommend using this solution at all in your case. Better passing variables through `render_template()` as Klaus said. – SivolcC Sep 03 '18 at 06:50

1 Answers1

0

You can use request to get the data from your HTML inputs.

First import it from flask

from flask import request

By default Flask only allows GET requests. You'll need to allow POST methods to your route.

@app.route('/placement_debugger', methods=['GET', 'POST')

Here is how you can get the data from the HMTL form. (This would go in your get_data() function)

if request.form:
    placement_id = request.form.get('Placement ID')    
Thomas
  • 15
  • 7