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.
Related
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?
I'm trying to make a Raspberry Pi 3 REST API that provides temperature and humidity with DHT22. The whole code:
from flask import Flask, jsonify, request
from sds011 import SDS011
from adafruit_dht import DHT22
import board
import os
import time
app = Flask(__name__)
dht = DHT22(board.D4)
def get_dht_data():
while True:
try:
temperature, humidity = dht.temperature, dht.humidity
print(temperature, humidity)
if temperature is not None and humidity is not None:
return temperature, humidity
else:
raise
except:
time.sleep(0.5)
#app.route('/', methods=['GET'])
def status():
temperature, humidity = get_dht_data()
return jsonify({
'temperature': temperature,
'humidity': humidity
})
if __name__ == '__main__':
app.run(debug=True)
I used https://github.com/adafruit/Adafruit_CircuitPython_DHT
However, when I start server, it shows message
'Unable to set line 4 to input'
and temperature and humidity is always None. If I don't run flask app but just DHT code, it works.
Short answer
Remove debug=True and enjoy. :-)
What was going on?
This problem drove me nuts but I think I found the root cause! In my case, I was encapsulating the DHT22 object in another object, like so:
...
class DHT22Custom:
def __init__(self):
print("**** BUILDING by {0}!".format(threading.currentThread().getName()))
self.dht_device = adafruit_dht.DHT22(board.D17)
...
My main.py looked like:
import RPi.GPIO as GPIO
from sensor.config.app_config import create_app
if __name__ == '__main__':
app = create_app() # builds DHT22Custom inside
app.run(debug=True)
print("Cleaning up GPIO before exiting...")
GPIO.cleanup()
And look what an interesting output I got:
root#05600e5:/app# python -m sensor.main
**** BUILDING by MainThread!
* Serving Flask app "FlaskWS" (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
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
**** BUILDING by MainThread!
Unable to set line 17 to input
The MainThread was initializing my object twice! How was that? Well, if you look at the documentation of Flask's run(), you'll see the following:
If the :attr:`debug` flag is set the server will automatically reload
for code changes and show a debugger in case an exception happened.
So, it seems that Flask just relaunches the application or something like this. Not clear to me, to be honest. But well, if you just remove debug, you'll see something like:
root#05600e5:/app# python -m sensor.main
**** BUILDING by MainThread!
* Serving Flask app "FlaskWS" (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://127.0.0.1:5000/ (Press CTRL+C to quit)
I hope this helps. Happy coding!
Locating the process libgpiod_pulsein and killing it resolved the issue.
In your terminal, search for the process ID:
pgrep libgpiod_pulsein
and
kill <PID> (found from above - you might have more than one running)
I was experiencing the exact same thing with the DHT11. In my situation I had to kill the process: libgpiod_pulsein.
Worked on the first try when on fresh boot, but then subsequent executions would fail. Changing the GPIO I was using and running the program had the same effect, worked the first time and subsequent attempts would fail with example:
Unable to set line 4 to input
Timed out waiting for PulseIn message
Timed out waiting for PulseIn message
...
Blockquote
In my case, pgrep libgpiod_pulsein returned nothing. But changing pin to D18 solved the issue. Seems to me like something else is blocking GPIO4, but no idea what. – Slav Apr 4 at 18:03
thanks,with the pin 18 its ok
but it is strange:
The pin 4, only run it: (version deprecated of adafruit)> runing before:
sudo modprobe w1-gpio
sudo modprobe w1-therm
#!/usr/bin/python
import sys
import Adafruit_DHT
while True:
humidity, temperature = Adafruit_DHT.read_retry(11, 4)
print 'Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(temperature, humidity)
I am facing the same issue with you meaning that using python, flask and cyrcuitpython adafruit_sht library I can only run once for every pin on rpi 4 the code. Finally the solution was in front of me and was the line dhtDevice.exit()
So before ending my code and return to the main class I run the command dhtDevice.exit()
so the next time I run the same code evrything works fine!
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.
I am new to Python programming and the Bottle framework as well. I wrote up a basic hello, world program which looks like this:
from bottle import run, route
#route('/')
def index():
return '<h1>Hello, World</h1>'
if __name__ == '__main__':
run(host='localhost', port=8080, debug=True)
The output of this code is
Bottle v0.12.13 server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.
But when I enter http://localhost:8080/ in a browser, i get the error- "The site cannot be reached"
Am I missing some configuration. I am learning using this youtube video
Make sure that no other programs are accessing the server. Are you using IPyhton as well? Just a sanity check nothing fancy.
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