[英]Change path of url flask with regex
In flask I a before_request
function which does some checks and returns the user to a different url if necessary. 在烧瓶中,我的
before_request
函数会进行一些检查,并在必要时将用户返回到另一个url。
I have something similar to the following example which where I get request_url
I now want to change this from: https://www.example.com:5000/user/profile/
to https://www.example.com:5000/us/user/profile/
我有一个类似于以下示例的示例,该示例中我获取
request_url
,现在我希望将其从以下位置更改: https://www.example.com:5000/user/profile/
: request_url
更改为https://www.example.com:5000/us/user/profile/
@app.before_request
def check_location():
country = request.cookies.get('country')
if country != g.country:
url = request.url
url = re.sub('.com[^\/]*', '.com/us', url)
return redirect(url, 301)
I tried some regex but this does not work when using dev server with a port. 我尝试了一些正则表达式,但是在使用带端口的开发服务器时这不起作用。 So my question is:
所以我的问题是:
Use groups: 使用组:
url = "https://www.example.com:5000/user/profile/"
url = re.sub('.com[^\/]*', '\g<0>/us', url)
print url # https://www.example.com:5000/us/user/profile/
From the docs: 从文档:
In addition to character escapes and backreferences as described above, \\g will use the substring matched by the group named name, as defined by the (?P...) syntax.
除了如上所述的字符转义和反向引用之外,\\ g还将使用由(?P ...)语法定义的名为name的组匹配的子字符串。 \\g uses the corresponding group number;
\\ g使用相应的组号; \\g<2> is therefore equivalent to \\2, but isn't ambiguous in a replacement such as \\g<2>0.
因此,\\ g <2>等效于\\ 2,但在诸如\\ g <2> 0之类的替换中并没有歧义。 \\20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'.
\\ 20将被解释为对组20的引用,而不是对组2的引用,后跟文字字符“ 0”。 The backreference \\g<0> substitutes in the entire substring matched by the RE.
反向引用\\ g <0>替换RE匹配的整个子字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.