Bottle not routing to index html file - python

I'm using Bottle for a Python project and I've set the project to run on the localhost:8080 (Windows 10 laptop). I’ve coded the project on VS Code, however, when I start the debugger on VS Code’s integrated terminal,I am presented with Error 500 on my browser (Google Chrome).
The project worked fine on a TA's machine, however on my laptop, bottle isn't routing to the index page, even when I explicitly had it import it from the static_file and adding the root file to the ‘run’ function. I tried running the example from Bottlepy.org, and even that isn’t working.
The only thing that has worked was:
from bottle import run, route
#route('/')
def hello():
return "If you're seeing this message, then bottle is working"
run(host='localhost', port=8080)
Again, I’ve ran:
from bottle import run, route, template
#route('/')
def hello():
return template("index.html")
run(host='localhost', port=8080)
and
from bottle import run, route, static_file
#route('/static/')
def hello():
return static_file('index.html', root='static')
run(host='localhost', port=8080)
Including the example from bottlepy.org, to which resulted in:
Error 500 Template 'index.html' not found.
Or
Error 500 ‘Template ‘/’ not found
I don’t believe it’s a PATH issue with Python, but it could be a JSON file issue with VS code. All the Python packages on my machine are updated and I’m out of ideas at the moment. Your suggestions/recommendations would be appreciated. Thank you.

Probably the issue is because the integrated shell executes the code in some other directory where the file 'index.html' is.
To help solve the issue, replace the file name with an absolute path, e.g.
#route('/static/')
def hello():
return static_file(os.path.join(os.path.dirname(__file__), 'index.html'), root='static')

Related

How set path of folder and files in Gunicorn. ( wsgi.py )

this my flask module main.py
import os
import Flask
import pandas as pd
app = Flask(__name__)
#app.route("/") # this route is working
def index():
return "this working"
#app.route("/data", methods=["POST"])
def get_data():
json = request.json
df = pd.DataFrame(json)
#here some other code that work on the data that are geting from folderspath as we have define below
if __name__=="__main__":
path=os.path.join(os.path.abspath(os.path.join('data')))
folder=os.path.join(path,'test')
app.run(debug=Flase,host="0.0.0.0")
if we just run the flask server it work and execute path statment but if we set for deployment purpose and using gunicorn the first route work. but when we send request to second route it give error of missing folder that are mention in paths. the below module (wsgi.py) is not getting those path how to set these path, that work in wsgi.py
my Gunicorn file wsgi.py
from main import app
if __name__=="__main__":
app.run()
i want wsgi.py to execute those path before app.run() i tried to put in those statement in wsgi before app.run() and imported dependences but still not working.
any help would be appreciated. thanks
You could try gunicorn's --pythonpath argument:
--pythonpath STRING A comma-separated list of directories to add to the Python path.

Error "no such file or directory" when using os.chdir in Flask

