【问题标题】:How to specify long url patterns using Regex so that they follow PEP8 guidelines如何使用正则表达式指定长 url 模式,以便它们遵循 PEP8 指南
【发布时间】:2014-05-11 15:01:03
【问题描述】:

我在 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'),  

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

【问题讨论】:

    标签: python django pep8


    【解决方案1】:

    相邻的字符串是连接在一起的,所以你可以这样做:

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

    【讨论】:

    • 澄清:它们在括号内连接。
    • 这就是这种情况下的情况,但它们不是只是连接在括号内。在交互式 shell 中尝试s = "foo" "bar"
    • 感谢您在不同的行中打破每个 slug 的想法。它使代码更具可读性。
    【解决方案2】:

    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', ...)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 2012-01-24
      相关资源
      最近更新 更多