In a flask app I’m working on, I use U.S. state names as part of the url structure. State names are pulled from a python dictionary that links state abbreviations with their respective proper name, e.g.
state_dict = {"Alabama" : "AL", "Alaska" : "AK",...
This is fine when the state name has no spaces. e.g. http://example.com/Alabama/ However, when the state in question has a space in it, it forms a poor url. e.g. http://example.com/North%20Dakota/
I currently get around this by being careful when I create urls using the state names to use something like state=state.replace(' ', '_') as an argument in url_for(). However, it’s cumbersome and seems crude.
How can I better use state names as part of the url without having to manually modify them each time? Extra points if the solution can also be used to change upper case letters to lowercase.
I’ve considered modifying the state dict to be url friendly e.g. north_dakota instead of North Dakota however, the dict is also used when creating text to display to users, and readability counts.
Thanks very much for your time!
The most common pattern for python would be to use a pair of dictionaries for the forward / reverse lookup to go from and to your friendly dictionary. On a side note, the term commonly used for such a “url-friendly” representation of a string value is “slug”.
You would put this somewhere it’s run only once, like possibly at module-level, or soon after your
state_dicthas been created.Then accessing either
state_slugs['NC']orstate_slugs['North Carolina']will both work to return “north_carolina” and accessingstates_from_slugs['north_carolina']will return ‘North Carolina’ for the reverse lookup.