Autore: Fabio Di Matteo
Ultima revisione: 21/10/2022 - 08:34
In certi casi puo' essere utile configurare le rotte in altri moduli Python. A tal fine è sicuramente meglio non usare i decoratori, ma il metodo route. Quello che ci interessa è nella funzione setup_routing() . Come mostrato nella guida ufficiale: Explicit routing configuration
... def setup_routing(app): app.route('/', ['GET', 'POST'], home) app.route('/get/<name>', ['GET', 'POST'], get) ...
Come possiamo vedere si esplicita rispettivamente rotta, metodi http, e la funzione di callback associata alla rotta. Di seguito uno script che mette a confronto alcuni modalita' per la definizione delle rotte.
myserver.py
from bottle import Bottle,static_file, route, run,os from routes import * app = Bottle() @app.route('/static/<filename>') def send_js(filename): return static_file(filename, root=os.path.dirname(os.path.realpath(__file__))+'/static/') @app.route('/static/sub/<filename>') def send_js(filename): return static_file(filename, root=os.path.dirname(os.path.realpath(__file__))+'/static/sub') @app.route('/hello') def hello(route='/hello'): return "Hello World!" def setup_routing(app): app.route('/', ['GET', 'POST'], home) #function home is in "routes.py" app.route('/get/<name>', ['GET', 'POST'], get) setup_routing(app) run(app, host='localhost', port=8080,reloader=True)
Qui invece il modulo routes.py che contiene le nostre rotte.
routes.py
def home(): r=''' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Prova</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <meta name="generator" content="Geany 1.24" /> </head> <body> <h1>Prova rotte esplicite</h1> </body> </html> ''' return r def get(name): r='<h1>'+name+'</h1>' s='<p>Paragrafe</p>' yield r yield s
Il nostro wiki installa solamente cookie tecnici necessari al funzionamento della piattaforma "Dokuwiki". Niente analitics, statistiche, tracciamenti o altro.