我正在开发一个用于创建/编辑 Django 模型的工具,请参阅https://github.com/timothyclemans/django-admin-models-editor。
解析 Python 代码的推荐方法是什么?我需要做一堆正则表达式并做很多 if thens 吗?
下面的代码获取模型名称和字段名称。
code_from_input = request.POST['code'].split('\n')[0]
def_lines = ''
if ' def' in request.POST['code']:
for i, line in enumerate(request.POST['code'].split('\n')):
if line.startswith(' def'):
def_lines = '\n'.join(request.POST['code'].split('\n')[i:])
break
last_code_from_input = request.POST['last_code'].split('\n')[0]
# check if model name in source changed
model_name_in_last_source = ''
model_name_in_code = ''
if last_code_from_input.startswith('class'):
m = re.match(r"class (\w+)\(models.Model\):", last_code_from_input)
try:
model_name_in_last_source = m.group(1)
except:
pass
if code_from_input.startswith('class'):
m = re.match(r"class (\w+)\(models.Model\):", code_from_input)
try:
model_name_in_code = m.group(1)
except:
pass
if model_name_in_last_source != model_name_in_code:
model_name = model_name_in_code
else:
model_name = request.POST['name']