How to automate browser refresh when developing an Flask app with Python? - python

I've started learning Flask to develop web applications. What I am realy missing is an automatic Browser refresh after any code change (including static files, templates, etc.). This seems to be a standard feature in almost any Javascript framework. Frontend people have several terms for that: auto reload / refresh, hot reload / refresh (hotreload), live reload / refresh (livereload), ...
Here on Stackoverflow most similar questions are related to the auto-reload of the Flask server (--> https://stackoverflow.com/search?q=flask+auto+reload).
J just want a simple browser refresh.
I googled and tried several things - with no luck:
https://github.com/lepture/python-livereload
https://gist.github.com/amontalenti/8922609
How can I have a smooth developing experience with Flask without having to hit the F5 key 1000 times a day in a browser just to see the results of my changes?
I think the answer is somewhere near to python-livereload from the link above.
So I guess an alternative title of my question could be:
Does somebody have a working example of Flask + python-livereload?
I am to dumb to get it from their documentation :)
EDIT: for the sake of completenes here is the Flask app I am using.
# filename: main.py
from flask import Flask, render_template
from livereload import Server
app = Flask(__name__)
#app.route('/')
def index():
return "INDEX"
#app.route('/bart')
def use_jinja():
return render_template('basic.html')
if __name__ == '__main__':
server = Server(app.wsgi_app)
server.serve(port=5555)
I start the app with
python main.py

This is an interesting question you've raised so I built a quick and dirty Flask application which utilizes the livereload library. Listed below are the key steps for getting this to work:
Download and install the livereload library:
pip install livereload
Within your main file which starts up your flask application, run.py in my particular case, wrap the flask application with the Server class provided by livereload.
For example, my run.py file looks like the following:
from app import app
from livereload import Server
if __name__ == '__main__':
server = Server(app.wsgi_app)
server.serve()
Start your server again:
python run.py
Navigate to localhost in the browser and your code changes will be auto-refreshed. For me I took the default port of 5500 provided by livereload so my url looks like the following: http://localhost:5500/.
With those steps you should now be able to take advantage of auto-reloads for your python development, similar to what webpack provides for most frontend frameworks.
For completeness the codebase can be found here
Hopefully that helps!

If on Windows:
set FLASK_ENV=development

I use Guard::LiveReload becose solution with python-livereload don't work correct with debug (for me).
In first terminal emulator:
$ cd my-flask-project
$ flask run
* Serving Flask app 'webface' (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:54321/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
In secondu terminal emulator:
$ cd my-flask-project
$ guard init livereload
Now I edit Guardfile and add/edit watch. Like this:
watch(%r{.+\.py})
watch(%r{webface/.+\.(css|js|html(\.j2)?)})
again in second terminal emulator:
$ guard
17:29:25 - INFO - LiveReload is waiting for a browser to connect.
17:29:25 - INFO - Guard is now watching at '/home/marek/my-flask-project'
[1] guard(main)> 17:29:29 - INFO - Browser connected.
17:29:31 - INFO - Reloading browser: webface/templates/base.html.j2
17:45:41 - INFO - Reloading browser: webface/templates/base.html.j2
[1] guard(main)>
Maybe need to click livereload extention button in browser to connect browser to guard.

Related

wxPython and Flask integration

I am trying to integrate wxPython and Flask into a single application, but I am not sure how to get them to work together as they both want exclusive use of the main thread.
I am calling the application with:
export FLASK_APP=keypad_controller
python3 -m flask run -p 2020 -h 0.0.0.0 --eager-loading --no-reload
The main code block using Flask is:
from flask import Flask
def create_app(test_config=None):
app = Flask(__name__)
return app
I am not sure how to integrate wxPython (below) into the above code, how do I run flask?
wx_app = wx.App()
main_window = MainWindow(config)
main_window.Show()
wx_app.MainLoop()
Start Flask (app.run()) in a separate thread.
Not that if you want app.run(debug=True), you must also pass use_reloader=False, because things will go off the rails quickly if Flask decides that it wants needs to reload anything from other than the main thread.

Python : unable to connect to localhost using flask app

I'm a beginner in Flask and we run a simple web app at univeristy where you connect to a localhost and you get a simple Hello World text . However when I try to run the app after the flask app loads with the code below :
* Serving Flask app "my_app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
Then i press CTRL +C to quit and then I try to run my app to connect to the webpage using the command
curl localhost:5000/
and I get the error message :
curl : Prefix of URI not recognised.
At line:1 char:1
+ curl localhost:5000/
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented: (:) [Invoke-WebRequest], NotSupportedException
+ FullyQualifiedErrorId :
WebCmdletIEDomNotSupportedException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
I have tried changing the command to curl.exe localhost:500/ but the result is the same . I have my code below for the web app :
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
#app.route('/<name>')
def hello_name(name):
return f'Hello {name}!\n'
if __name__ == '__main__':
app.run(host='0.0.0.0')
I would appreciate your help with guiding me to run my app . Thank you in advance.
EDIT: the problem was simply that I would terminate my app without opening a shell to connect to the localhost . Thank you for your responses very much
You said it yourself:
Then i press CTRL +C to quit
That is when you terminate the server, so it would just cease to exist, and obviously not accept any incoming connections.
You need to leave the process running until you want to terminate it. So, go to another terminal, without first terminating the server, and then you will see curl manages to retrieve the page.
If I'm understanding your issue correctly it's that you can't get back your website's response from the server.
This makes complete sense. You are running your app, then stopping it when you hit 'CTRL + C'.
Then you are trying to connect to the server, which you've already stopped. You need to leave the server running (don't hit 'CTRL + C') then use a web browser and type in http://0.0.0.0:5000/ and you should see your 'hello world' back.
Alternatively, you can open a separate tab in terminal/command prompt and use the curl command.
You are terminate the app. Instead press CTRL+T to open a new tab.

