Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8743601
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T11:42:28+00:00 2026-06-13T11:42:28+00:00

I have an existing Python application which servers a bunch of files via a

  • 0

I have an existing Python application which servers a bunch of files via a Bottle.py service.

Now I have to change the path the server should react to.
The obvious way would be to change the @route statement and prepend the new path to each route.

But I got the constraint that the old path should keep on working for a while.
As the server should react to the old requests, too, I would have to replicate each route-statement in order to have it once with the old and the new path.

So, straightforward it would be a change from:

@route('/somefile')
def doSomeStuff():

to:

@route('/somefile')
@route('/newpath/somefile')
def doSomeStuff():

But as there are a lot of routes and I don’t want to mess with all the code, I am searching for an elegant way to process the requests before the routing happens.

Is there any way to hook into the routing process?


My current approach is to serve a 301 to the browser, but I don’t like this solution as it increases the number of requests and changes the user’s URLs.

#Serve a 301 (hope the browsers remember it for a session at least)
@route('/newpath<path:path>')
def redirectNewToOld(path):
    if len(path) == 0:                         #Catch the lazy typers
        path = '/'
    redirect(path, code=301)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T11:42:29+00:00Added an answer on June 13, 2026 at 11:42 am

    Well, I wrote my own mod_rewrite for bottle.
    Code can also be found on GitHub

    Changes:

    (Based on fork created today, Oct 29, 2012)

    In class Bottle(object):
    @Lines 754ff, one addition:

    def _handle(self, environ):
        try:
            environ['bottle.app'] = self
    +       url_rewrite.apply(environ)    #Added mod_rewrite
            request.bind(environ)
            response.bind()
            route, args = self.router.match(environ)
            environ['route.handle'] = route
            environ['bottle.route'] = route
            environ['route.url_args'] = args
            return route.call(**args)
    

    Added at the bottom

    ###############################################################################
    # Nippey #### 29.10.2012 #### mod_rewrite #####################################
    ###############################################################################
    # This modification to bottly.py allows the application of rewrite rules to 
    # requests _before_ they are processed by the routing system
    
    class UrlRewriteException(BottleException):
        """ This is a base class for all rewrite related exceptions """
    
    class UrlRewrite():
        """ This class processes every URL before is is passed to the routing system 
        In case one of the included rewrite rules matches the URL, the URL will be modified.
        New rules can be added via the .addRule(str, str, bool) method.
        For each requested URL, the method apply will be called with the environ variable as parameter.
        """
        
        def __init__(self):
            """ Initiates the rules variable """
            print("UrlRewrite init.")
            self.rules = []
        
        def addRule(self, match, replace, final=False):
            """ Add a new rule.
            match:   Regular expression to search for. Can be a string or a compiled regular expression
            replace: Replacement string. May use backreferences.
            final:   If a rule with <final=True> matches the URL, the evaluation will be stopped afterwards
            """
            print("UrlRewrite addRule.")
            if type(match) is not str and type(replace) is not str:
                raise UrlRewriteException
            pattern = re.compile(match)
            self.rules.append({'pattern':pattern, 'repl':replace, 'final':bool(final)})
        
        def apply(self, environ):
            """ Test a URL for a match of one of the saved rules and rewrite it if required
            environ: Environmental variable created by bottle on each request. Contains the PATH_INFO 
                     information, modification will happen with the reference to this variable.
            returns: Returns true if a rewrite has been executed. Not used by the main program (yet)
                     Original path will still be available as PATH_INFO_ORIGINAL in the environ variable
            """
            print("UrlRewrite apply.")
            rewritten = False
            url = environ['PATH_INFO']
            for rule in self.rules:             #Try to alppy each of the rules
                (url, noSubs) = rule['pattern'].subn(rule['repl'], url)
                if noSubs > 0:
                    rewritten = True
                    if rule['final']:
                        break
            if rewritten:
                environ['PATH_INFO_ORIGINAL'] = environ['PATH_INFO']
                environ['PATH_INFO'] = url
                return True
            return False
    
        """ EXAMPLES:
        
        #Backreferences may be used by the replacement string
        from bottle import url_rewrite
        url_rewrite.addRule("^/he(l*)o", r"/by\1e", False)
        #Input:  "/hello/test_hello" 
        #Output: "/bye/test_hello"
        
        #All matching occurences will be replaced
        from bottle import url_rewrite
        url_rewrite.addRule("hello", "bye", False)
        #Input:  "/hello/test_hello" 
        #Output: "/bye/test_bye"
        
        #Rules will be applied in successive order
        from bottle import url_rewrite
        url_rewrite.addRule("hello", "hi", False)
        url_rewrite.addRule("hi", "bye", False)
        #Input:  "/hello/test_hello" 
        #Output: "/bye/test_bye"
        
        #Rules won't be re-applied from the start if one rule matches
        from bottle import url_rewrite
        url_rewrite.addRule("hi", "bye", False)
        url_rewrite.addRule("hello", "hi", False)
        #Input:  "/hello/test_hello" 
        #Output: "/hi/test_hi"
        
        #After applying a rule with <final> set to True, the evaluation will be finished
        from bottle import url_rewrite
        url_rewrite.addRule("hello", "hi", True)
        url_rewrite.addRule("hi", "bye", False)
        #Input:  "/hello/test_hello" 
        #Output: "/hi/test_hi"
        """
    # END class UrlRewrite
    
    url_rewrite = UrlRewrite()
    # END ## mod_rewrite ## Nippey
    

    I’ve sent a pull request, but here it is in case it won’t be pulled in. 😉

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an existing Python django Project running in Web Server. Now the client
I have to integrate my application with an existing (not modifiable) Python script which
I have made a batch script which runs a Python application. This batch script
I have an existing application which connects to a database. It is running under
I have an existing python application (limited deployment) that requires the ability to run
I have to create a python (twisted) application that accepts connections from clients via
I have an existing python script that, among other things checks a file against
I'm trying to create a TFTP in python over a existing UDP i have.
I have existing Linux shared object file (shared library) which has been stripped. I
I have existing code with their own makefiles which I want to load into

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.