Search code examples
pythonpyramid

Creating a dynamic redirect by using any of Flask, Pyramid, or Bottle?


I want to create a webapp that dynamically redirects to a URL, based on address that user typed. When a user visit my site by a address like this:

http://mydomain1.com/a1b2c3d4

I want redirect this user to URL:

http://mydomain2.com/register.php?id=a1b2c3d4&from=mydomain1.com

Solution

  • Yay, I love a good fight!

    from pyramid.config import Configurator
    from pyramid.httpexceptions import HTTPFound
    from paste.httpserver import serve
    
    config = Configurator()
    
    config.add_route('redirect', '/{arg}')
    
    def redirect_view(request):
        dst = 'http://mydomain2.com/register.php?id={id}&from={host}'
        args = {
            'id': request.matchdict['arg'],
            'host': request.host,
        }
        return HTTPFound(dst.format(**args))
    config.add_view(redirect_view, route_name='redirect')
    
    serve(config.make_wsgi_app(), host='0.0.0.0', port=80)