Started work on an upgrade script for blueprints
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 1f31ec4 · Browse files · 2 files·+178 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+178 added−4 removed
- other:+178 added−4 removed
Provenance
- Commit
6dae36f- Tree
66f8be7- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
1f31ec4
2 files changed+178 added−4 removed
modified:flask/helpers.py+7 added-4 removed
166 unmodified lines167 :param values: the variable arguments of the URL rule168 :param _external: if set to `True`, an absolute URL is generated.169 """170 ctx = _request_ctx_stack.top171+ blueprint_name = request.blueprint172 if not ctx.request._is_old_module:173 if endpoint[:1] == '.':174+ if blueprint_name is not None:173- endpoint = request.blueprint + endpoint175+ endpoint = blueprint_name + endpoint176+ else:177+ endpoint = endpoint[1:]178 else:179 # TODO: get rid of this deprecated functionality in 1.0180 if '.' not in endpoint:177- mod = ctx.request.blueprint178- if mod is not None:179- endpoint = mod + '.' + endpoint181+ if blueprint_name is not None:182+ endpoint = blueprint_name + '.' + endpoint183 elif endpoint.startswith('.'):184 endpoint = endpoint[1:]185 external = values.pop('_external', False)186 ctx.app.inject_url_defaults(endpoint, values)386 unmodified linesadded:scripts/flask-07-upgrade.py+171 added
1+#!/usr/bin/env python2+# -*- coding: utf-8 -*-3+"""4+ flask-07-upgrade5+ ~~~~~~~~~~~~~~~~6+7+ This command line script scans a whole application tree and attempts to8+ output an unified diff with all the changes that are necessary to easily9+ upgrade the application to 0.7 and to not yield deprecation warnings.10+11+ This will also attempt to find `after_request` functions that don't modify12+ the response and appear to be better suited for `teardown_request`.13+14+ :copyright: (c) Copyright 2011 by Armin Ronacher.15+ :license: see LICENSE for more details.16+"""17+import re18+import os19+import sys20+import inspect21+import difflib22+import posixpath23+from optparse import OptionParser24+25+try:26+ import ast27+except ImportError:28+ ast = None29+30+31+_string_re_part = r"('([^'\\]*(?:\\.[^'\\]*)*)'" \32+ r'|"([^"\\]*(?:\\.[^"\\]*)*)")'33+_url_for_re = re.compile(r'\b(url_for\()(%s)' % _string_re_part)34+_after_request_re = re.compile(r'((?:@\S+\.(?:app_)?))(after_request)(\b\s*$)(?m)')35+36+37+def error(message):38+ print >> sys.stderr, 'error:', message39+ sys.exit(1)40+41+42+def make_diff(filename, old, new):43+ for line in difflib.unified_diff(old.splitlines(), new.splitlines(),44+ posixpath.normpath(posixpath.join('a', filename)),45+ posixpath.normpath(posixpath.join('b', filename)),46+ lineterm=''):47+ print line48+49+50+def fix_url_for(contents):51+ def handle_match(match):52+ prefix = match.group(1)53+ endpoint = ast.literal_eval(match.group(2))54+ if endpoint.startswith('.'):55+ endpoint = endpoint[1:]56+ else:57+ endpoint = '.' + endpoint58+ return prefix + repr(endpoint)59+ return _url_for_re.sub(handle_match, contents)60+61+62+def looks_like_teardown_function(node):63+ returns = [x for x in ast.walk(node) if isinstance(x, ast.Return)]64+ if len(returns) != 1:65+ return66+ return_def = returns[0]67+ resp_name = node.args.args[0]68+ if not isinstance(return_def.value, ast.Name) or \69+ return_def.value.id != resp_name.id:70+ return71+72+ for body_node in node.body:73+ for child in ast.walk(body_node):74+ if isinstance(child, ast.Name) and \75+ child.id == resp_name.id:76+ if child is not return_def.value:77+ return78+79+ return resp_name.id80+81+82+def fix_teardown_funcs(contents):83+84+ def is_return_line(line):85+ args = line.strip().split()86+ return args and args[0] == 'return'87+88+ def fix_single(match, lines, lineno):89+ if not lines[lineno + 1].startswith('def'):90+ return91+ block_lines = inspect.getblock(lines[lineno + 1:])92+ func_code = ''.join(block_lines)93+ if func_code[0].isspace():94+ node = ast.parse('if 1:\n' + func_code).body[0].body95+ else:96+ node = ast.parse(func_code).body[0]97+ response_param_name = looks_like_teardown_function(node)98+ if response_param_name is None:99+ return100+ before = lines[:lineno]101+ decorator = [match.group(1) +102+ match.group(2).replace('after_', 'teardown_') +103+ match.group(3)]104+ body = [line.replace(response_param_name, 'exception')105+ for line in block_lines if106+ not is_return_line(line)]107+ after = lines[lineno + len(block_lines) + 1:]108+ return before + decorator + body + after109+110+ content_lines = contents.splitlines(True)111+ while 1:112+ found_one = False113+ for idx, line in enumerate(content_lines):114+ match = _after_request_re.match(line)115+ if match is None:116+ continue117+ new_content_lines = fix_single(match, content_lines, idx)118+ if new_content_lines is not None:119+ content_lines = new_content_lines120+ break121+ else:122+ break123+124+ return ''.join(content_lines)125+126+127+def upgrade_python_file(filename, contents, teardown):128+ new_contents = fix_url_for(contents)129+ if teardown:130+ new_contents = fix_teardown_funcs(contents)131+ make_diff(filename, contents, new_contents)132+133+134+def upgrade_template_file(filename, contents):135+ new_contents = fix_url_for(contents)136+ make_diff(filename, contents, new_contents)137+138+139+def scan_path(path=None, teardown=True):140+ for dirpath, dirnames, filenames in os.walk(path):141+ for filename in filenames:142+ filename = os.path.join(dirpath, filename)143+ with open(filename) as f:144+ contents = f.read()145+ if filename.endswith('.py'):146+ upgrade_python_file(filename, contents, teardown)147+ elif '{% for' or '{% if' or '{{ url_for' in contents:148+ upgrade_template_file(filename, contents)149+150+151+def main():152+ """Entrypoint"""153+ if ast is None:154+ error('Python 2.6 or later is required to run the upgrade script.\n'155+ 'The runtime requirements for Flask 0.7 however are still '156+ 'Python 2.5.')157+158+ parser = OptionParser()159+ parser.add_option('-T', '--no-teardown-detection', dest='no_teardown',160+ action='store_true', help='Do not attempt to '161+ 'detect teardown function rewrites.')162+ options, args = parser.parse_args()163+ if not args:164+ args = ['.']165+166+ for path in args:167+ scan_path(path, teardown=not options.no_teardown)168+169+170+if __name__ == '__main__':171+ main()