Avatar

Code is self explanatory. Could this be written in a better way? Just curious

1
2
3
4
5
cards = Card.objects.all()

for card in cards:
        photo_index = card.photo_address.rfind('/')
        card.thumb_url = card.photo_address[photo_index:].replace('/', '/th_')

Refactorings

No refactoring yet !

3ca6bd7b50c8f00349e6586c3627de24

Tom Lynn

July 17, 2008, July 17, 2008 12:31, permalink

No rating. Login to rate!

This is shorter, but arguably not clearer.

1
2
3
4
cards = Card.objects.all()

for card in cards:
    card.thumb_url = '/th_'.join(card.photo_address.rsplit('/', 1))
Avatar

gsson

August 20, 2008, August 20, 2008 13:49, permalink

No rating. Login to rate!

Normally I would use something like
card.thumb_url = os.path.join(os.path.dirname(card.photo_address), "th_" + os.path.basename(card.photo_address))
It is not optimal, but it does convey the intent rather well. But since os.path.* performs OS-dependant operations (quite portable code provided you were actually realing with file-system paths rather than URLs). I think the following snippet would work properly on URLs though.

1
2
3
4
5
6
import os.path

cards = Card.objects.all()

for card in cards:
    card.thumb_url = urljoin(cards.photo_address, "th_" + os.path.basename(cards.photo_address))
Avatar

gsson

August 20, 2008, August 20, 2008 13:50, permalink

No rating. Login to rate!

Oops, missed an import when I copied; add "from urlparse import urljoin"

Your refactoring





Format Copy from initial code

or Cancel