Field resources
***************

Each of an entry's fields has its own HTTP resource. If you only need
to change one of an entry's fields, you can send PUT or PATCH to the
field resource itself, rather than PUT/PATCH to the entry.

    >>> from lazr.restful.testing.webservice import WebServiceCaller
    >>> webservice = WebServiceCaller(domain='cookbooks.dev')

    >>> from urllib import quote
    >>> cookbook_url = quote("/cookbooks/The Joy of Cooking")
    >>> field_url = cookbook_url + "/description"

    >>> import simplejson
    >>> def set_description(description):
    ...     """Sets the description for "The Joy of Cooking"."""
    ...     return webservice(field_url, 'PATCH',
    ...                       simplejson.dumps(description)).jsonBody()

    >>> print set_description("New description")
    New description

    >>> print webservice.get(field_url)
    HTTP/1.1 200 Ok
    ...
    Content-Type: application/json
    ...
    "New description"

PATCH on a field resource works identically to PUT.

    >>> representation = simplejson.dumps('<b>Bold description</b>')
    >>> print webservice.put(field_url, 'application/json',
    ...                      representation).jsonBody()
    <b>Bold description</b>

If you get a field that contains a link to another object, you'll see
the link, rather than the actual object.

    >>> link_field_url = "/recipes/3/cookbook_link"
    >>> print webservice.get(link_field_url).jsonBody()
    http://.../cookbooks/James%20Beard%27s%20American%20Cookery

    >>> collection_url = quote(
    ...     "/cookbooks/The Joy of Cooking/recipes_collection_link")
    >>> print webservice.get(collection_url).jsonBody()
    http://.../cookbooks/The%20Joy%20of%20Cooking/recipes

Changing a field resource that contains a link works the same way as
changing a field resource that contains a scalar value.

    >>> new_value = simplejson.dumps(
    ...     webservice.get(cookbook_url).jsonBody()['self_link'])
    >>> print new_value
    "http://.../cookbooks/The%20Joy%20of%20Cooking"

    >>> print webservice(link_field_url, 'PATCH', new_value)
    HTTP/1.1 209 Content Returned
    ...
    Content-Type: application/json
    ...
    <BLANKLINE>
    "http://cookbooks.dev/.../cookbooks/The%20Joy%20of%20Cooking"

The same rules for modifying a field apply whether you're modifying
the entry as a whole or just modifying a single field.

    >>> date_field_url = cookbook_url + "/copyright_date"
    >>> print webservice.put(date_field_url, 'application/json',
    ...                      simplejson.dumps("string"))
    HTTP/1.1 400 Bad Request
    ...
    copyright_date: Value doesn't look like a date.

    >>> print webservice(collection_url, 'PATCH', new_value)
    HTTP/1.1 400 Bad Request
    ...
    recipes_collection_link: You tried to modify a collection attribute.

Field resources also support GET, for when you only need part of an
entry. You can get either a JSON or XHTML-fragment representation.

    >>> print webservice.get(field_url).jsonBody()
    <b>Bold description</b>

    >>> print webservice.get(field_url, 'application/xhtml+xml')
    HTTP/1.1 200 Ok
    ...
    Content-Type: application/xhtml+xml
    ...
    &lt;b&gt;Bold description&lt;/b&gt;

Cleanup.

    >>> ignored = set_description("Description")

Changing a field resource can move the entry
--------------------------------------------

