How to use machine variables in cookiecutter

Is there a way to machine generate some values โ€‹โ€‹after the user has provided some of their values โ€‹โ€‹for variables in cookiecutter.json ?

I ask that:

  • One of the values โ€‹โ€‹I need to request is quite difficult for users.
  • but itโ€™s very easy for me to write Python code to create the correct value

So I really would like to remove the user prompt and calculate the value.

Things I tried:

  • Search the web for an example pre_gen_project.py file to show how to do this.
  • Read the cookie Advanced Use Page

I use cookiecutter on the command line:

 cookiecutter path_to_template 

Am I missing tricks?

+6
source share
1 answer

I need this exact opportunity just a few days ago. The solution I came up with was to write a wrapper script for cookiecutter, similar to what is stated in:

http://cookiecutter.readthedocs.io/en/latest/advanced_usage.html#calling-cookiecutter-functions-from-python

My script creates a random string for use in a Django project. I called the shorthand script:

 #! /usr/bin/env python from cookiecutter.main import cookiecutter import os rstring = ''.join([c for c in os.urandom(1024) if c.isalnum()])[:64] cookiecutter( 'django-template', # path/url to cookiecutter template extra_context={'secret': rstring}, ) 

So now I just run cut-cut and execute the process as usual. The only difference is that the entry with the name secret in my cookiecutter.json file is pre-populated with the generated value in rstring from the script provided through the passed extra_context.

You can modify the script to accept the template via the command line, but in my use I always use the same template, so I just pass in the hard-coded value of "django-template" as indicated in the code above.

+3
source

All Articles