最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Python Flask: Return HTML Content - Stack Overflow

programmeradmin2浏览0评论

i am trying to put together a makeshift tool for my own personal use, im not experienced with backend development at all. so my methods may be unconventional. although there may be a much better method to go about this

consider the following snippet from my html file:

<tr><td>
    <button id="socks.shirt.pants"> dummy text here </button>
</td></tr>

my goal, as simply as i can put it, is to click BUTTON and return the string text within the ID attribute in python using Flask. Below is the code i am working with.

app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
    #display html file
    return send_from_directory('','myfile.html')
    #this is the part that needs help
    textdata = request.htmlcontent.td.id

i have tried several different ways to extract the html content. including but not limited to:

request.html.tr.id,
request.get_data(),
request.data(),
request.form,

i understand now that request.form returns user-supplied information submitted in a form, which wont work for me because the information that i want to retrieve will be hardcoded into the html file under whichever tag that would allow this process to work. (currently tr -> td -> button). the other methods either returned None or an some empty string, i believe.

also, i am wondering if maybe there is some piece of javascript code that ill need to use in addition to Flask as well? i hope that this is not an unrealistic expectation to ask this question! any suggestions would help greatly!

i am trying to put together a makeshift tool for my own personal use, im not experienced with backend development at all. so my methods may be unconventional. although there may be a much better method to go about this

consider the following snippet from my html file:

<tr><td>
    <button id="socks.shirt.pants"> dummy text here </button>
</td></tr>

my goal, as simply as i can put it, is to click BUTTON and return the string text within the ID attribute in python using Flask. Below is the code i am working with.

app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
    #display html file
    return send_from_directory('','myfile.html')
    #this is the part that needs help
    textdata = request.htmlcontent.td.id

i have tried several different ways to extract the html content. including but not limited to:

request.html.tr.id,
request.get_data(),
request.data(),
request.form,

i understand now that request.form returns user-supplied information submitted in a form, which wont work for me because the information that i want to retrieve will be hardcoded into the html file under whichever tag that would allow this process to work. (currently tr -> td -> button). the other methods either returned None or an some empty string, i believe.

also, i am wondering if maybe there is some piece of javascript code that ill need to use in addition to Flask as well? i hope that this is not an unrealistic expectation to ask this question! any suggestions would help greatly!

Share Improve this question asked May 18, 2018 at 18:41 user9494275user9494275 1051 gold badge2 silver badges9 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 10

You can use ajax with jquery:

In the main filename.py, include a route like this, that access the parameters from the json response from the frontend. Also, provide a route that will render the HTML template:

@app.route('/recieve_data')
def get_id():
   the_id = flask.request.args.get('button_id')
   return "<p>Got it!</p>"

@app.route('/', methods=['GET', 'POST'])
def home():
   return flask.render_template('filename.html')

In your HTML (stored in filename.html), utilize the code below:

<html>
  <head>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  </head>
  <body>
    <tr><td>
     <button id="socks.shirt.pants" type='button'> dummy text here</button>
     <div id='response'></div>
    </td></tr>
  </body>
  <script>
   $(document).ready(function() {
      $("button").click(function(event){
         var the_id = event.target.id;
         $.ajax({
            url: "/recieve_data",
            type: "get",
            data: {button_id: the_id},
           success: function(response) {
           $("#response").html(response);
         },
          error: function(xhr) {
        //Do Something to handle error
        }
       });
     });
   });
  </script>
</html>

I would recommend using Socket.io along with Flask to perform real-time event handling without needing to refresh the page.

The Python imports will look something like this:

from flask_socketio import SocketIO, emit
from flask import Flask, redirect, render_template, request, session

Note that the second line contains just a few important features of the Flask library that I use within my own projects.

On the HTML side, make sure you include a reference to Socket.io (and jQuery) so that the following code will actually work. This creates an event handler to execute the inline function whenever the button in question is clicked (in this specific instance, when any button is clicked--this can be changed by using $('td button'), or even better, $('#socks.shirts.pants')). This function simply calls emit() to transmit the data to the Python backend using a websocket. The data you transmit is in a dictionary format.

namespace = 'namespace'
var socket = io();

$('button').on('click', function() {
    socket.emit('event_name', {
        'data_name' : $(this).attr('id')
    })
});

Over in the backend, we need to create an event listener to wait for this specific call to emit(). At this point, you can do whatever you want with the data!

@socketio.on('event_name', namespace='namespace')
def function_name(message):
    print(message['data_name'])

From here, you can also store it in the session variables (which is also a dictionary) so that you can use it throughout your application across different routes by simply writing session['variable_name'] = message['data_name'] in your socket handler function_name().

Hope this helps!

发布评论

评论列表(0)

  1. 暂无评论