Dealing with spaces in creating Flask URLs

In the jar application I'm working on, I use US state names as part of the URL structure. State names are pulled from a python dictionary that associates state abbreviations with their corresponding proper name, for example.

state_dict = {"Alabama" : "AL", "Alaska" : "AK",... 

This is normal when the state name has no spaces. for example http://example.com/Alabama/ However, when the state in question has a space in it, it forms a bad URL. e.g. http://example.com/North%20Dakota/

I currently circumvented this, being careful when I create URLs using state names to use something like state=state.replace(' ', '_') as an argument in url_for() . However, it is bulky and seems rude.

What is the best way to use state names as part of a URL without having to manually change them each time? Extra points if this solution can also be used to change lowercase letters. p>

I thought about modifying the state dict to be URL friendly, for example. north_dakota instead of North Dakota , however, dict is also used when creating text to display to users and count readability.

Thanks so much for your time!

+4
source share
2 answers

The most common pattern for python will be to use a pair of dictionaries to search forward / backward to go from and to your friendly dictionary. On the other hand, the term commonly used for such a "friendly URL" representation of a string value is "slug".

 # state_slugs lets you lookup either state name or code => its slug state_slugs = {} # states_from_slugs lets you lookup the slug => the state name states_from_slugs = {} for state_name, state_code in state_dict.items(): slug = state_name.lower().replace(' ', '_') state_slugs[state_name] = slug state_slugs[state_code] = slug states_from_slugs[slug] = state_name 

You put this somewhere when it starts only once, for example, perhaps at the module level or shortly after creating state_dict .

Then access to state_slugs['NC'] or state_slugs['North Carolina'] will work to return north_carolina, and access to states_from_slugs['north_carolina'] will return North Carolina for reverse lookups.

+4
source

Have you considered creating a second dictionary to represent your URL-specific names? And you just don’t need to worry about adding the 51st state (when this happens) to the two dictionaries, you can do this easily at runtime:

 state_dictionary = {'South Carolina': 'SC', 'North Carolina': 'NC'} url_friendly = {k.lower().replace(' ', '_'): v for k, v in state_dictionary.iteritems()} 

or, for pre-2.7 python:

 url_friendly = dict((k.lower().replace(' ', '_'), v) for k, v in state_dictionary.iteritems()) 

creates something like this:

 {'south_carolina': 'SC', 'north_carolina': 'NC'} 
+2
source

Source: https://habr.com/ru/post/1384526/


All Articles