Automatic page refresh stops working (Flask App) - python

I created a Flask app that displays the latest pictures on an HTML website. The website is set to automatically refresh every 10 seconds using a meta tag
<meta http-equiv="refresh" content="10" />
it all works great when the server and website run on a local PC, but when I run the app over LAN, the page refreshes correctly a few times, but sooner or later it stops. The webpage itself looks like it is loading (spinning wheel), but no new requests are registered in the flask app. The only way to start refreshing it again is by manual refresh on the client-side or by restarting the flask app on the server-side.
What could be the problem that causes this and how to mitigate it? Can it be caused by a firewall that doesn't like the constant refreshes? Are there any alternatives to said meta tag? I don't want to have any difficult set-up on the client-side like job scheduling etc (unless it is the only solution).

You could just use javascript for this. Just put the code below in your html file somewhere or in a seperate javascript file named script.js and link that javascript file like <script src="/Path/To/File.js"></script>
<script>
window.setTimeout(function () {
window.location.reload();
}, 30000);
</script>

Related

Rasa, Botfront and heroku: Frontend doesn't work after deployment

I have deployed my rasa chatbot online by creating a docker image, pushing and releasing it to Heroku. Now my bot is live on Heroku. I would like to communicate with this bot, through my website. I have added my bot url to Botfront widget's socketurl. However, when I send a message, I do not get any response. Does anyone know what I'm missing or doing wrong?
The content of my script is:
<!-- chatbot -->
<script>
!(function () {
let e = document.createElement("script"),
t = document.head || document.getElementsByTagName("head")[0];
(e.src = "{% static 'js/chatbot.js' %}"),
(e.async = !0),
(e.onload = () => {
window.WebChat.default(
{
customData: { language: "en" },
socketUrl: "https://app-name.herokuapp.com",//not real bot url
// add other props here
// initPayload: "/greet",
title: "Let's talk, we are online.",
subtitle: "Say hi to get started.",
},
null
);
}),
t.insertBefore(e, t.firstChild);
})();
</script>
If someone can help me, I would really appreciate it, been stuck on this for days!
Did you add the SocketIO configuration? You should add the following in your credentials.yml file (it will be inside your Docket container, not in git repository).
socketio:
user_message_evt: user_uttered
bot_message_evt: bot_uttered
session_persistence: true # or false
You can see more details in RASA documentation for web channel.
I see, since Heroku is using python as server end it might be not able to load index.html or any HTML code. try hosting your HTML code to a different server. I would suggest using Github's profile hosting.
I have also hosted my HTML page on GitHub and rasa server on a cloud server.
check it out here: https://horizon733.github.io/
Also, check out this documentation by Heroku while using the python server.
I hope this helps, feel free to ask any doubts.

Getting Livereload + Flask to trigger hard refresh

After exposure to Svelte/Rollup in the JavaScript world I was impressed that it could refresh the browser automatically when changes were made to the source code. Seeking a similar behaviour in Python I found the package livereload that supports integration with Flask (pretty sure using the same tech). I want the result of the refresh to reflect ALL changes to the source code.
I am using WSL with livereload v2.5.1 and viewing via Chrome. I can successfully get the page to refresh on a detected source code change but the refresh doesn't re-download the new files and just displays the cached files. The page does refresh but I need to hit Ctrl + click refresh to see the actual changes. Using developer mode and turning off caching works as desired. Using Svelte/Rollup doesn't require disabling caching to see source changes.
Most of my changes are to *.css or *.js files served from the 'static' folder in a standard Flask project template and rendered using the 'render_template' function of Flask.
I'm launching my Flask server as follows:
app = create_app()
app.debug = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
server = Server(app.wsgi_app)
server.watch(filepath='static/*', ignore=lambda *_: False)
server.serve(liveport=35729, host='127.0.0.1', port=80)
I would like to not have to disable the cache so that the refresh triggered by livereload actually reflects the changes in the source. Is there a setting in Flask or livereload I can use to achieve this or is this a feature request for the livereload package?
Related Question:
How to automate browser refresh when developing an Flask app with Python?
UPDATE EDIT:
Further testing has shown that this is specifically an issue with Chrome, with Firefox it works as expected out of the box. Digging into the underlying livereload.js library it seems there is a parameter of 'isChromeExtension' which I have tried to force set to True but had no effect.
I came across the same issue and here is what I did to solve the issue.
As you mentioned this is a browser caching problem. So we want invalidate the cached css/js files. We can achieve this by setting a version on the static file. We want the version to change each time you make changes to the css file. What I did feels a bit hacky but you'll get the idea.
Here is what I have for my html template
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World</title>
<link href="{{ url_for('static', filename='main.css', version=time)}}" rel="stylesheet" type="text/css" />
</head>
<body>
<h1 class="hello-color">
{{ message }}
</h1>
</body>
</html>
You can see version=time I am passing the template the current time with the following.
from flask import Flask, render_template
from time import time
app = Flask(__name__)
#app.route("/")
def hello():
return render_template('hello.html', message="Hello World!", time=time())
from time import time and
time=time()
And finally my main python file
from app import app
from livereload import Server
if __name__ == '__main__':
server = Server(app.wsgi_app)
server.serve(port=2200, host='0.0.0.0')
Hopefully this helps you or anyone else running to this issue.

