seitime-frappe/frappe/website/redirect.py
Gavin D'souza e407b78506 chore: Drop dead and deprecated code
* Remove six for PY2 compatability since our dependencies are not, PY2
  is legacy.
* Removed usages of utils from future/past libraries since they are
  deprecated. This includes 'from __future__ ...' and 'from past...'
  statements.
* Removed compatibility imports for PY2, switched from six imports to
  standard library imports.
* Removed utils code blocks that handle operations depending on PY2/3
  versions.
* Removed 'from __future__ ...' lines from templates/code generators
* Used PY3 syntaxes in place of PY2 compatible blocks. eg: metaclass
2021-05-26 15:31:29 +05:30

39 lines
1 KiB
Python

import re, frappe
def resolve_redirect(path):
'''
Resolve redirects from hooks
Example:
website_redirect = [
# absolute location
{"source": "/from", "target": "https://mysite/from"},
# relative location
{"source": "/from", "target": "/main"},
# use regex
{"source": r"/from/(.*)", "target": r"/main/\1"}
# use r as a string prefix if you use regex groups or want to escape any string literal
]
'''
redirects = frappe.get_hooks('website_redirects')
redirects += frappe.db.get_all('Website Route Redirect', ['source', 'target'])
if not redirects: return
redirect_to = frappe.cache().hget('website_redirects', path)
if redirect_to:
frappe.flags.redirect_location = redirect_to
raise frappe.Redirect
for rule in redirects:
pattern = rule['source'].strip('/ ') + '$'
if re.match(pattern, path):
redirect_to = re.sub(pattern, rule['target'], path)
frappe.flags.redirect_location = redirect_to
frappe.cache().hset('website_redirects', path, redirect_to)
raise frappe.Redirect