如何使用正则表达式指定长 url 模式,以便它们遵循 PEP8 准则



我在 Django 中有一个类似于这样的长 url 模式:

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

绝对它不遵循 PEP8 指南,因为一行中的字符超过 80 个。我找到了两种解决此问题的方法:

第一个(使用反斜杠):

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

第二个 - 使用 ():

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

他们都被正则表达式打破了。有没有更好的方法来解决这个问题。或者为 url 编写这么长的正则表达式是一种不好的做法。

相邻的字符串是串联的,所以你可以做这样的事情:

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

PEP8 没有正则表达式格式化提示。但是试试这些:

  • 使用 re.compile 并具有这些好处
    • 更快地匹配/搜索它们
    • 在(短)名称下引用它们!
  • 用(空白)空格编写正则表达式多行
    • 使用 re。VERBOSE 忽略正则表达式字符串中的空格
    • 使用旗帜代替"魔法组" ( (?i) → re.IGNORECASE

 

slugs = re.compile(r'''
    ^
    top-dir/
    (?P<first_slug>[-w]+?)/
    (?P<second_slug>[-w]+?)/
    (?P<third_slug>[-w]+?).html/
    $
        ''', re.VERBOSE|re.IGNORECASE)
url(slugs, 'apps.Discussion.views.pricing', ...)

最新更新