Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to pass command line arguments to a decorator in Django?

I have a decorator that is supposed to use a parameter that’s passed in from the commandline e.g

@deco(name)
def handle(self, *_args, **options):
    name = options["name"]
def deco(name):
    // The name should come from commandline
    pass
class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            "--name",
            type=str,
            required=True,
        )
    @deco(//How can I pass the name here?)
    def handle(self, *_args, **options):
        name = options["name"]

any suggestions on this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can make a "meta-decorator", something like:

from functool import wraps

def metadeco(function):
    @wraps(function)
    def func(*args, **kwargs):
        name = kwargs['name']
        return deco(name)(function)(*args, **kwargs)
    return func

and then work with that meta-decorator:

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            "--name",
            type=str,
            required=True,
        )
    
    @metadeco
    def handle(self, *_args, **options):
        name = options['name']
        # …
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading