Newbie: Is there a more pythonic approach?

Fredrik Lundh fredrik at pythonware.com
Wed Mar 14 17:08:07 CET 2001


loyd Sommerer wrote:
> Thanks, the program follows below.

looks fine to me.  minor nits below.

> =========================================
> error_page = '/404.html'
> base_url = 'http://churchsite.gatheringspot.com'
> base_directory = '/home/gatheri/public_html/churchsite/'
> extension_list = ['.html','.shtml','.htm','.txt','.php','.asp']
>
> import string
> import os
>
> lowercase_url = string.lower(os.environ['REDIRECT_URL'])
> url_path,url_extension = os.path.splitext(lowercase_url)
> new_url = base_url+error_page

to make the program a bit more robust, you might wish to
use os.path.join and urlparse.urljoin instead of "+" when
building filenames/urls.

> #
> # Check to see if simply converting the URL to lowercase corrects the
> problem.
> # If it doesn't, check to see if the extension is incorrect and fix it
> if it is.
> #
> if os.path.exists(base_directory+lowercase_url):
>     new_url = base_url+lowercase_url

if you like source code optimizations, you could prepend an empty
extension to the extensions list and get rid of the if clause:

      for extension in [''] + extension_list:

> else:
>     for extension in extension_list:
>         if os.path.exists(base_directory+url_path+extension):
>             new_url = base_url+url_path+extension

you should probably add a break here, to get out of the loop once
you've found an existing file.

for extra python-style points, you can use the for-else construct
to set new_url to the error page URL only if you don't find a file:

    filename = os.path.join(base_directory, url_path)
    for extension in [''] + extension_list:
            if os.path.exists(filename + extension):
                new_url = urlparse.urljoin(base_url, url_path + extension)
                break # this skips the else clause
    else:
        new_url = urlparse.urljoin(base_url, error_page)

> #
> # Send HTTP header information to the browser so that it can request the
> "correct" document.
> #
> print "Status: 301 Permanently moved"
> print "Location: " + new_url

or:

    print "Location:", new_url

> print

Cheers /F

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list