Skip to content

Commit fcd153d

Browse files
committed
Work on upgrading to new contentful client with localization support.
1 parent c853538 commit fcd153d

File tree

5 files changed

+56
-54
lines changed

5 files changed

+56
-54
lines changed

Makefile

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
SHELL := /bin/bash
2+
PATH := $(PATH):$(HOME)/bin
3+
4+
test:
5+
grow install example
6+
grow build example

contentful_ext/contentful_ext.py

+47-45
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,15 @@
1-
from contentful.cda import client
2-
from contentful.cda import resources
1+
import contentful
32
from grow.common import utils
43
from protorpc import messages
4+
import datetime
55
import grow
6+
import json
67
import os
78

89

9-
class KeyMessage(messages.Message):
10-
preview = messages.StringField(1)
11-
production = messages.StringField(2)
12-
13-
1410
class BindingMessage(messages.Message):
1511
collection = messages.StringField(1)
16-
contentModel = messages.StringField(2)
12+
content_type = messages.StringField(2)
1713

1814

1915
class ContentfulPreprocessor(grow.Preprocessor):
@@ -22,22 +18,27 @@ class ContentfulPreprocessor(grow.Preprocessor):
2218
_edit_space_url_format = 'https://app.contentful.com/spaces/{space}/entries'
2319
_preview_endpoint = 'preview.contentful.com'
2420

21+
def encoder(self):
22+
preprocessor = self
23+
class ContentfulEncoder(json.JSONEncoder):
24+
def default(self, obj):
25+
if isinstance(obj, datetime.datetime):
26+
return obj.isoformat()
27+
if hasattr(obj, 'type') and obj.type == 'Entry':
28+
return obj.fields()
29+
if hasattr(obj, 'type') and obj.type == 'Link':
30+
return obj.raw
31+
if hasattr(obj, 'type') and obj.type == 'Asset':
32+
return obj.url()
33+
return json.JSONEncoder.default(self, obj)
34+
return ContentfulEncoder
35+
2536
class Config(messages.Message):
2637
space = messages.StringField(2)
27-
keys = messages.MessageField(KeyMessage, 3)
38+
access_token = messages.StringField(3)
2839
bind = messages.MessageField(BindingMessage, 4, repeated=True)
2940
limit = messages.IntegerField(5)
30-
31-
def _parse_field(self, field):
32-
if isinstance(field, resources.Asset):
33-
return field.url
34-
elif isinstance(field, resources.Entry):
35-
return field.sys['id']
36-
elif isinstance(field, resources.ResourceLink):
37-
return self.cda.resolve_resource_link(field)
38-
elif isinstance(field, list):
39-
return [self._parse_field(sub_field) for sub_field in field]
40-
return field
41+
preview = messages.BooleanField(6, default=False)
4142

4243
def _parse_entry(self, entry):
4344
"""Parses an entry from Contentful."""
@@ -63,48 +64,49 @@ def _parse_entry(self, entry):
6364
body = body.encode('utf-8')
6465
return fields, body, basename
6566

66-
def bind_collection(self, entries, collection_pod_path, contentful_model):
67+
def bind_collection(self, entries, collection_pod_path):
6768
"""Binds a Grow collection to a Contentful collection."""
6869
collection = self.pod.get_collection(collection_pod_path)
6970
existing_pod_paths = [
7071
doc.pod_path for doc in collection.list_docs(recursive=False, inject=False)]
7172
new_pod_paths = []
7273
for i, entry in enumerate(entries):
73-
if entry.sys['contentType']['sys']['id'] != contentful_model:
74-
continue
75-
fields, body, basename = self._parse_entry(entry)
76-
# TODO: Ensure `create_doc` doesn't die if the file doesn't exist.
77-
path = os.path.join(collection.pod_path, basename)
78-
if not self.pod.file_exists(path):
79-
self.pod.write_yaml(path, {})
80-
doc = collection.create_doc(basename, fields=fields, body=body)
81-
new_pod_paths.append(doc.pod_path)
82-
self.pod.logger.info('Saved -> {}'.format(doc.pod_path))
74+
result = json.dumps(entry.fields(), cls=self.encoder())
75+
print result
76+
77+
# if entry.sys['contentType']['sys']['id'] != contentful_model:
78+
# continue
79+
# fields, body, basename = self._parse_entry(entry)
80+
# # TODO: Ensure `create_doc` doesn't die if the file doesn't exist.
81+
# path = os.path.join(collection.pod_path, basename)
82+
# if not self.pod.file_exists(path):
83+
# self.pod.write_yaml(path, {})
84+
# doc = collection.create_doc(basename, fields=fields, body=body)
85+
# new_pod_paths.append(doc.pod_path)
86+
# self.pod.logger.info('Saved -> {}'.format(doc.pod_path))
87+
8388
pod_paths_to_delete = set(existing_pod_paths) - set(new_pod_paths)
8489
for pod_path in pod_paths_to_delete:
8590
self.pod.delete_file(pod_path)
8691
self.pod.logger.info('Deleted -> {}'.format(pod_path))
8792

8893
def run(self, *args, **kwargs):
89-
request = self.cda.fetch(resources.Entry)
90-
if self.config.limit:
91-
request.params['limit'] = self.config.limit
92-
entries = request.all()
9394
for binding in self.config.bind:
94-
self.bind_collection(entries, binding.collection,
95-
binding.contentModel)
95+
content_type = binding.content_type
96+
entries = self.client.entries({
97+
'content_type': content_type,
98+
})
99+
self.bind_collection(entries, binding.collection)
96100

97101
@property
98102
@utils.memoize
99-
def cda(self):
103+
def client(self):
100104
"""Contentful API client."""
101-
endpoint = None
102-
token = self.config.keys.production
103-
# Use preview endpoint if preview key is provided.
104-
if self.config.keys.preview:
105-
token = self.config.keys.preview
106-
endpoint = ContentfulPreprocessor._preview_endpoint
107-
return client.Client(self.config.space, token, endpoint=endpoint)
105+
access_token = self.config.access_token
106+
if self.config.preview:
107+
api_url = 'preview.contentful.com'
108+
return contentful.Client(self.config.space, access_token, api_url=api_url)
109+
return contentful.Client(self.config.space, access_token)
108110

109111
def can_inject(self, doc=None, collection=None):
110112
if not self.injected:

example/.podcache.yaml

-2
This file was deleted.

example/podspec.yaml

+2-6
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,7 @@ preprocessors:
77
autorun: true
88
inject: true
99
space: cfexampleapi
10-
keys:
11-
# preview: exampleContentfulPreviewKey
12-
production: b4c0n73n7fu1
10+
access_token: b4c0n73n7fu1
1311
bind:
14-
- collection: /content/city/
15-
contentModel: city
1612
- collection: /content/cat/
17-
contentModel: cat
13+
content_type: cat

setup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,6 @@
1212
'contentful_ext',
1313
],
1414
install_requires=[
15-
'contentful.py==0.9.3',
15+
'contentful==1.10.2',
1616
],
1717
)

0 commit comments

Comments
 (0)