def create_webhooks(self, publishable): if not isinstance(publishable, (Publishable, PretendPublishable)): raise Exception( 'You can only create webhooks for objects that inherit from ' 'Publishable or PretendPublishable') obj = publishable.published_object() obj_id = obj.pk obj_type = ContentType.objects.get_for_model(type(obj)) payload = json.dumps(to_json_dict(publishable)) for api_key_type in api_key_types(): allowed_keys = publishable.allowed_api_keys(api_key_type) if allowed_keys is None: raise Exception(( 'Apparently I dont know how to check which {} have access to ' 'this {}').format(api_key_type, publishable.__class__)) for api_key in allowed_keys: webhook_url = api_key.webhook_url if not webhook_url: continue # Let's say I just always send a webhook any time an object saves. Then # let's say the customer writes code that accepts any webhook, and # saves to their database. Then let's say the customer writes code # that, any time an object saves, saves to our API. Infinite loop. So # only send a webhook if the object actually changed since the last # webhook. latest = self.latest(obj_id, obj_type, webhook_url) if latest and latest.payload == payload: continue self.create(obj_id=obj_id, obj_type=obj_type, payload=payload, webhook_url=webhook_url)
def paged_results(model, query, page): count = query.count() total_pages = math.ceil(1.0 * count / USE_PAGE_SIZE) page = page or USE_FIRST_PAGE results = [] from_row = (page - 1) * USE_PAGE_SIZE to_row = page * USE_PAGE_SIZE for obj in query.order_by('pk')[from_row:to_row]: results.append(to_json_dict(obj, model)) return construct_paged_results(results, count, page, total_pages)
def get_or_save_existing(request, api_key, model_name, pk): model = get_publishable_model(model_name) filters = get_filters(model, request.GET) filter_field_names = [f.filter_field.name for f in filters] if filter_field_names: raise Problem(( 'When getting or saving a single {}, no filters are valid. You ' 'specified {}').format(model_name, ', '.join(filter_field_names)), 400) instance = get_instance(model_name, model.objects, pk, api_key) if request.method == 'POST': update(instance, get_posted_json(request), api_key) elif request.method == 'DELETE': instance.mark_deleted() return to_json_dict(instance, model)
def list_or_save_new(request, api_key, model_name): model = get_publishable_model(model_name) if request.method == 'GET': return paged_results( model, filter_model(model, api_key, request.GET), page=get_page(request.GET)) elif request.method in ['POST', 'PUT']: data = get_posted_json(request) if 'id' in data: raise Problem( 'When saving a new {}, you should not specify an id'.format( model_name)) instance = save_new(model, data, api_key) return to_json_dict(instance, model) else: raise Problem(( 'This API endpoint is not sure what to do with the {} ' 'request method').format(request.method))
def ajax_get(request): return to_json_dict(get_request_ajax_obj(request))