I've read the Bottle Documentation but I can't find the example of how to use Bottle with multiple files. Below is the way I did and it's working but I'm not sure whether this is the proper way to go (I saw merge()
and mount()
in API but not sure if they are related to this). Please give me the comments.
all.py (This is the main file for running)
#! /usr/bin/python
from bottle import route, run
import hello1
import hello2 # if I have 10 files, it will be 10 imports
run(host='localhost', port=8080, debug=True)
hello1.py
#! /usr/bin/python
from bottle import route, run
@route('/hello1')
def hello1():
return "Hello world no.1"
hello2.py
#! /usr/bin/python
from bottle import route, run
@route('/hello2')
def hello2():
return "Hello world no.2"
I've wanted to use a single bottle server to serve a suite of micro-applications and for a decent separation of concerns, have wanted to do what you've been looking for.
Here's how I resolved my task:
rootApp.py (Your main file)
from bottle import Bottle
from clientApp import clientApp
rootApp = Bottle()
@rootApp.route('/')
def rootIndex():
return 'Application Suite Home Page'
if __name__ == '__main__':
rootApp.merge(clientApp)
rootApp.run(debug=True)
clientApp.py (The new app needing to be merged into the suite)
from bottle import Bottle
clientApp = Bottle()
@clientApp.route('/clientApp')
def clientAppIndex():
return 'Client App HomePage'
I am not sure if this is the best way to do it, but it seems to work without complaints and saves the hassle of having to share ports between applications that could otherwise have mutual knowledge. The approach really stems out of a design preference but I'd be grateful if someone could demonstrate how/if the AppStack could be used to get the same result.
If you split your code into 10 Python modules, you’re going to do 10 imports. You can iterate with __import__
:
for i in range(1, 11):
__import__('hello%d' % i)
but this doesn’t strike me as a good idea. Why would you need 10 modules with a micro-framework?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With