我最近在尝试将我的 REST API 设置为使用路径版本控制时遇到了一些麻烦。
我在 my_app/urls.py 中有代码:
def ping():
return "pong"
API_PREFIX = r'^(?P<version>(v1))'
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(f'^{API_PREFIX}/ping/$', get_json(ping))) # assume that get_json returns the right thing
]
我将这行添加到同一目录中的 settings.py 中:
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning'
'DEFAULT_VERSION': 'v1',
'ALLOWED_VERSIONS': ('v1',),
}
如果我执行 GET localhost:8000/v1/ping/,这将不起作用。 f 字符串是否能够包含 regex 语法,或者问题出在其他地方?我试过 fr'^{(API_PREFIX}}/ping/$' 也没有用。
奖励问题:在 ping 函数中,我如何访问和检查路径中传递的版本号(在这种情况下为 1,但会随时间变化)?
请您参考如下方法:
我发现了问题。文档中的这一段概述了我面临的问题;
Using unnamed regular expression groups¶ As well as the named group syntax, e.g. (?P[0-9]{4}), you can also use the shorter unnamed group, e.g. ([0-9]{4}).
This usage isn’t particularly recommended as it makes it easier to accidentally introduce errors between the intended meaning of a match and the arguments of the view.
> In either case, using only one style within a given regex is recommended. When both styles are mixed, any unnamed groups are ignored and only named groups are passed to the view function.