Why is Python Flask application rendering only after a second restart?

I am new to Python Flask. I want my Python application to only start the web server (and the Flask application parts) if the user chooses to do so, at runtime. Otherwise, the application should simply run a program on the terminal. I have used the following code.
User selecting option '1' works fine - the program runs to completion with no web server starting.
However, if the user chooses option '2' below - the whole application re-starts, asking for the same user input again. The html page also does not render at this point. Only if the user chooses option '2' now a second time, do we get the local web server working and the html webpage localhost:5000/index renders as expected.
(User selecting option '2', and then upon restart selects option '1' - ends as the terminal program and webpage never renders)
How can user select to option '2' just once and make the web app component run? Why is this app.run() being executed twice to get the web application running?
import flask
app = flask.Flask(__name__)
app.config["DEBUG"]= True
#app.route('/index', methods=['GET'])
def home():
print("came home!..")
return flask.render_template('index.html')
print('hello there')
a = input("do you want 1. Normal app or 2.Web app? (1/2): ")
if a=='2':
#do the flask thing
print("Woo! the next line should start off the web server too .. but does it?")
b = input("press enter to continue .. and then check with web browser")
app.run()
else:
print("Well done. This should end the terminal program cleanly.")
b = input("press enter to continue .. and end.")
print(".. AND we are out of the main block")
The results shown below are from the terminal where the user is forced to selection option '2' twice to get server started .. Webpage renders fine on browser. on pressing Ctrl+C we exit the application (twice!)
hello there
do you want 1. Normal app or 2.Web app? (1/2): 2
Woo! the next line should start off the web server too .. but does it?
press enter to continue .. and then check with web browser
* Serving Flask app "try" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
hello there
do you want 1. Normal app or 2.Web app? (1/2): 2
Woo! the next line should start off the web server too .. but does it?
press enter to continue .. and then check with web browser
* Debugger is active!
* Debugger PIN: 132-339-530
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
came home!..
127.0.0.1 - - [26/Apr/2020 18:12:38] "GET /index HTTP/1.1" 200 -
.. AND we are out of the main block
.. AND we are out of the main block
Easiest solution would be to set the debug to false. Or use any of the solutions here: Why does running the Flask dev server run itself twice?

Deploying Watson Visual recognition app fails

