I am a newbie for the aiohttp, and I have a question below,
First, I have a button in the page as below,
<body>
<button class="button" name="click_me" onclick="click_me">Click Me</button>
</body>
and in the python code, I define the function as below,
async def click_me(request):
logger.info(f'test on click_me')
async def handler(request):
... ... default code here ... ...
However, when I open the browser and click the "click_me" button, the debugging page shows the error,
Uncaught ReferenceError: click_me is not defined at HTMLButtonElement.onclick
How to define the function in the python script to catch click_me event?
No, the onclick attribute refers to a Javascript function, that must be loaded in your page. If you want to call a Python function from that click event, you must perform an HTTP request (or whatever, there are many other ways), for instance with AJAX or fetch, to your corresponing server's url. e.g.
<body>
<button onclick="doFoo()"></button>
<script>
async function doFoo() {
const response = await fetch('http://YOURSERVER/foo')
// do whatever you want with your response
}
</script>
</body>
Will call the Python foo function defined here
from aiohttp import web
async def foo(request):
logger.info("button clicked")
return web.Response()
app = web.Application()
app.add_routes([web.get('/foo', foo)])
if __name__ == '__main__':
web.run_app(app)
Related
I have a view that generates data and streams it in real time. I can't figure out how to send this data to a variable that I can use in my HTML template. My current solution just outputs the data to a blank page as it arrives, which works, but I want to include it in a larger page with formatting. How do I update, format, and display the data as it is streamed to the page?
import flask
import time, math
app = flask.Flask(__name__)
#app.route('/')
def index():
def inner():
# simulate a long process to watch
for i in range(500):
j = math.sqrt(i)
time.sleep(1)
# this value should be inserted into an HTML template
yield str(i) + '<br/>\n'
return flask.Response(inner(), mimetype='text/html')
app.run(debug=True)
You can stream data in a response, but you can't dynamically update a template the way you describe. The template is rendered once on the server side, then sent to the client.
One solution is to use JavaScript to read the streamed response and output the data on the client side. Use XMLHttpRequest to make a request to the endpoint that will stream the data. Then periodically read from the stream until it's done.
This introduces complexity, but allows updating the page directly and gives complete control over what the output looks like. The following example demonstrates that by displaying both the current value and the log of all values.
This example assumes a very simple message format: a single line of data, followed by a newline. This can be as complex as needed, as long as there's a way to identify each message. For example, each loop could return a JSON object which the client decodes.
from math import sqrt
from time import sleep
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/stream")
def stream():
def generate():
for i in range(500):
yield "{}\n".format(sqrt(i))
sleep(1)
return app.response_class(generate(), mimetype="text/plain")
<p>This is the latest output: <span id="latest"></span></p>
<p>This is all the output:</p>
<ul id="output"></ul>
<script>
var latest = document.getElementById('latest');
var output = document.getElementById('output');
var xhr = new XMLHttpRequest();
xhr.open('GET', '{{ url_for('stream') }}');
xhr.send();
var position = 0;
function handleNewData() {
// the response text include the entire response so far
// split the messages, then take the messages that haven't been handled yet
// position tracks how many messages have been handled
// messages end with a newline, so split will always show one extra empty message at the end
var messages = xhr.responseText.split('\n');
messages.slice(position, -1).forEach(function(value) {
latest.textContent = value; // update the latest value in place
// build and append a new item to a list to log all output
var item = document.createElement('li');
item.textContent = value;
output.appendChild(item);
});
position = messages.length - 1;
}
var timer;
timer = setInterval(function() {
// check the response for new data
handleNewData();
// stop checking once the response has ended
if (xhr.readyState == XMLHttpRequest.DONE) {
clearInterval(timer);
latest.textContent = 'Done';
}
}, 1000);
</script>
An <iframe> can be used to display streamed HTML output, but it has some downsides. The frame is a separate document, which increases resource usage. Since it's only displaying the streamed data, it might not be easy to style it like the rest of the page. It can only append data, so long output will render below the visible scroll area. It can't modify other parts of the page in response to each event.
index.html renders the page with a frame pointed at the stream endpoint. The frame has fairly small default dimensions, so you may want to to style it further. Use render_template_string, which knows to escape variables, to render the HTML for each item (or use render_template with a more complex template file). An initial line can be yielded to load CSS in the frame first.
from flask import render_template_string, stream_with_context
#app.route("/stream")
def stream():
#stream_with_context
def generate():
yield render_template_string('<link rel=stylesheet href="{{ url_for("static", filename="stream.css") }}">')
for i in range(500):
yield render_template_string("<p>{{ i }}: {{ s }}</p>\n", i=i, s=sqrt(i))
sleep(1)
return app.response_class(generate())
<p>This is all the output:</p>
<iframe src="{{ url_for("stream") }}"></iframe>
5 years late, but this actually can be done the way you were initially trying to do it, javascript is totally unnecessary (Edit: the author of the accepted answer added the iframe section after I wrote this). You just have to include embed the output as an <iframe>:
from flask import Flask, render_template, Response
import time, math
app = Flask(__name__)
#app.route('/content')
def content():
"""
Render the content a url different from index
"""
def inner():
# simulate a long process to watch
for i in range(500):
j = math.sqrt(i)
time.sleep(1)
# this value should be inserted into an HTML template
yield str(i) + '<br/>\n'
return Response(inner(), mimetype='text/html')
#app.route('/')
def index():
"""
Render a template at the index. The content will be embedded in this template
"""
return render_template('index.html.jinja')
app.run(debug=True)
Then the 'index.html.jinja' file will include an <iframe> with the content url as the src, which would something like:
<!doctype html>
<head>
<title>Title</title>
</head>
<body>
<div>
<iframe frameborder="0"
onresize="noresize"
style='background: transparent; width: 100%; height:100%;'
src="{{ url_for('content')}}">
</iframe>
</div>
</body>
When rendering user-provided data render_template_string() should be used to render the content to avoid injection attacks. However, I left this out of the example because it adds additional complexity, is outside the scope of the question, isn't relevant to the OP since he isn't streaming user-provided data, and won't be relevant for the vast majority of people seeing this post since streaming user-provided data is a far edge case that few if any people will ever have to do.
Originally I had a similar problem to the one posted here where a model is being trained and the update should be stationary and formatted in Html. The following answer is for future reference or people trying to solve the same problem and need inspiration.
A good solution to achieve this is to use an EventSource in Javascript, as described here. This listener can be started using a context variable, such as from a form or other source. The listener is stopped by sending a stop command. A sleep command is used for visualization without doing any real work in this example. Lastly, Html formatting can be achieved using Javascript DOM-Manipulation.
Flask Application
import flask
import time
app = flask.Flask(__name__)
#app.route('/learn')
def learn():
def update():
yield 'data: Prepare for learning\n\n'
# Preapre model
time.sleep(1.0)
for i in range(1, 101):
# Perform update
time.sleep(0.1)
yield f'data: {i}%\n\n'
yield 'data: close\n\n'
return flask.Response(update(), mimetype='text/event-stream')
#app.route('/', methods=['GET', 'POST'])
def index():
train_model = False
if flask.request.method == 'POST':
if 'train_model' in list(flask.request.form):
train_model = True
return flask.render_template('index.html', train_model=train_model)
app.run(threaded=True)
HTML Template
<form action="/" method="post">
<input name="train_model" type="submit" value="Train Model" />
</form>
<p id="learn_output"></p>
{% if train_model %}
<script>
var target_output = document.getElementById("learn_output");
var learn_update = new EventSource("/learn");
learn_update.onmessage = function (e) {
if (e.data == "close") {
learn_update.close();
} else {
target_output.innerHTML = "Status: " + e.data;
}
};
</script>
{% endif %}
Fastapi docs include a websocket example that receives data via html/javascript. Saving the script as main.py and running uvicorn main:app --reload, the example works as expected:
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
app = FastAPI()
html = """
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<form action="" onsubmit="sendMessage(event)">
<input type="text" id="messageText" autocomplete="off"/>
<button>Send</button>
</form>
<ul id='messages'>
</ul>
<script>
var ws = new WebSocket("ws://localhost:8000/ws");
ws.onmessage = function(event) {
var messages = document.getElementById('messages')
var message = document.createElement('li')
var content = document.createTextNode(event.data)
message.appendChild(content)
messages.appendChild(message)
};
function sendMessage(event) {
var input = document.getElementById("messageText")
ws.send(input.value)
input.value = ''
event.preventDefault()
}
</script>
</body>
</html>
"""
#app.get("/")
async def get():
return HTMLResponse(html)
#app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
How can I modify this example to write websocket messages to file without using any html/js? I'd like direct access to the incoming data (text/json) with python and I'm unable to capture it directly. Any additional info/clarity is appreciated.
So, probably in the comments I didn't explain myself well.
From what I understood you want to connect via python to your webserver with a websocket and log to file the messages the server sends to your python script on the client. In simpler terms, you need to mimic the html/js part via python.
TL;DR
The server is already there, you just need to connect to it.
Here's the code snippet that you have to copy and paste in a different file and run when the webserver is already running. Note that the webserver doesn't need to be changed, if not for the two line within the while True loop. These can go away and you may change them with something like await websocket.send_text("text")
import asyncio
import websockets
async def hello():
uri = "ws://localhost:8000/ws"
async with websockets.connect(uri) as websocket:
await websocket.send("Hello world!")
res = await websocket.recv()
print(res)
asyncio.get_event_loop().run_until_complete(hello())
I'm not sure what messages you need to write to file, but the code snippet above is working and is the basis for what you need.
I have a view that generates data and streams it in real time. I can't figure out how to send this data to a variable that I can use in my HTML template. My current solution just outputs the data to a blank page as it arrives, which works, but I want to include it in a larger page with formatting. How do I update, format, and display the data as it is streamed to the page?
import flask
import time, math
app = flask.Flask(__name__)
#app.route('/')
def index():
def inner():
# simulate a long process to watch
for i in range(500):
j = math.sqrt(i)
time.sleep(1)
# this value should be inserted into an HTML template
yield str(i) + '<br/>\n'
return flask.Response(inner(), mimetype='text/html')
app.run(debug=True)
You can stream data in a response, but you can't dynamically update a template the way you describe. The template is rendered once on the server side, then sent to the client.
One solution is to use JavaScript to read the streamed response and output the data on the client side. Use XMLHttpRequest to make a request to the endpoint that will stream the data. Then periodically read from the stream until it's done.
This introduces complexity, but allows updating the page directly and gives complete control over what the output looks like. The following example demonstrates that by displaying both the current value and the log of all values.
This example assumes a very simple message format: a single line of data, followed by a newline. This can be as complex as needed, as long as there's a way to identify each message. For example, each loop could return a JSON object which the client decodes.
from math import sqrt
from time import sleep
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/stream")
def stream():
def generate():
for i in range(500):
yield "{}\n".format(sqrt(i))
sleep(1)
return app.response_class(generate(), mimetype="text/plain")
<p>This is the latest output: <span id="latest"></span></p>
<p>This is all the output:</p>
<ul id="output"></ul>
<script>
var latest = document.getElementById('latest');
var output = document.getElementById('output');
var xhr = new XMLHttpRequest();
xhr.open('GET', '{{ url_for('stream') }}');
xhr.send();
var position = 0;
function handleNewData() {
// the response text include the entire response so far
// split the messages, then take the messages that haven't been handled yet
// position tracks how many messages have been handled
// messages end with a newline, so split will always show one extra empty message at the end
var messages = xhr.responseText.split('\n');
messages.slice(position, -1).forEach(function(value) {
latest.textContent = value; // update the latest value in place
// build and append a new item to a list to log all output
var item = document.createElement('li');
item.textContent = value;
output.appendChild(item);
});
position = messages.length - 1;
}
var timer;
timer = setInterval(function() {
// check the response for new data
handleNewData();
// stop checking once the response has ended
if (xhr.readyState == XMLHttpRequest.DONE) {
clearInterval(timer);
latest.textContent = 'Done';
}
}, 1000);
</script>
An <iframe> can be used to display streamed HTML output, but it has some downsides. The frame is a separate document, which increases resource usage. Since it's only displaying the streamed data, it might not be easy to style it like the rest of the page. It can only append data, so long output will render below the visible scroll area. It can't modify other parts of the page in response to each event.
index.html renders the page with a frame pointed at the stream endpoint. The frame has fairly small default dimensions, so you may want to to style it further. Use render_template_string, which knows to escape variables, to render the HTML for each item (or use render_template with a more complex template file). An initial line can be yielded to load CSS in the frame first.
from flask import render_template_string, stream_with_context
#app.route("/stream")
def stream():
#stream_with_context
def generate():
yield render_template_string('<link rel=stylesheet href="{{ url_for("static", filename="stream.css") }}">')
for i in range(500):
yield render_template_string("<p>{{ i }}: {{ s }}</p>\n", i=i, s=sqrt(i))
sleep(1)
return app.response_class(generate())
<p>This is all the output:</p>
<iframe src="{{ url_for("stream") }}"></iframe>
5 years late, but this actually can be done the way you were initially trying to do it, javascript is totally unnecessary (Edit: the author of the accepted answer added the iframe section after I wrote this). You just have to include embed the output as an <iframe>:
from flask import Flask, render_template, Response
import time, math
app = Flask(__name__)
#app.route('/content')
def content():
"""
Render the content a url different from index
"""
def inner():
# simulate a long process to watch
for i in range(500):
j = math.sqrt(i)
time.sleep(1)
# this value should be inserted into an HTML template
yield str(i) + '<br/>\n'
return Response(inner(), mimetype='text/html')
#app.route('/')
def index():
"""
Render a template at the index. The content will be embedded in this template
"""
return render_template('index.html.jinja')
app.run(debug=True)
Then the 'index.html.jinja' file will include an <iframe> with the content url as the src, which would something like:
<!doctype html>
<head>
<title>Title</title>
</head>
<body>
<div>
<iframe frameborder="0"
onresize="noresize"
style='background: transparent; width: 100%; height:100%;'
src="{{ url_for('content')}}">
</iframe>
</div>
</body>
When rendering user-provided data render_template_string() should be used to render the content to avoid injection attacks. However, I left this out of the example because it adds additional complexity, is outside the scope of the question, isn't relevant to the OP since he isn't streaming user-provided data, and won't be relevant for the vast majority of people seeing this post since streaming user-provided data is a far edge case that few if any people will ever have to do.
Originally I had a similar problem to the one posted here where a model is being trained and the update should be stationary and formatted in Html. The following answer is for future reference or people trying to solve the same problem and need inspiration.
A good solution to achieve this is to use an EventSource in Javascript, as described here. This listener can be started using a context variable, such as from a form or other source. The listener is stopped by sending a stop command. A sleep command is used for visualization without doing any real work in this example. Lastly, Html formatting can be achieved using Javascript DOM-Manipulation.
Flask Application
import flask
import time
app = flask.Flask(__name__)
#app.route('/learn')
def learn():
def update():
yield 'data: Prepare for learning\n\n'
# Preapre model
time.sleep(1.0)
for i in range(1, 101):
# Perform update
time.sleep(0.1)
yield f'data: {i}%\n\n'
yield 'data: close\n\n'
return flask.Response(update(), mimetype='text/event-stream')
#app.route('/', methods=['GET', 'POST'])
def index():
train_model = False
if flask.request.method == 'POST':
if 'train_model' in list(flask.request.form):
train_model = True
return flask.render_template('index.html', train_model=train_model)
app.run(threaded=True)
HTML Template
<form action="/" method="post">
<input name="train_model" type="submit" value="Train Model" />
</form>
<p id="learn_output"></p>
{% if train_model %}
<script>
var target_output = document.getElementById("learn_output");
var learn_update = new EventSource("/learn");
learn_update.onmessage = function (e) {
if (e.data == "close") {
learn_update.close();
} else {
target_output.innerHTML = "Status: " + e.data;
}
};
</script>
{% endif %}
I'm totally new to all this python things, I've searched on my problem but withiout results, so I count on your help guys :)
I have a template file with button:
<button class="btn" value="{{invoice.number}}">Send</button>
In different file I have a class which runs function from another file:
class ReminderManual(webapp2.RequestHandler):
...
for inv in invoices:
is_send = reminder.send(inv)
And I'd like to:
run this class when the button is pushed
display is_send value
Any ideas how I can do that?
If you don't want to reload the complete page to get the result, you could to the following using JQuery and Ajax:
In HTML, you have
<button class="btn" value="{{invoice.number}}" id="myButton">Send</button>
and later in the file (before the closing </body> tag):
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
$('#myButton').on('click', function (e) {
var invoice_number = $('#myButton').val();
var data = { invoice_number:invoice_number };
var args = { dataType: "json", type:"POST", url:"/my_ajax_url/",
data:data, complete:ajax_call_complete };
$.ajax(args);
});
});
var ajax_call_complete = function(res, status) {
data = jQuery.parseJSON(res.responseText);
// use data as a json response object here and
// do something with the response data
}
</script>
In Javascript, the /my_ajax_url/ would be the URL on which your request handler on the server runs. It is called via Ajax, the parameters are provided as POST parameters (in the code example, the value of the button is send as parameter invoice_number).
I typically set up my server Ajax requests to return JSON, which is then handled by the callback method (in the example, ajax_call_complete). Here you can check for errors and indicating the result to the user by displaying a message, modifying certain HTML elements, etc.
If you want to submit the complete page instead of using Ajax, you should use the Django forms mechanism:
https://docs.djangoproject.com/en/1.6/topics/forms/
The button needs an onclick handler, so it knows what to do. The onclick handler is a javascript function that sends a new request via a url. So, your app needs to handle that url, and execute the Class when a request comes to the url.
With jquery, you could easily make the onclick handler process an Ajax request to the url, and respond back with the value of is_send. Still need a url handler in the app, which calls the class.
I see you added django as a tag. With django, you could make the button part of a form, and use django's form handling to execute the class, and push back the value of is_send.
I am trying to make a web application that accepts button clicks. The button clicked then sends a specific device, and operation code to the python application which then calls a irsend command using Lirc. This is based off of the source code/instructions from here:
https://github.com/slimjim777/web-irsend
http://randomtutor.blogspot.com/2013/01/web-based-ir-remote-on-raspberry-pi.html
The html for the button is simple and is in "Xbox.html"
<button onclick="clickedOp('Xbox', 'OnOff');"> Power </button>
This launches the js function:
<script>
function clickedOp(device_name, op) {
$.ajax({url:'/' + device_name + '/clicked/' + op});
}
I know that the function is firing on a click event because if i put an alert command in the clickedOp function the alert command runs
the python/flask app looks like this:
from flask import Flask
from flask import render_template
from flask import request, redirect, url_for
BASE_URL = ''
app = Flask(__name__)
#app.route("/")
def menu():
return render_template('menu.html')
#app.route("/<device_name>")
def remote(device_name):
if device_name == "Xbox":
return render_template('Xbox.html')
#app.route("/<device_name>/clicked/<op>")
def clicked(device_id=None, op=None):
return render_template('test.html')
if __name__ == "__main__":
app.run('0.0.0.0', port=80, debug=True)
All of the code up to the ajax request works. going to "/" loads the menu.html template and presents links to different devices, for instance
Xbox
will route to
"/<device_name>"
in the python program and "Xbox.html" is loaded.
Then the button loads and clicking it fires the "clickedOp(device_name, op)" function.
This is where it breaks down. Even though the ajax request routes to
"/<device_name>/clicked/<op>"
the "test.html" page is not loaded
This is the case even though the Flask debugger says that there was a successful GET request(it returns 200) to "/Xbox/clicked/OnOff" (filling in the variables for the example above)
so any ideas why test.html is not being loaded from the ajax request, when it seems that in the source code/tutorial I provided he uses the same ajax method?
You can simply do this with help of AJAX... Here is a example which calls a python function which prints hello without redirecting or refreshing the page.
In app.py put below code segment.
//rendering the HTML page which has the button
#app.route('/json')
def json():
return render_template('json.html')
//background process happening without any refreshing
#app.route('/background_process_test')
def background_process_test():
print "Hello"
return "nothing"
And your json.html page should look like below.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('a#test').on('click', function(e) {
e.preventDefault()
$.getJSON('/background_process_test',
function(data) {
console.log(data)
});
});
});
</script>
//button
<div class='container'>
<h3>Test</h3>
<form>
<a href=# id=test><button class='btn btn-default'>Test</button></a>
</form>
</div>
Here when you press the button Test simple in the console you can see "Hello" is displaying without any refreshing.
In the code the template will render and be returned to the jquery Ajax object, which will do nothing with it - it won't render it in the browser. Have you used your browser's developer tools to see if a response is received by the browser - again, if Flask logs HTTP 200 OK then I would imagine the request is being handled correctly. You should also be able to put print statements in your Flask method and see them logged too (I think).