Bottle framework python - site cannot be reached - python

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.

Related

Slow requests to Bottle server

Let's run a simple Bottle server:
from bottle import route, run
#route('/')
def index():
return 'Hello'
if __name__ == "__main__":
run(port=80)
I wanted to test the speed of the requests with:
import requests
for i in range(10):
requests.get('http://localhost/?param=%i' % i)
and then I was about to use multithreading/parallel to also test what happens if 10 requests arrive at the same time, and not one after another... but I was stopped by something strange:
Animated console of the incoming requests
Each request seems to take precisely 1 second!
Why such a long time for each request on a Bottle server? (I know it's a micro-framework, but this is surely not the reason for 1-second to respond!)
PS: it's the same with urllib.request.urlopen. This code uses the default WSGIRefServer:
Bottle v0.12.18 server starting up (using WSGIRefServer())...
and was tested on Windows 7 + Python 3.7 64 bit.

Flask RuntimeError: working outside of application context

I want to run my Flask app with websocket. Everything seems to be ok as long as I am starting my joiner class (running as thread) and then want to register a call back funktion. This works ok with flask development server.
As I am not very good in Englisch I have problems to understand the context issues with Flask. Any help would be very much appreciated
#socketio.on('change_R8', namespace='/fl')
def change_Relay8(R8_stat):
if R8_stat == 'on':
#print("Relay 8 on")
ui.set_relay(8,1,0)
elif R8_stat == 'off':
#print("Relay 8 off")
ui.set_relay(8,0,0)
# Listen for SocketIO event that will change analog output
#socketio.on('change_ao', namespace='/fl')
def change_ao(ao_value):
#print("setze ao auf: ", ao_value)
ui.set_ao(ao_value)
#- call back function from UniPi_joiner_class----------------------------
def unipi_change(event, data):
#print("Webserver in: ",event,data)
emit_to_all_clients(event, data)
# main program ----------------------------------------------------------
if __name__ == "__main__":
log.text("Flask Web-Server gestartet")
print("Flask Web-Server gestartet")
joiner = unipi_joiner("10.0.0.52",0)
joiner.on_unipi_change(unipi_change)
socketio.run(app, host='127.0.0.1', use_reloader=False, debug=False)
log.text("Flask Web-Server beendet")
The joiner function delivers data from sensors in the format event, data(json) which I emit to my website with broadcast. The data comes from 2 different sources (time dependend) and are joined together in the joiner function using queues. This works ok with Flask development server. When I use eventlet then joiner.on_unipi_change(unipi_change) does not work and shows context error. I tested the server with data from within flask and it worked.
Question: would it be possible to deliver the sensor data through websocket to my Flask server and then from flask server to my web-site. This would be very interesting as I would have different Raspi 3 collecting data and sending it to my web server.
Regarding complete stack trace I need some guidelines (sorry Flask beginner)

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()

Restart Bottle app (programmatically)

How do I restart my Bottle app programmatically?
def error_handler(error):
if error.message == "connection already closed":
RESTART_BOTTLE_SERVER() # This will reacquire connection
You can stop the bottle app (thread) with the approach described in this answer.
I'll recommed you'll run your bottle server as a daemon in the background on your OS. You can than start and stop your server and use simple python code to kill the thread. BottleDaemon might do the job for you.
from bottledaemon import daemon_run
from bottle import route
#route("/hello")
def hello():
return "Hello World"
if __name__ == "__main__":
daemon_run()
The above application will launch in the background. This top-level script can be used to start/stop the background process easily:
jonathans-air:bottle-daemon jhood$ python bottledaemon/bottledaemon.py
usage: bottledaemon.py [-h] {start,stop}
Now you can use bottledaemon.py to start or stop or restart your application and call it from your main python file.

Python Bottle Tutorial: cannot get anything from the HelloWorld example

I just installed Bottle and add it into this directory: /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3
And when I was trying to run the HelloWorld example in http://bottlepy.org/docs/dev/tutorial.html#installation
and opened localhost:8080/hello
, there was nothing on the page.
>>> from bottle import route, run
>>>
>>> #route('/hello')
... def hello():
... return "Hello World!"
...
>>> run(host='localhost', port=8080, debug=True)
Bottle v0.13-dev server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.
I don't know why, please help!
I had the same problem. Replaced 'localhost' with '127.0.0.1' and got a 404 Not Found page.
However, the second example in the quickstart tutorial worked:
from bottle import Bottle, run
app = Bottle()
#app.route('/hello')
def hello():
return "Hello World!"
run(app, host='localhost', port=8080)
If its not working with localhost but it is working with 127.0.0.1, it means your network configuration is not really set up correctly.
If you are on linux or mac, check the /etc/hosts file and look for:
127.0.0.1 localhost
Windows has the same file at %SystemRoot%\system32\drivers\etc\hosts.
If the row is not there, add it.

Categories

Resources