Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bottlepy: template not found

Tags:

python

bottle

I have server running on apache. I use bottle.py. When I'm going to xxx/getbio, SOMETIMES it returns :

Error: 500 Internal Server Error: Template 'bio' not found.

This error occurs not all time: if I restart apache, it's normalizing for several hours, but happens again. Here is code fragment :

@route('/getbio')
def getBio():
    return template('bio')

Here is file structure :

xxx/
├── views/
│   ├── bio.tpl
└── index.py

And I didin't missed following lines of code:

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
sys.path.append('views')
os.chdir(os.path.dirname(os.path.abspath(__file__)))

Please help me, because I don't have idea how to fix this bug

like image 963
user2594650 Avatar asked Dec 16 '22 07:12

user2594650


2 Answers

Add your template location to TEMPLATE_DIR, not to sys.path:

bottle.TEMPLATE_PATH.insert(0, 'views')

You may find that it's more robust to use the absolute path:

bottle.TEMPLATE_PATH.insert(0, '/path/to/xxx/views')
like image 153
ron rothman Avatar answered Jan 03 '23 14:01

ron rothman


By default Bottle adds the views folder to the template path for template files. However, at least on Windows, it looks for the views folder relative to where the python script was invoked from (ie. the current working directory) and not relative to where the app entry point .py file is found.

Therefore if your folder structure looks like this:

xxx/
├── views/
│   ├── bio.tpl
└── index.py

and index.py is your Bottle app entry point, you would need to launch index.py with xxx as the current working directory.

Hard-coding the path to the templates folder should work, but is not a portable solution.

You can however specify the absolute path to the templates folder in a portable way by determining it at runtime with code like this:

import os     
abs_app_dir_path = os.path.dirname(os.path.realpath(__file__))
abs_views_path = os.path.join(abs_app_dir_path, 'views')
bottle.TEMPLATE_PATH.insert(0, abs_views_path )

Just change the line performing the os.path.join call to correctly construct the abs_views_path relative to your file.

This way, you can simply move the code from machine to machine, and run it from any working directory, and as long as your views folder location is always in the correct place relative to your app it will be found.

like image 39
Matt Coubrough Avatar answered Jan 03 '23 12:01

Matt Coubrough