devxoul
11/22/2013 - 6:23 AM

Replace non-blueprint `url_for` to specific blueprint. e.g. url_for('login') -> url_for('blueprint.login')

Replace non-blueprint url_for to specific blueprint. e.g. url_for('login') -> url_for('blueprint.login')

import os
import re

BLUEPRINT = 'blueprint'
TARGET_DIR = 'myproject/templates'
RECURSIVE = True
EXTENSIONS = ['py', 'html', 'htm']

pat = "url_for\('(?![a-z]+\.)(?!static)([a-z_]+)"
rep = "url_for('%s.\g<1>" % BLUEPRINT


def replace_all(dirpath):
    for filename in os.listdir(dirpath):
        path = os.path.join(dirpath, filename)
        if not os.path.isdir(path):
            if filename.split('.')[-1] in EXTENSIONS:
                f = open(path, 'r+')
                rv = re.sub(pat, rep, f.read())
                f.seek(0)
                f.write(rv)
                f.close()
        elif RECURSIVE:
            if filename[0] != '.':
                replace_all(path)

if __name__ == '__main__':
    replace_all(TARGET_DIR)