def _convert_xml_node(self, node): """INTERNAL: convert a single XML node to a Resource.""" type = node.attrib['Type'] if type in ('System.Int32', 'System.Int64'): return int(node.text) elif type == 'System.Boolean': return node.text == 'True' elif type == 'System.String': return node.text elif type == 'System.Version': # Why isn't this done automatically?? parts = map(int, node.text.split('.')) items = zip(('Major', 'Minor', 'Build', 'Revision'), parts) resource = Resource('version', items) return resource elif type.startswith('System.'): return node.text elif type.startswith('RhevmCmd.'): type = type[9:] if type.startswith('CLI'): type = type[3:] resource = Resource(type.lower()) for child in node: resource[child.attrib['Name']] = self._convert_xml_node(child) return resource elif type.startswith('VdcDAL.'): return self._convert_xml_node(node[0]) elif type.endswith('[]'): result = [] for child in node: result.append(self._convert_xml_node(child)) return result elif type: raise ParseError, 'Unknown type: %s' % type
def create_resource_from_entity(e, verbose=False): """ Create a Rest Resource from a datastore entity TODO: We don't care about verbosity just yet """ return Resource(e, REST_RULES).to_dict()
def _post(self): """ Create a Post """ post = posts_api.create_post(self.cleaned_data) self.serve_success(Resource(post, REST_RULES).to_dict())
def _post(self): """ Create a Post """ category = posts_api.create_post_category(self.cleaned_data) self.serve_success(Resource(category, CATEGORY_REST_RULES).to_dict())
def validate_payload(self): # aka Form.clean """ Validate the request payload against the rest rules This only works for a single payload entity, not a list... """ rules = self.get_rules() self.cleaned_data = Resource(None, rules).from_dict(self.data)
def __construct_resource(loader, node): """YAML constructor that constructs a Resource.""" if isinstance(node, yaml.MappingNode): mapping = loader.construct_mapping(node) resource = Resource(node.tag[1:], mapping) else: resource = loader.construct_undefined(node) return resource
def _post(self): """ Create a User TODO: Needs admin decorator """ e = auth_api.create_user(self.cleaned_data) self.serve_success(Resource(e, REST_RULES).to_dict())
def _get(self, resource_id): """ Get a post by resource id Note: To get a post by slug id, hit collection endpoint (/?get_by_slug=slug) """ post = posts_api.get_post_by_resource_id(resource_id) self.serve_success(Resource(post, REST_RULES).to_dict())
def handle(self, exception): if not isinstance(exception, ArgProcError): return exception format = FormatEntity() error = Resource('error') error['id'] = 'rest.entity_error' error['message'] = str(exception) body = format.filter(error) headers = response.headers raise HTTPReturn(http.BAD_REQUEST, headers=headers, body=body)
def _get(self, resource_id): f_key = get_key_from_resource_id(resource_id) # TODO: Abstract this a bit more out into a rest-like service... f = f_key.get() if not f: raise Exception('File Not Found') self.serve_success(Resource(f, self.get_rules()).to_dict())
def handle(self, exception): if not isinstance(exception, PowerShellError): return exception format = FormatEntity() error = Resource('error') error['id'] = exception.id error['message'] = exception.message body = format.filter(error) headers = response.headers raise Error(http.BAD_REQUEST, headers=headers, body=body)
def _put(self, resource_id): """ Edit a User """ key = get_key_from_resource_id(resource_id) e = key.get() e = auth_api.edit_user(e, self.cleaned_data) self.serve_success(Resource(e, REST_RULES).to_dict())
def _get(self): # TODO: Abstract this a bit more out into a rest-like service... files = FileContainer.query().fetch(1000) resource_list = [] for f in files: resource_list.append(Resource(f, self.get_rules()).to_dict()) self.serve_success(resource_list)
def _put(self): # Note: At the moment this is doing a .put() for key/val pair e = set_global_settings(self.cleaned_data) # Step 3: Kill all related caches... # TODO: this should be signal or pub/sub ubercache.cache_invalidate('events') results = Resource(e, REST_RULES).to_dict() self.serve_success(results)
def _get(self): """ Get a list of Blog Posts """ entities = auth_api.get_users() # Create A set of results based upon this result set - iterator?? results = [] for e in entities: results.append(Resource(e, REST_RULES).to_dict()) self.serve_success(results)
def _put(self, resource_id): """ Edit a Post given by resource_id """ # First retrieve the post to edit post = posts_api.get_post_by_resource_id(resource_id) if not post: return self.serve_404('Resource given by resource id %s Not Found' % resource_id) post = posts_api.edit_post(post, self.cleaned_data) self.serve_success(Resource(post, REST_RULES).to_dict())
def _get_by_slug_or_404(self, slug): """ Given a slug, attempt to return slug resource or issue a 404 """ post = posts_api.get_post_by_slug(slug) if not post: self.serve_404('Resource given by slug %s Not Found' % slug) return # Found Post: Serve it up self.serve_success(Resource(post, REST_RULES).to_dict()) return
def _get(self): get_by_slug = self.cleaned_params.get('get_by_slug', None) if get_by_slug: category = posts_api.get_post_category_by_slug(get_by_slug) if not category: self.serve_404('Category given by slug %s Not Found' % get_by_slug) return else: self.serve_success(Resource(category, CATEGORY_REST_RULES).to_dict()) return # Refactor this... results = [] entities = BlogCategory.query().fetch(1000) for e in entities: results.append(Resource(e, CATEGORY_REST_RULES).to_dict()) cursor = None more = None self.serve_success(results, {'cursor': cursor, 'more': more})
def from_resource(self, obj, field): """ """ resource_id = super(FileField, self).from_resource(obj, self.resource_id_prop) if not resource_id: return None try: resource_key = get_key_from_resource_id(resource_id) except ValueError: logging.error('Invalid Resource Id %s' % resource_id) return None return Resource(resource_key.get(), REST_RESOURCE_RULES).to_dict()
def _post(self, resource_id): f_key = get_key_from_resource_id(resource_id) f = f_key.get() if not f: raise Exception('File Not Found') do_put = False # Only do put if something changed for prop, val in self.cleaned_data.items(): if getattr(f, prop) == val: continue do_put = True setattr(f, prop, val) if do_put: f.put() self.serve_success(Resource(f, self.get_rules()).to_dict())
def _convert(self, node, path=[]): """Convert an XML node into its native representation (a string, a list, or a Resource).""" if len(node) == 0: return node.text has_duplicates = len(set((child.tag for child in node))) != len(node) if has_duplicates or self.hints.get(path).get('sequence'): result = [] path.append(None) for ix, child in enumerate(node): path[-1] = '[%d]' % ix result.append(self._convert(child, path)) del path[-1] else: result = Resource(node.tag) path.append(None) for child in node: path[-1] = child.tag result[child.tag] = self._convert(child, path) del path[-1] return result
def get(self): """ Written Main Page Web Handler """ pagemeta = { 'title': 'Written', 'description': 'Writing and Critique', 'image': DEFAULT_POST_IMAGE } # TEMP: Get List of posts for serverside rendering entities, cursor, more = posts_api.get_posts(limit=25, cursor=None) posts_api.bulk_dereference_posts(entities) # Create A set of results based upon this result set - iterator?? results = [] for e in entities: results.append(Resource(e, REST_RULES).to_dict()) template_values = {'pagemeta': pagemeta, 'entities': results} self.render_template('./templates/v0/bloglist.html', template_values)
def _post(self): # TODO: Abstract this a bit more out into a rest-like service... resource = Resource(self.cleaned_data, self.get_rules()).to_dict() self.serve_success(resource)
def post(self): """ Callback for a successful upload... keep this lightweight """ fs = Filesystem(BUCKET_NAME) has_files = fs.get_uploads(self.request, 'the_file', populate_post=True) if has_files: file_info = has_files[0] original_filename = file_info.filename content_type = file_info.content_type size = file_info.size gs_object_name = file_info.gs_object_name # We could urlfetch this, but file not public blob_key = blobstore.create_gs_key(gs_object_name) data = fs.read(gs_object_name.replace('/gs', '')) # What we want to do now is create a copy of the file with our own info dest_filename = 'juniper/%s' % original_filename # Prep the file object file_obj = self.create_image(fs, data, dest_filename) file_obj_key = file_obj.key resource_id = get_resource_id_from_key(file_obj_key) # Finally delete the tmp file #data = fs.delete(gs_object_name.replace('/gs', '')) # "Return" a rest resource of sorts payload = { 'status': 200, 'messages': [], 'results': Resource(file_obj, REST_RESOURCE_RULES).to_dict() } self.response.set_status(200) self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps(payload)) # Handle Attachment to Resource # Do this in a deferred task? attach_to_resource_id = self.request.get('attach_to_resource', None) # TODO: This should be done in a txn - especially when there are multiple uploads if attach_to_resource_id: attachment_resource_key = get_key_from_resource_id( attach_to_resource_id) attachment_resource = attachment_resource_key.get() if not attachment_resource: raise Exception( 'Resource with key %s not found. File was uploaded...' % attach_to_resource_id) if not attachment_resource.attachment_resources: attachment_resource.attachment_resources = [] # Update attachments attachment_resource.attachment_resources.append(resource_id) target_property = self.request.get('target_property', None) if target_property: setattr(attachment_resource, target_property, resource_id) attachment_resource.put() return
def _get(self): """ Get a collection of Written Posts """ # Check if we want to get a post by its slug get_by_slug = self.cleaned_params.get('get_by_slug', None) if get_by_slug: return self._get_by_slug_or_404(get_by_slug) # Get a list of all posts limit = self.cleaned_params.get('limit', None) cursor = self.cleaned_params.get('cursor', None) start_date = self.cleaned_params.get('start_date', None) category_slug = self.cleaned_params.get('category_slug', None) optional_params = {} if 'is_published' in self.params: optional_params['is_published'] = self.cleaned_params['is_published'] if start_date: optional_params['start_date'] = start_date category_resource_id_filter = None if category_slug: category = posts_api.get_post_category_by_slug(category_slug) if not category: self.serve_404('Category with slug %s Not Found' % category_slug) return optional_params['category_resource_id'] = get_resource_id_from_key(category.key) # TODO: If you are not admin, default is_published to True... key_stamp = str(hash(json.dumps(self.params))) cache_key = 'written_resources_%s' % key_stamp cached_result = ubercache.cache_get(cache_key) if False and cached_result: results, cursor, more = cached_result else: # Posts were not Cached for this set of properties entities, cursor, more = posts_api.get_posts(limit=limit, cursor=cursor, **optional_params) posts_api.bulk_dereference_posts(entities) # Create A set of results based upon this result set - iterator?? results = [] for e in entities: results.append(Resource(e, REST_RULES).to_dict()) if cursor: cursor = cursor.urlsafe() # Store In Cache ubercache.cache_set(cache_key, (results, cursor, more), category='written') self.serve_success(results, {'cursor': cursor, 'more': more})
def _put(self, resource_id): e = posts_api.get_post_category_by_resource_id(resource_id) e = posts_api.edit_category(e, self.cleaned_data) self.serve_success(Resource(e, CATEGORY_REST_RULES).to_dict())
def _get(self, resource_id): post = posts_api.get_post_category_by_resource_id(resource_id) self.serve_success(Resource(post, CATEGORY_REST_RULES).to_dict())
def _get(self, resource_id): # Get a Public User Profile key = get_key_from_resource_id(resource_id) e = key.get() self.serve_success(Resource(e, REST_RULES).to_dict())
def _get(self): e = get_global_settings() results = Resource(e, REST_RULES).to_dict() self.serve_success(results)