[mod_python] How to get path from URL

Graham Dumpleton grahamd at dscpl.com.au
Sun Feb 27 18:22:05 EST 2005


Shawn Harrison wrote ..
> > What you want is:
> > 
> >   p = 'http://' + req.hostname + req.uri[:-len(req.path_info)]
> > 
> > Which yields:
> > 
> >   http://localhost/~grahamd/hclass/page
> 
> Well, that's a lot less work, isn't it.
> 
> > This will not work though if not the standard server port or if "https"
> is
> > used.
> 
> Thanks, I forgot to mention that.
> 
> Is the port available in mod_python? I wasn't able to find it when
> working with this problem earlier. How about the protocol (https vs http)?

One can get the port from the connection object, but protocol, hostname
and port aren't usually wise things to rely on if one is intending to use the
derived address to plug back into a HTML page for example. This is because
it will fail with if your web page location is being masked by another instance
of Apache using proxy pass through.

The original poster would have to be clear about what they intended using
it for in order to comment further as to whether it is a good idea to be
doing what was asked for.

If the intent is to use the address in generated HTML content where it is
a hyperlink, you are thus better off using a relative address. This can be a
bit tricky if using publisher though where it may auto map to an index()
method as well as you accessing it explicitly. Ie., from memory if you
access "/dog" you can end up with:

  req.uri = /dog
  req.path_info =

If you instead access "/dog/index" you instead get for the same method:

  req.uri = /dog/index
  req.path_info = /index

If my thinking is right, the relative URL in the first case would need to
be "." and in the latter "..". You thus perhaps need to do something like:

  hops = req.path_info.split('/')
  if len(hops) == 1:
    relative = "."
  else:
    relative = '/'.join((len(hops)-1)*[".."])

If instead you are after a URL for the purposes of doing an internal/external
redirection, you do not need the protocol, hostname and port anyway and
could just say:

  target = req.uri[:-len(req.path_info)] + '/login
  req.internal_redirect(target)

Note, that the above haven't been throughly tested. I could also just be wrong
in the first place. :-)

Graham


More information about the Mod_python mailing list