Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use machine-generated variables in cookiecutter

Tags:

cookiecutter

Is there a way to machine-generate some values, after the user has supplied some their values for the variables in cookiecutter.json?

The reason I ask is that:

  • one of the values I need to prompt for is rather hard for users to work out
  • but it's really easy for me to write some Python code to generate the right value

So I'd really like to be able to remove the user prompt, and calculate the value instead.

Things I've tried:

  • Searched online for an example pre_gen_project.py file to show how to do it
  • Read the cookiecutter Advanced Usage page

I'm using cookiecutter on the command line:

cookiecutter path_to_template

Am I missing any tricks?

like image 367
Clare Macrae Avatar asked May 02 '16 15:05

Clare Macrae


People also ask

How does Cookiecutter work Python?

Cookiecutter is a Python package, easily installable with pip or other package managers, that enables you to create and use templates for microservices and software projects. It is a command-line tool that requires no knowledge of Python to use.

What is cookie cutter coding?

Cookiecutter is a templating library for creating project boilerplates in any programming language.

What is Cookiecutter JSON?

The easiest way to understand what Cookiecutter does is to create a simple one and see how it works. Cookiecutter takes a source directory tree and copies it into your new project. It replaces all the names that it finds surrounded by templating tags {{ and }} with names that it finds in the file cookiecutter.json .


1 Answers

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

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

My script generates a random string for use in a Django project. I called my script cut-cut:

#! /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 simply run cut-cut and step through the process as normal. The only difference is that the entry named secret in my cookiecutter.json file is prepopulated with the generated value in rstring from the script, provided via the extra_context passed.

You could modify the script to accept the template via the command line, but in my usage I always use the same template, thus I simply pass a hard coded value "django-template" as noted in the code above.

like image 112
zzzirk Avatar answered Oct 10 '22 01:10

zzzirk