Django rest framework interface code generator

Time:2020-11-30

Refuse to repeat work

Save the following code as codeGen.py In the module statistics directory

import sys

name = sys.argv[1]
verbose = sys.argv[2]


def underscore(str):
    return "".join(map(lambda x: "_" + x if x.isupper()  else x, str))[1:].lower()


model = """class {name}(CoreModel):

    class Meta:
        verbose_name = '{verbose}'
        verbose_name_plural = '{verbose}'""".format(name=name, verbose=verbose)

serializer = """class {name}Serializer(serializers.ModelSerializer):
    class Meta:
        model = {name}""".format(name=name, verbose=verbose)

view = """class {name}ViewSet(viewsets.ModelViewSet):
    serializer_class = {name}Serializer
    queryset = {name}.objects.all()""".format(name=name, verbose=verbose)

url = """router.register(r'{lower}', {name}ViewSet, base_name="{lower}")""".format(name=name, verbose=verbose,
                                                                                   lower=underscore(name) + 's')

try:
    with open('models.py', 'a') as f:
        f.write(model)
    with open('serializers.py', 'a') as f:
        f.write(serializer)
    with open('views.py', 'a') as f:
        f.write(view)
    with open('urls.py', 'a') as f:
        f.write(url)

    Print ("generating API interface {name} finished". Format (name = name))
except:
    Print ("code generation error")

Execute the order

Execute in the module directorypython codeGen.py Model word model description
The model word is Tuofeng nomenclature

Recommended Today

JS function

1. Ordinary function Grammar: Function function name (){ Statement block } 2. Functions with parameters Grammar: Function function name (parameter list){ Statement block } 3. Function with return value Grammar: Function function name (parameter list){ Statement block; Return value; } Allow a variable to accept the return value after calling the function Var variable name […]