I can boot the app up with Flask, it loads and displays localhost viewing info, then immediately quits with the error:
can't open file 'server.py': [Errno 2] No such file or directory
This is normally what you get when there is no file of that name in the folder, but there definitely is in this case as it successfully loads it initially
EDIT: Adding code for server.py:
from flask import Flask, jsonify
from services.controller import Controller
app = Flask(__name__)
path = '/Users/bhouwens/some/path'
ctrl = Controller(path)
#app.route('/')
def home():
stats = {'path' : path}
return jsonify(stats)
#app.route('/task-runners')
def task_runners():
return jsonify({'task_runners': ctrl.task_runners})
if __name__ == '__main__':
app.run(debug=True)
As mentioned, os.chdir from within a Flask app doesn't seem possible without breaking the server.
In my case, I'm trying to read a file in another directory using another module, where the path to the directory is passed into the module as a parameter in this line:
ctrl = Controller(path)
I've discovered that the open function that Python makes available can open files in other directories, so I got around this issue by using
with open(path + '/file_to_open.txt', 'r') as file:
from the Controller module.
Hopefully this helps someone else who runs into the same problem.
Like you already discovered, you can't do chdir.
import os
from flask import Flask
app = Flask(__name__)
os.chdir('..')
app.run(debug=True)
When you execute this file, this is the output:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
/usr/bin/python: can't open file 'example.py': [Errno 2] No such file or directory
I don't know exactly what causes this issue, but if you check app.root_path after an os.chdir(), you would find it messed up, changing app.config['APPLICATION_ROOT'] doesn't solve this either, you need to change app.root_path attribute manually with the new directory path, you can do it while initializing the flask app like so app = Flask.flask(__name__, root_path=BASE_DIR), but you can also change it at any time while flask is running.
Without doing so, Flask does this:
if your app was at ~/one/two/three/app.py and you try to run the app from ~/one , doing an os.chdir() to os.path.dirname(os.path.abspath(__file__)) inside the app would result the app.root_path to be equal to '~/one/two/three/two/three', it basically doubles the portion of the path left between the location where you called the app and the app file itself, and if you were running the app from ~/one/two/three/four/five and doing os.chdir() to os.path.dirname(os.path.abspath(__file__)) inside the app this would result app.root_path to be equal to '~/one' ,i.e truncates the number of directories it's far from the app file starting from the app.py directory and going backwards.
os.path.dirname(os.path.abspath(__file__)) equals '~/one/two/three'
Weird bug :(

How can I get Bottle to restart on file change?

I'm really enjoying Bottle so far, but the fact that I have to CTRL+C out of the server and restart it every time I make a code change is a big hit on my productivity. I've thought about using Watchdog to keep track of files changing then restarting the server, but how can I do that when the bottle.run function is blocking.
Running the server from an external script that watches for file changes seems like a lot of work to set up. I'd think this was a universal issue for Bottle, CherryPy and etcetera developers.
Thanks for your solutions to the issue!
Check out from the tutorial a section entitled "Auto Reloading"
During development, you have to restart the server a lot to test your
recent changes. The auto reloader can do this for you. Every time you
edit a module file, the reloader restarts the server process and loads
the newest version of your code.
This gives the following example:
from bottle import run
run(reloader=True)
With
run(reloader=True)
there are situations where it does not reload like when the import is inside a def. To force a reload I used
subprocess.call(['touch', 'mainpgm.py'])
and it reloads fine in linux.
Use reloader=True in run(). Keep in mind that in windows this must be under if __name__ == "__main__": due to the way the multiprocessing module works.
from bottle import run
if __name__ == "__main__":
run(reloader=True)
These scripts should do what you are looking for.
AUTOLOAD.PY
import os
def cherche(dir):
FichList = [ f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir,f)) ]
return FichList
def read_file(file):
f = open(file,"r")
R=f.read()
f.close()
return R
def load_html(dir="pages"):
FL = cherche(dir)
R={}
for f in FL:
if f.split('.')[1]=="html":
BUFF = read_file(dir+"/"+f)
R[f.split('.')[0]] = BUFF
return R
MAIN.PY
# -*- coding: utf-8 -*-
#Version 1.0 00:37
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import datetime
import ast
from bottle import route, run, template, get, post, request, response, static_file, redirect
#AUTOLOAD by LAGVIDILO
import autoload
pages = autoload.load_html()
BUFF = ""
for key,i in pages.iteritems():
BUFF=BUFF+"#get('/"+key+"')\n"
BUFF=BUFF+"def "+key+"():\n"
BUFF=BUFF+" return "+pages[key]+"\n"
print "=====\n",BUFF,"\n====="
exec(BUFF)
run(host='localhost', port=8000, reloader=True)

CherryPy3 and IIS 6.0

