Files

This document explains how to render single files using diecutter web API. See also Directories about how to render multiple files at once.

Here is service’s API overview:

  • GET: retrieve information about template, typically raw template content.
  • POST: render single template file against data.
  • PUT: upload template file from client to server.
  • other HTTP verbs aren’t implemented yet.

Note

In the examples below, let’s communicate with a diecutter server using Python requests.

This diecutter serves diecutter’s demo templates.

The diecutter_url variable holds root URL of diecutter service, i.e. something like http://diecutter.io/api/.

GET

Let’s work on file resource greetings.txt.

A GET request returns raw template content:

>>> response = requests.get(diecutter_url + 'greetings.txt')
>>> response.status_code
200
>>> print response.content
{{ greetings|default('Hello') }} {{ name }}!

Of course, if template does not exist, it returns a 404:

>>> response = requests.get(diecutter_url + 'i-do-not-exist.txt')
>>> response.status_code
404

POST

POST data to template resource in order to retrieve generated file:

>>> greetings_url = diecutter_url + 'greetings.txt'
>>> response = requests.post(greetings_url, data={'name': 'world'})
>>> response.status_code
200
>>> print response.content
Hello world!

>>> response = requests.post(greetings_url, {'greetings': u'Greetings',
...                                          'name': u'professor Falken'})
>>> print response.content
Greetings professor Falken!

See also Targeting template engines about using specific template engines.

PUT

Use PUT to upload template from client to server:

>>> name = 'hello'
>>> server_side_name = os.path.join(diecutter_template_dir, name)
>>> os.path.exists(server_side_name)
False
>>> url = diecutter_url + name
>>> files = {'file': ('client-side-name', 'Hello {{ who }}\n')}
>>> response = requests.put(url, files=files)
>>> response.status_code
201
>>> os.path.exists(server_side_name)
True
>>> print open(server_side_name).read()
Hello {{ who }}

Subdirectories are created on the fly:

>>> name = 'some/nested/directories/hello'
>>> server_side_name = os.path.join(diecutter_template_dir, name)
>>> os.path.exists(server_side_name)
False
>>> url = diecutter_url + name
>>> files = {'file': ('client-side-name', 'Hello {{ who }}\n')}
>>> response = requests.put(url, files=files)
>>> response.status_code
201
>>> os.path.exists(server_side_name)
True
>>> print open(server_side_name).read()
Hello {{ who }}

Warning

Sometimes, you don’t want users to be able to PUT files on your server. That’s why diecutter service can be configured as “read only”. In that case, it is up to you to manage files that live in diecutter’s template directory (which is just a directory in the filesystem).

As an example, diecutter’s online demo is readonly, and templates are synchronized with source code on project’s repository.