Django api的正则表达式

2024-06-17 09:37:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的api中使用以下url,使用一个regex

我需要的网址是

testapi/type1/   

testapi/type2/  

testapi/type2/subtype1/   

testapi/type2/subtype2/  

我现在使用的正则表达式是:

(r'^testapi/(?P<type>type1|type2|type3)/(?P<subtype>.*)/$', my_handler),

现在的问题不是页面不喜欢像myapi/type1/[url没有子类型]

最好的解决方案是什么


Tags: apiurlmytype页面regexhandler网址
3条回答

尝试:

(r'^testapi/(?P<type>type1|type2|type3)/(?P<subtype>subtype\d+|)/?$', my_handler)

>>  testapi/type2/
>>  [('type2', '')]
>>  testapi/type2/subtype1/
>>  [('type2', 'subtype1')]
>>  testapi/type2/subtype1
>>  [('type2', 'subtype1')]

(?P<subtype>subtype\d+|)将捕获subtype<number><empty string>。你知道吗

如果您想使regex更加灵活,可以替换以下内容:

  • (?P<subtype>subtype\d+|)>;(?P<subtype>\w+|)
  • (?P<type>type1|type2|type3)>;(?P<type>\w+)

这些替换将不要求您的url包含子类型类型并接受任何字符串。你知道吗

只需创建两种模式:

r('^testapi/type(?P<type\d+)/subtype(?P<subtype>\d+)/$', my_handler),
r('^testapi/type(?P<type>\d+)/$', my_handler),

注册表上的尾随/不可选:

(r'^testapi/(?P<type>type1|type2|type3)/(?P<subtype>.*)/$', my_handler),
                                                       ^ here

尝试添加一个?这也是可选的。你知道吗

相关问题 更多 >