I have a small Python web application using the Cherrypy framework. I am by no means an expert in web servers.
I got Cherrypy working with Apache using mod_python on our Ubuntu server. This time, however, I have to use Windows 2003 and IIS 6.0 to host my site.
The site runs perfectly as a stand alone server - I am just so lost when it comes to getting IIS running. I have spent the past day Googling and blindly trying any and everything to get this running.
I have all the various tools installed that websites have told me to (Python 2.6, CherrpyPy 3, ISAPI-WSGI, PyWin32) and have read all the documentation I can. This blog was the most helpful:
http://whatschrisdoing.com/blog/2008/07/10/turbogears-isapi-wsgi-iis/
But I am still lost as to what I need to run my site. I can't find any thorough examples or how-to's to even start with. I hope someone here can help!
Cheers.
I run CherryPy behind my IIS sites. There are several tricks to get it to work.
When running as the IIS Worker Process identity, you won't have the same permissions as you do when you run the site from your user process. Things will break. In particular, anything that wants to write to the file system will probably not work without some tweaking.
If you're using setuptools, you probably want to install your components with the -Z option (unzips all eggs).
Use win32traceutil to track down problems. Be sure that in your hook script that you're importing win32traceutil. Then, when you're attempting to access the web site, if anything goes wrong, make sure it gets printed to standard out, it'll get logged to the trace utility. Use 'python -m win32traceutil' to see the output from the trace.
It's important to understand the basic process to get an ISAPI application running. I suggest first getting a hello-world WSGI application running under ISAPI_WSGI. Here's an early version of a hook script I used to validate that I was getting CherryPy to work with my web server.
#!python
"""
Things to remember:
easy_install munges permissions on zip eggs.
anything that's installed in a user folder (i.e. setup develop) will probably not work.
There may still exist an issue with static files.
"""
import sys
import os
import isapi_wsgi
# change this to '/myapp' to have the site installed to only a virtual
# directory of the site.
site_root = '/'
if hasattr(sys, "isapidllhandle"):
import win32traceutil
appdir = os.path.dirname(__file__)
egg_cache = os.path.join(appdir, 'egg-tmp')
if not os.path.exists(egg_cache):
os.makedirs(egg_cache)
os.environ['PYTHON_EGG_CACHE'] = egg_cache
os.chdir(appdir)
import cherrypy
import traceback
class Root(object):
#cherrypy.expose
def index(self):
return 'Hai Werld'
def setup_application():
print "starting cherrypy application server"
#app_root = os.path.dirname(__file__)
#sys.path.append(app_root)
app = cherrypy.tree.mount(Root(), site_root)
print "successfully set up the application"
return app
def __ExtensionFactory__():
"The entry point for when the ISAPIDLL is triggered"
try:
# import the wsgi app creator
app = setup_application()
return isapi_wsgi.ISAPISimpleHandler(app)
except:
import traceback
traceback.print_exc()
f = open(os.path.join(appdir, 'critical error.txt'), 'w')
traceback.print_exc(file=f)
f.close()
def install_virtual_dir():
import isapi.install
params = isapi.install.ISAPIParameters()
# Setup the virtual directories - this is a list of directories our
# extension uses - in this case only 1.
# Each extension has a "script map" - this is the mapping of ISAPI
# extensions.
sm = [
isapi.install.ScriptMapParams(Extension="*", Flags=0)
]
vd = isapi.install.VirtualDirParameters(
Server="CherryPy Web Server",
Name=site_root,
Description = "CherryPy Application",
ScriptMaps = sm,
ScriptMapUpdate = "end",
)
params.VirtualDirs = [vd]
isapi.install.HandleCommandLine(params)
if __name__=='__main__':
# If run from the command-line, install ourselves.
install_virtual_dir()
This script does several things. It (a) acts as the installer, installing itself into IIS [install_virtual_dir], (b) contains the entry point when IIS loads the DLL [__ExtensionFactory__], and (c) it creates the CherryPy WSGI instance consumed by the ISAPI handler [setup_application].
If you place this in your \inetpub\cherrypy directory and run it, it will attempt to install itself to the root of your IIS web site named "CherryPy Web Server".
You're also welcome to take a look at my production web site code, which has refactored all of this into different modules.
OK, I got it working. Thanks to Jason and all his help. I needed to call
cherrypy.config.update({
'tools.sessions.on': True
})
return cherrypy.tree.mount(Root(), '/', config=path_to_config)
I had this in the config file under [/] but for some reason it did not like that. Now I can get my web app up and running - then I think I will try and work out why it needs that config update and doesn't like the config file I have...

Django with Passenger

I'm trying to get a trivial Django project working with Passenger on Dreamhost, following the instructions here
I've set up the directories exactly as in that tutorial, and ensured that django is on my PYTHONPATH (I can run python and type 'import django' without any errors). However, when I try to access the url in a browser, I get the following message: "An error occurred importing your passenger_wsgi.py". Here is the contents of my passenger_wsgi.py file:
import sys, os
sys.path.append("/path/to/web/root/") # I used the actual path in my file
os.environ['DJANGO_SETTINGS_MODULE'] = ‘myproject.settings’
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
However, when I put the following simple "Hello World" application in passenger_wsgi.py, it works as intended, suggesting Passenger is set up correctly:
def application(environ, start_response):
write = start_response('200 OK', [('Content-type', 'text/plain')])
return ["Hello, world!"]
What am I missing? Seems like some config issue.
Are those fancy quotation marks also in your code?
os.environ['DJANGO_SETTINGS_MODULE'] = ‘myproject.settings’
^ ^
If so, start by fixing them, as they cause a syntax error.

Categories