I created some custom classifiers locally and then i try to deploy on bluemix an app that classifies an image based on the classifiers i made.
When I try to deploy it, it failes to start.
import os
import json
from os.path import join, dirname
from os import environ
from watson_developer_cloud import VisualRecognitionV3
import time
start_time = time.time()
visual_recognition = VisualRecognitionV3(VisualRecognitionV3.latest_version, api_key='*************')
with open(join(dirname(__file__), './test170.jpg'), 'rb') as image_file:
print(json.dumps(visual_recognition.classify(images_file=image_file,threshold=0, classifier_ids=['Angle_971786581']), indent=2))
print("--- %s seconds ---" % (time.time() - start_time))
Even if I try to deploy a simple print , it failes to deploy, but the starter app i get from bluemix, or a Flask tutorial (https://www.ibm.com/blogs/bluemix/2015/03/simple-hello-world-python-app-using-flask/) i found online deploy just fine.
I'm very new to web programming and using cloud services so i'm totally lost.
Thank you.
Bluemix is expecting your python application to serve on a port. If your application isn't serving some kind of response on the port, it assumes the application failed to start.
# On Bluemix, get the port number from the environment variable PORT
# When running this app on the local machine, default the port to 8080
port = int(os.getenv('PORT', 8080))
#app.route('/')
def hello_world():
return 'Hello World! I am running on port ' + str(port)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=port)
It looks like you're writing your code to just execute once and stop. Instead, make it do the work when someone hits your URL, like shown in the hello_world() function above.
Think about what you want to happen when someone goes to YOUR_APP_NAME.mybluemix.net
If you do not want your application to be a WEB application, but instead just execute once (a background worker application), then use the --no-route option at the end of your cf push command. Then, look at the logs using cf logs appname --recent to see the output of your application
https://console.ng.bluemix.net/docs/manageapps/depapps.html#deployingapps
The main problem was watson-developer-cloud module, giving me an error that it could not be found.
I downgraded to python version 2.7.12, installing it for all users.
Modified runtime.exe and requirments.txt (requirments.txt possible not needed)
Staged with Diego, using no-route and set-health-check APP_NAME none command.
Those fixed the problem, but i still get an exit status 0.
when you deploy an app in bluemix,you should have a requirements.txt which include services you used in your app.
so ,you should checkout your requirements.txt,maybe you lost
watson_developer_cloud
and then, the requirements.txt likes this:
Flask==0.10.1
watson_developer_cloud

Replacing flask internal web server with Apache

I have written a single user application that currently works with Flask internal web server. It does not seem to be very robust and it crashes with all sorts of socket errors as soon as a page takes a long time to load and the user navigates elsewhere while waiting. So I thought to replace it with Apache.
The problem is, my current code is a single program that first launches about ten threads to do stuff, for example set up ssh tunnels to remote servers and zmq connections to communicate with a database located there. Finally it enters run() loop to start the internal server.
I followed all sorts of instructions and managed to get Apache service the initial page. However, everything goes wrong as I now don't have any worker threads available, nor any globally initialised classes, and none of my global variables holding interfaces to communicate with these threads do not exist.
Obviously I am not a web developer.
How badly "wrong" my current code is? Is there any way to make that work with Apache with a reasonable amount of work? Can I have Apache just replace the run() part and have a running application, with which Apache communicates? My current app in a very simplified form (without data processing threads) is something like this:
comm=None
app = Flask(__name__)
class CommsHandler(object):
__init__(self):
*Init communication links to external servers and databases*
def request_data(self, request):
*Use initialised links to request something*
return result
#app.route("/", methods=["GET"]):
def mainpage():
return render_template("main.html")
#app.route("/foo", methods=["GET"]):
def foo():
a=comm.request_data("xyzzy")
return render_template("foo.html", data=a)
comm = CommsHandler()
app.run()
Or have I done this completely wrong? Now when I remove app.run and just import app class to wsgi script, I do get a response from the main page as it does not need reference to global variable comm.
/foo does not work, as "comm" is an uninitialised variable. And I can see why, of course. I just never thought this would need to be exported to Apache or any other web server.
So the question is, can I launch this application somehow in a rc script at boot, set up its communication links and everyhing, and have Apache/wsgi just call function of the running application instead of launching a new one?
Hannu
This is the simple app with flask run on internal server:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
To run it on apache server Check out fastCGI doc :
from flup.server.fcgi import WSGIServer
from yourapplication import app
if __name__ == '__main__':
WSGIServer(app).run()

Categories

Resources