Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify long url patterns using Regex so that they follow PEP8 guidelines

I have a long url pattern in Django similar to this:

url(r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/(?P<second_slug>[-\w]+?)/(?P<third_slug>[-\w]+?).html/$',
    'apps.Discussion.views.pricing',

Definitely it doesn't follow PEP8 guide as the characters are more than 80 in a single line. I have found two approach of solving this:

The first one (using backslash):

   url(r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/(?P<second_slug>[-\w]+?)'\
       '/(?P<third_slug>[-\w]+?).html/$',
       'apps.Discussion.views.pricing',

The second one - using ():

 url((r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/(?P<second_slug>[-\w]+?)',
      r'/(?P<third_slug>[-\w]+?).html/$'),
      'apps.Discussion.views.pricing'),  

Both of them break by Regex. Is there a better approach to solve this issue. OR Is it a bad practice to write such long Regex for urls.

like image 809
Sudip Kafle Avatar asked Apr 01 '14 02:04

Sudip Kafle


People also ask

How do you define URL pattern?

A URL pattern is a set of ordered characters to which the Google Search Appliance matches actual URLs that the crawler discovers. You can specify URL patterns for which your index should include matching URLs and URL patterns for which your index should exclude matching URLs.

What is re verbose in Python?

VERBOSE. This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments.

What is regular expression in Python?

A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. RegEx can be used to check if a string contains the specified search pattern.


1 Answers

Adjacent strings are concatenated, so you can do something like this:

url(r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/'
    r'(?P<second_slug>[-\w]+?)/'
    r'(?P<third_slug>[-\w]+?).html/$',
    'apps.Discussion.views.pricing',)
like image 144
khagler Avatar answered Sep 19 '22 12:09

khagler