def process_import(filepath, space_id, content_type_id, api_key): client = Client(api_key) space = client.entries(space_id) with open(filepath) as import_file: records = json.load(import_file) for record in tqdm(records): entry_id = None # tell server to auto-generate it entry_data = { 'content_type_id': content_type_id, 'fields': {key: { 'en-US': value } for (key, value) in record.items()} } try: entry = space.create(entry_id, entry_data) except Exception: print('Creation failed', json.dumps(record)) else: try: entry.publish() except Exception: pass
def test_client_not_raise_errors(self): client = Client(PLAYGROUND_KEY, raise_errors=False) error = client.entries(PLAYGROUND_SPACE, 'master').find('not_here') self.assertEqual(error.status_code, 404) self.assertEqual(error.response.status_code, 404)
def importDataV2(filename, space, environment, token): client = Client(token) with open(filename, 'r') as source: errors = list() reader = json.load(source) count = 0 for entry in reader['entries']: displayName = entry['fields']['title']['en-US'] if not 'content_type_id' in entry: entry['content_type_id'] = entry['sys']['contentType']['sys'][ 'id'] print("Importing " + displayName + '...') try: new_entry = client.entries(space, environment).create(None, entry) new_entry.publish() count = count + 1 except Exception: print("\tFailed. Moving on.") errors.append(displayName) print("Import complete. Successfully imported " + str(count) + "/" + str(count + len(errors)) + " items.") if len(errors) > 0: print("\nThe following items failed to create/publish:") for err in errors: print("\t" + err)
def test_client_with_additional_headers(self): client = Client(PLAYGROUND_KEY, raise_errors=False, additional_headers={'fizz': 'buzz'}) error = client.entries(PLAYGROUND_SPACE, 'master').find('abc123') self.assertIn('fizz', error.response.request.headers)
def save(self): cma = CMA(os.environ['CF_CMA_TOKEN']) entries_proxy = cma.entries(os.environ['CF_SPACE_ID']) entries = entries_proxy.all({ 'content_type': self.__class__.__CONTENT_TYPE__, 'fields.{0}'.format(self.__class__.__SEARCH_FIELD__): self._search_field() }) if entries: # We found a matching entry, therefore we don't do anything return False return entries_proxy.create( None, { 'content_type_id': self.__class__.__CONTENT_TYPE__, 'fields': self._create_fields() }).publish()
def run(): if len(sys.argv) < 4: helpText() sys.exit() contentful_space = sys.argv[1] contentful_environment = sys.argv[2] management_token = sys.argv[3] client = Client(management_token) space = client.spaces().find(contentful_space) question = "WARNING: This will delete ALL content in the '" + space.name + "' space under the '" + contentful_environment + "' environment. Are you sure you wish to continue?" if not confirmContinue(question): sys.exit() # API only fetches 100 entries at a time, so keep looping until we don't find any more. # This could cause an infinite loop if any entries fail to delete, but hey, this is just a convenience utility anyway. while True: try: print('Checking for entries...') entries = client.entries(contentful_space, contentful_environment).all() print('Found ' + str(len(entries)) + ' entries.') if len(entries) == 0: break for entry in entries: displayName = entry.title if hasattr(entry, 'title') else entry.name if hasattr(entry, 'name') else entry.sys['id'] if entry.is_published: print("Unpublishing " + displayName + "...") entry.unpublish() print("Deleting " + displayName + "...") entry.delete() except KeyboardInterrupt: print "\nInterrupted by user. Exiting." sys.exit() print("Complete.")
def delete(self, entry): cma = CMA(os.environ['CF_CMA_TOKEN']) entries_proxy = cma.entries(os.environ['CF_SPACE_ID']) entry = entries_proxy.find(entry.id) return entry.unpublish().delete()
import os import json import random import string import smtplib import dateutil.parser from datetime import datetime, timedelta, timezone from loader import load_env load_env() from contentful_management import Client as CMA CMA_CLIENT = CMA(os.environ['CF_CMA_TOKEN']) ENTRY_PROXY = CMA_CLIENT.entries(os.environ['CF_SPACE_ID'], 'master') def send_mail(user, password, to_mails, subject, body): message = 'From: {0}\nTo: {1}\nSubject: {2}\n\n{3}'.format( user, ", ".join(to_mails), subject, body) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(user, password) server.sendmail(user, to_mails, message) server.close() print('Email sent: {0}'.format(subject)) except Exception as e: print('Failed to send Email')
def runimport(): client = Client(management_token) with open(filename, 'rb') as f: reader = csv.reader(f) try: for row in reader: # skip header row if row[0] == '': continue category = getFunctionalCategory(row[1]) if category == "Invalid category": print "Invalid category - '" + row[ 1] + "'. Will not import row " + row[0] continue gc_date = None if row[20] != '': gc_date = formatDate(row[20]) revised_date = None if row[21] != '': revised_date = formatDate(row[21]) entry = { "content_type_id": "recordType", "fields": { "recordType": { "en-US": row[2] }, "category": { "en-US": { "sys": { "type": "Link", "linkType": "Entry", "id": category } } }, "scheduleId": { "en-US": row[3] }, "recordTypeDescription": { "en-US": row[4] }, "officialCopy": { "en-US": row[5] }, "retention": { "en-US": row[6] }, "triggerEvent": { "en-US": row[7] }, "disposition": { "en-US": row[8] }, "dispositionMethod": { "en-US": row[9] }, "referenceCopy": { "en-US": row[10] }, "referenceCopyDisposition": { "en-US": row[11] }, "referenceCopyDispositionMethod": { "en-US": row[12] }, "dataClassification": { "en-US": row[13] }, "storageRequirements": { "en-US": row[14] }, "legalReference": { "en-US": row[15] }, "notes": { "en-US": row[16] }, "systemOfRecord": { "en-US": row[17] }, "generalCounselNotes": { "en-US": row[18] }, "dateApprovedByGeneralCounsel": { "en-US": gc_date }, "dateRevised": { "en-US": revised_date } } } #print entry client.entries(contentful_space, 'master').create(None, entry) except csv.Error as e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
def test_client_raw_mode(self): client = Client(PLAYGROUND_KEY, raw_mode=True) response = client.entries(PLAYGROUND_SPACE, 'master').all() self.assertEqual(response.status_code, 200)