how run a python script with a html button?

i just would like to run a python script by clicking on a html button.
python script is reallly simple. when you run it, it just add a "name" and "age" data in my database.
import sqlite3
conn = sqlite3.connect('bdaremplir.sqlite')
cur = conn.cursor()
"""cur.execute('DROP TABLE IF EXISTS latable')
cur.execute('CREATE TABLE latable (noms TEXT, age INTEGER)')"""
nom = 'TheName'
age = 100
cur.execute('''INSERT OR IGNORE INTO latable (noms, age) VALUES ( ?, ? )''', (nom, age))
conn.commit()
and the basics of html
<!DOCTYPE html>
<html>
<head>
<title>visualisateur</title>
</head>
<body>
<button></button>
</body>
</html>
now from here i don't at all what i can do.
if anyone can help... thank you.
Web browsers only know how to run JavaScript, not Python, so unless you really want to run Python in the browser1, you have to learn about the client-server architecture of the web.
Basically, you have to
make your Python program available as a web server, and
send a request to that server when your HTML button is clicked.
Running a web server
There are many ways to implement a web server in Python. When you get to writing a proper application, you'll probably want to use a library like Flask, Django, or others. But to get started quickly, you can use the built-in Python HTTP server with CGI:
Create a Python script named handle_request.py with the following content:
#!/usr/bin/env python3
print("Content-Type: text/plain\n")
print("hello world")
and put it into the cgi-bin directory next to your HTML file and make sure you can run it by typing "handle_request.py" into the console;
2. Run the built-in HTTP server:
python3 -m http.server --bind localhost --cgi 8000
Open http://localhost:8000 in your browser to access the server.
You should see the listing of the directory, including your HTML file and the cgi-bin directory. Clicking the HTML file should display it in the browser (with a URL like http://localhost:8000/test.html), and opening http://localhost:8000/cgi-bin/handle_request.py will run the script we've created and display its response as a web page. You can add your code to the script, and it will run whenever the browser accesses its URL.
Making a request from your web page
Now the question is how to make the browser access the http://localhost:8000/cgi-bin/handle_request.py URL when a button on your page is clicked.
To do that you need to invoke the API for making requests from JavaScript. There are different ways to do that (e.g. XMLHttpRequest or jQuery.ajax()), but a simple way that works in the modern web browsers is fetch():
<button id="mybutton"></button>
<script>
document.getElementById("mybutton").onclick = async function() {
let response = await fetch("http://localhost:8000/cgi-bin/handle_request.py");
let text = await response.text();
alert(text);
}
</script>
Now when you click the button, the browser will make a request to the specified URL (thus running your script), but instead of displaying the results as a web page in a tab, it will be made available to your JavaScript.
notes
1 ...which you probably don't at this point, but if you do, see the pointers by Michael Bianconi.

Error in displaying web pages using Flask

I used flask to make a web portal for the users to register but when I run the html file using a local host, the display looks like below:
This html file is not actually an html file but rather a Jinja template. Thus, you need it to be served via your flask app render_template function. So it makes not sense to open this page via browser as html.

pyramid: get application absolute url

Is there any way to get pyramid absolute application url in main() function?
I want to add it into global settings, so it could be called every where(in templates and js files).
In pyramid documents there is some functions would help, but all of them need a request object and must call in a view.
Thanks.
Pyramid (like most WSGI applications) can be mounted on any domain and url prefix. Thus the application itself doesn't actually know what urls it is responsible for unless you code that into your application specifically (an INI setting, for example).
This is why request.application_url exists... because the application_url could be different per request based on how many different domains and url prefixes you have that are proxying requests to your application.
I just get the full route for my index route, 'home' in my case:
I set this in my main wrapper mako template so that all of my JS calls can reference it to build a proper path for ajax calls/etc
<script type="text/javascript" charset="utf-8">
<%
app_url = request.route_url('home').rstrip('/')
%>
APP_URL = '${app_url}';
</script>

Categories

Resources