If you modify a field that the entry uses as part of its URL (such as
a cookbook's name), the field's URL will change. You'll be redirected
to the new field URL.

    >>> name_url = cookbook_url + "/name"
    >>> representation = simplejson.dumps("The Joy of Cooking Extreme")
    >>> print webservice.put(name_url, 'application/json',
    ...                      representation)
    HTTP/1.1 301 Moved Permanently
    ...
    Location: http://.../cookbooks/The%20Joy%20of%20Cooking%20Extreme/name
    ...

Note that the entry's URL has also changed.

    >>> print webservice.get(cookbook_url)
    HTTP/1.1 404 Not Found
    ...

    >>> new_cookbook_url = quote("/cookbooks/The Joy of Cooking Extreme")
    >>> print webservice.get(new_cookbook_url)
    HTTP/1.1 200 Ok
    ...

Cleanup.

    >>> representation = simplejson.dumps("The Joy of Cooking")
    >>> new_name_url = new_cookbook_url + "/name"
    >>> print webservice.put(new_name_url, 'application/json',
    ...                      representation)
    HTTP/1.1 301 Moved Permanently
    ...
    Location: http://.../cookbooks/The%20Joy%20of%20Cooking/name
    ...

Field resources can give more detail than entry resources
=========================================================

An entry resource, and the field resource for one of the entry's
fields, will display the same basic information. But the entry field
can give a lot more detail.

For instance, here's the representation of a cookbook's 'cuisine' field
within the cookbook entry itself.

    >>> cookbook = webservice.get(cookbook_url).jsonBody()
    >>> print cookbook['cuisine']
    General

Here's the representation of the resource for the same 'cuisine' field.

    >>> for cuisine in sorted(
    ...     webservice.get(cookbook_url + '/cuisine').jsonBody()):
    ...     print(sorted(cuisine.items()))
    [(u'title', u'American'), (u'token', u'AMERICAN')]
    ...
    [(u'selected', True), (u'title', u'General'), (u'token', u'GENERAL')]

The detailed representation includes information about the other
values the 'status' field can take. This information is also published
in the WADL file, but that's not easily accessible to some clients,
especially JavaScript clients.

XHTML representations don't work this way. Complex XHTML
representations require custom code; see "Custom representations"
below. By default, the XHTML representation of a field is a simple
HTML-escaped string, similar to what's seen in the JSON representation
of the entry.

    >>> print webservice.get(cookbook_url + '/cuisine',
    ...                      'application/xhtml+xml')
    HTTP/1.1 200 Ok
    ...
    General

=================
Supported methods
=================

Field resources support GET, PUT, and PATCH.

    >>> for method in ['HEAD', 'POST', 'DELETE', 'OPTIONS']:
    ...     print webservice(field_url, method)
    HTTP/1.1 405 Method Not Allowed...
    Allow: GET PUT PATCH
    ...
    HTTP/1.1 405 Method Not Allowed...
    Allow: GET PUT PATCH
    ...
    HTTP/1.1 405 Method Not Allowed...
    Allow: GET PUT PATCH
    ...
    HTTP/1.1 405 Method Not Allowed...
    Allow: GET PUT PATCH
    ...

===============
Conditional GET
===============

Field resources have ETags independent of their parent entries. They
respond to conditional GET.

    >>> response = webservice.get(cookbook_url)
    >>> cookbook_etag = response.getheader('ETag')

    >>> response = webservice.get(field_url)
    >>> etag = response.getheader('ETag')

    >>> cookbook_etag == etag
    False

    >>> print webservice.get(field_url, headers={'If-None-Match': etag})
    HTTP/1.1 304 Not Modified
    ...

    >>> ignored = set_description("new description")
    >>> print webservice.get(field_url,
    ...                      headers={'If-None-Match': etag})
    HTTP/1.1 200 Ok
    ...

=================
Conditional write
=================

Every field supports conditional PUT and PATCH, just like the entries
do.

    >>> response = webservice.get(field_url)
    >>> cookbook_etag = response.getheader('ETag')

The first attempt to modify the field succeeds, because the ETag
provided in If-Match is the one we just got from a GET request.

    >>> representation = simplejson.dumps("New description")
    >>> print webservice.put(field_url, 'application/json',
    ...                      representation,
    ...                      headers={'If-Match': cookbook_etag})
    HTTP/1.1 209 Content Returned
    ...

But when the field is modified, the ETag changes. Any subsequent
requests that use that ETag in If-Match will fail.

    >>> print webservice.put(field_url, 'application/json',
    ...                      representation,
    ...                      headers={'If-Match': cookbook_etag})
    HTTP/1.1 412 Precondition Failed
    ...

    >>> ignored = set_description("Description")

============================
Custom XHTML representations
============================

Every entry has an XHTML representation. The default representation is
a simple text node.

  >>> print webservice.get(field_url, 'application/xhtml+xml')
  HTTP/1.1 200 Ok
  ...
  Description

But it's possible to define a custom HTML renderer for a particular
object and field type. Here's a simple renderer that bolds whatever
value it's given.

  >>> from zope import component
  >>> from zope.interface import implementer
  >>> from zope.schema.interfaces import ITextLine
  >>> from lazr.restful.interfaces import (
  ...     IFieldHTMLRenderer, IWebServiceClientRequest)
  >>> from lazr.restful.example.base.interfaces import ICookbook

  >>> from lazr.restful.testing.webservice import simple_renderer
  >>> @component.adapter(ICookbook, ITextLine, IWebServiceClientRequest)
  ... @implementer(IFieldHTMLRenderer)
  ... def dummy_renderer(context, field, request):
  ...     """Bold the original string and add a snowman."""
  ...     return simple_renderer

  >>> print webservice.get(cookbook_url +'/name', 'application/xhtml+xml')
  HTTP/1.1 200 Ok
  ...
  The Joy of Cooking

Register the renderer as the IFieldHTMLRenderer adapter for an
ITextLine field of an IPerson entry...

  >>> from zope.component import getGlobalSiteManager
  >>> manager = getGlobalSiteManager()
  >>> manager.registerAdapter(dummy_renderer)

...and the XHTML representation of an ICookbook's description will be the
result of calling a dummy_renderer object.

  >>> from lazr.restful.testing.helpers import encode_response
  >>> response = webservice.get(field_url, 'application/xhtml+xml')
  >>> print encode_response(response)
  HTTP/1.1 200 Ok
  ...
  \u2603 Description

In fact, that adapter will be used for every ITextLine field of an
ICookbook.

  >>> print encode_response(
  ...     webservice.get(cookbook_url +'/name', 'application/xhtml+xml'))
  HTTP/1.1 200 Ok
  ...
  The Joy of Cooking

The adapter will not be used for ITextLine fields of other interfaces:

  >>> dish_field_url = quote('/dishes/Roast chicken/name')
  >>> print webservice.get(dish_field_url, 'application/xhtml+xml')
  HTTP/1.1 200 Ok
  ...
  Roast chicken

It will not be used for non-text fields of ICookbook.

  >>> print webservice.get(cookbook_url + '/copyright_date',
  ...                      'application/xhtml+xml')
  HTTP/1.1 200 Ok
  ...
  1995-01-01

Combined JSON/HTML representations
----------------------------------

You can get a combined JSON/HTML representation of an entry by setting
the "include=lp_html" parameter on the application/json media type.

  >>> response = webservice.get(
  ...     cookbook_url, 'application/json;include=lp_html')
  >>> print response.getheader("Content-Type")
  application/json;include=lp_html

The cookbook's description is a normal JSON representation...

  >>> json = response.jsonBody()
  >>> print json['description']
  Description

...but the JSON dictionary will include a 'lp_html' sub-dictionary...

  >>> html = json['lp_html']

...which includes HTML representations of the fields with HTML
representations:

  >>> sorted(html.keys())
  [u'description', u'name']

  >>> from lazr.restful.testing.helpers import encode_unicode
  >>> print encode_unicode(html['description'])
  \u2603 Description

  >>> print encode_unicode(html['name'])
  \u2603 The Joy of Cooking

Cleanup
-------

Before we continue, here's some cleanup code to remove the custom
renderer we just defined.

  >>> ignored = getGlobalSiteManager().unregisterAdapter(dummy_renderer)

Compare the HTML generated by the custom renderer, to the XHTML
generated now that the default adapter is back in place.

  >>> ignored = set_description("Bold description")

  >>> print webservice.get(field_url, 'application/xhtml+xml')
  HTTP/1.1 200 Ok
  ...
  <b>Bold description</b>

  >>> ignored = set_description("Description")

The default renderer escapes HTML tags because it thinks they might
contain XSS attacks. If you define a custom adapter, you can generate
XHTML without worrying about the tags being escaped. The downside is
that you're responsible for escaping user-entered HTML tags yourself
to avoid XSS attacks.

Defining a custom representation for a single field
===================================================

It's also possible to define a custom HTML representation of one
particular field, by registering a view on the field. This code
creates a custom renderer for ICookbook.description, by registering
a view on ICookbook called "description".

  >>> @component.adapter(ICookbook, ITextLine, IWebServiceClientRequest)
  ... @implementer(IFieldHTMLRenderer)
  ... def dummy_renderer(context, field, request):
  ...     """Bold the original string, add a snowman, and encode UTF-8."""
  ...     def render(value):
  ...         return (u"\N{SNOWMAN} %s" % value).encode("utf-8")
  ...     return render
  >>> manager.registerAdapter(dummy_renderer, name='description')

This renderer is identical to the one shown earlier, except that it
returns UTF-8 instead of Unicode.

  >>> response = webservice.get(field_url, 'application/xhtml+xml')
  >>> print encode_response(response)
  HTTP/1.1 200 Ok
  ...
  \u2603 Description

Unlike what happened when we registered a renderer for
ICookbook/ITextLine, other ITextLine fields of ICookbook are not
affected.

  >>> print webservice.get(cookbook_url + '/name', 'application/xhtml+xml')
  HTTP/1.1 200 Ok
  ...
  The Joy of Cooking

The XHTML representation of an entry incorporates any custom XHTML
representations of that entry's fields.

  >>> response = webservice.get(cookbook_url, 'application/xhtml+xml')
  >>> print encode_response(response)
  HTTP/1.1 200 Ok
  ...
  
description
  
\u2603 Description
  ...

Before we continue, here's some code to unregister the view.

  >>> ignored = getGlobalSiteManager().unregisterAdapter(
  ...      dummy_renderer, name='description')

  >>> print webservice.get(field_url, 'application/xhtml+xml')
  HTTP/1.1 200 Ok
  ...
  Description
