class ConfigType(StructuredNode, models.Node): """ config type model """ configtype_id = UniqueIdProperty() configtype_name = StringProperty() app_use = RelationshipFrom("App", "USE")
class Genre(StructuredNode): name = StringProperty(unique_index=True) product = RelationshipFrom('Product', 'GENRE')
class Type(StructuredNode): name = StringProperty(unique_index=True) product = RelationshipFrom('Product', 'TYPE')
class Track(BillboardNode): ''' Represents a Track from Billboard ''' spotify = RelationshipFrom('model.graph.genius.track.Track', 'RANKED AS') # artists = RelationshipTo('model.graph.spotify.artist.Artist', 'BY', model=Credited) credited_artists = RelationshipTo('model.graph.billboard.artist.Artist', 'PERFORMED BY', model=Credited) credited_writers = RelationshipTo('model.graph.billboard.writer.Writer', 'WRITTEN BY', model=Credited) credited_producers = RelationshipTo('model.graph.billboard.producer.Producer', 'PRODUCED BY', model=Credited) publishers = RelationshipTo('model.graph.billboard.publisher.Publisher', 'PUBLISHED BY', model=Credited) labels = RelationshipTo('model.graph.billboard.label.Label', 'DISTRIBUTED BY', model=Credited) rank = IntegerProperty() title_id = IntegerProperty(unique_index=True) title = StringProperty() imprint = StringProperty() label = StringProperty() feature_code = StringProperty() history = JSONProperty() bullets = JSONProperty() awards = JSONProperty() bdssongid = IntegerProperty(unique_index=True) title_vevo_id = StringProperty() title_brightcove_id = FloatProperty() title_content_url = StringProperty() title_images = JSONProperty() title_brightcove_data = JSONProperty() brightcove_data = JSONProperty() content_url = StringProperty() canonical = StringProperty(unique_index=True) peak_date_formatted = JSONProperty() peak_date_link = StringProperty() @classmethod def exists(cls, identifier): return cls.nodes.get_or_none(title_id=identifier.get('title_id')) @classmethod def inst(cls, **kwargs): tor = cls.build(cls, {'title_id': kwargs['title_id']}, **kwargs) return tor @classmethod def clean(cls, **kwargs) -> Tuple[StructuredNode, Dict[str, dict]]: print(kwargs['awards']) to_del = [key for key in kwargs.keys() if 'unnamed' in key.lower() or 'artist_' in key.lower()] to_eval = ('history', 'credited_artists', 'credited_writers', 'credited_producers', 'awards', 'title_images', 'publishers', 'title_brightcove_data', 'brightcove_data', 'peak_date_formatted', 'labels') for val in to_eval: kwargs[val] = literal_eval(kwargs[val]) actually_nodes = ('credited_artists', 'credited_writers', 'credited_producers', 'publishers', 'labels') to_connect = {} for node in actually_nodes: to_connect[node] = kwargs.pop(node) return cls(**kwargs), to_connect @staticmethod def post_clean(obj, to_connect: dict) -> StructuredNode: actually_nodes = ('credited_artists', 'credited_writers', 'credited_producers', 'publishers', 'labels') node_classes = (Artist, Writer, Producer, Publisher, Label) artists = ', '.join(list(map(lambda x: x['artist_name'], sorted(to_connect['credited_artists'], key=lambda x: x['ordinal'])))) for cls, node_name in zip(node_classes, actually_nodes): node = to_connect[node_name] for item in node: if 'credit' not in item: item['credit'] = 1 if 'ordinal' not in item: item['ordinal'] = 1 if 'seq' in item and 'ordinal' not in item: item['ordinal'] = item['seq'] print("ITEM", item) credit = item.pop('credit') ordinal = item.pop('ordinal') item = cls.inst(**item) if node_name == 'credited_artists': obj.credited_artists.connect(item, {'credit': credit, 'ordinal': ordinal}) if node_name == 'credited_writers': obj.credited_writers.connect(item, {'credit': credit, 'ordinal': ordinal}) if node_name == 'credited_producers': obj.credited_producers.connect(item, {'credit': credit, 'ordinal': ordinal}) if node_name == 'publishers': obj.publishers.connect(item, {'credit': credit, 'ordinal': ordinal}) if node_name == 'labels': obj.labels.connect(item, {'credit': credit, 'ordinal': ordinal}) search_str = obj.title + ' ' + artists genius_resp = Genius.search(search_str) print('\n\nSearching for:', search_str) if genius_resp['meta']['status'] != 200: raise ValueError('Probably exceeded Genius limits or invalid search') genius_resp = genius_resp['response']['hits'] for hit in genius_resp[:1]: hit = hit['result'] song_data = Genius.get_song(hit['id'])['response']['song'] genius_node = GeniusTrack.inst(**song_data) print("song data", song_data) if 'spotify' in [a['provider'] for a in song_data['media']]: print('Spotify exists!') for i, a in enumerate(song_data['media']): print(a) if a['provider'] == 'spotify': print('Spotify Exists -', song_data['full_title']) spotify_data = Spotify.get_track(song_data['media'][i]['native_uri']) print(spotify_data) break return obj
class Repo(StructuredNode, models.Node): """Repo Model""" repo_id = IntegerProperty() name = StringProperty() users = RelationshipFrom("User", "event", cardinality=ZeroOrMore)
class Topic(StructuredNode): uid = UniqueIdProperty() name = StringProperty(max_length=120, required=True) tagged_in_blog = RelationshipFrom("Blog", "TAGGED_TOPIC", model=TaggedRel)
class Person(StructuredNode): name = StringProperty(unique_index=True) pets = RelationshipFrom('Dog', 'owner')
class Complex(Mixin, StructuredNode, metaclass=ExtNodeMeta): """ Gate object for join Molecules from CGRdb with EquilibriumState`s """ signature = StringProperty(unique_index=True, required=True) # signature of Complex energy = FloatProperty() brutto = RelationshipFrom('Brutto', 'B2C', cardinality=One) molecules = RelationshipFrom( 'Molecule', 'M2C', model=Mapping) # mapping of Molecules in db into Complex equilibrium_states = RelationshipFrom( 'EquilibriumState', 'E2C', model=Mapping) # mapping of ES into complex reactant = RelationshipTo('Reaction', 'C2R', model=M_and_B) product = RelationshipFrom('Reaction', 'R2C', model=M_and_B) def __init__(self, structure: MoleculeContainer = None, **kwargs): if structure is not None: se = structure.meta['energy'] # load ES first for validation e = EquilibriumState(structure) super().__init__(signature=str(structure), energy=se) try: self.save() except UniqueProperty: # already exists self.id = self.nodes.get(signature=str(structure), lazy=True) # get id of existing node self.refresh() # new lowest ES found if self.energy > se: # this can break existing reaction barriers values! # check ES is new if self.equilibrium_states.is_connected(e): raise ValueError( 'same EquilibriumState with different energy exists' ) self.energy = se self.save() self.equilibrium_states.connect( e, { 'mapping_json': next(structure.get_mapping(self.structure)) }) elif not self.equilibrium_states.is_connected( e): # only new ES need connection from complex. self.equilibrium_states.connect( e, { 'mapping_json': next(structure.get_mapping(self.structure)) }) else: # new complex. store relations into CGRdb and Brutto self.brutto.connect(Brutto(structure)) # create mapping into molecules for s in structure.split(): m = Molecule(s) self.molecules.connect( m, {'mapping_json': next(m.structure.get_mapping(s))}) # store ES as-is self.equilibrium_states.connect( e, {'mapping_json': {n: n for n in structure}}) self.__es__ = e else: super().__init__(**kwargs) def get_effective_paths(self, target: 'Complex', limit: int = 10, max_path=30): if not limit: raise ValueError('limit should be positive') paths = [] for n, path in enumerate(self.search_path(target, limit)): nodes = [] costs = [] total = 0 for i, (node, barrier) in enumerate(path, start=1): nodes.append(node) costs.append(barrier) if i % 2 == 0 else costs.append(0) total += costs[-1] paths.append(weighted_path(nodes, costs, total)) if n == max_path: return paths return paths def search_path(self, target: 'Complex', max_len=10): seen = set() seen.add(self) final_compl = set() final_compl.add(target) cur_compl = seen - final_compl final_compl -= seen if not final_compl: return queue = [] n = count() for x in cur_compl: heappush(queue, (1, 0, next(n), [(x, 0)])) old_len = 1 new_seen = set() while queue: level, prev_barrier, _, init_path = heappop(queue) cur = init_path[-1][0] if len(init_path) != old_len: seen.update(new_seen) old_len = len(init_path) cur_len = len(init_path) + 1 < max_len for i, r in enumerate(cur.reactant.all()): barrier = (r.energy - cur.energy) # * 627.51 # barrier = barrier if barrier > prev_barrier else prev_barrier prod = r.product.all()[0] if prod in final_compl: path = init_path.copy() path.append((r, barrier)) path.append((prod, barrier)) yield path elif cur_len and prod not in seen: new_seen.add(prod) path = init_path.copy() path.append((r, barrier)) path.append((prod, barrier)) heappush(queue, (len(path), barrier, next(n), path)) @property @db_session def structure(self): structure = [] for m in set(self.molecules.all()): s = m.structure for r in self.molecules.all_relationships(m): structure.append(s.remap(r.mapping, copy=True)) return reduce(or_, structure) def depict(self): s = self.structure s.clean2d() return s.depict() def depict3d(self, index: int = 0) -> str: s = self.structure es = self.equilibrium_states.all()[index] mapping = self.equilibrium_states.relationship(es).mapping s._conformers.append({mapping[n]: v for n, v in es.xyz.items()}) return s.depict3d() def view3d(self, index: int = 0, width='600px', height='400px'): """ Jupyter widget for 3D visualization. :param index: index of conformer :param width: widget width :param height: widget height """ return JupyterWidget(self.depict3d(index), width, height) def _repr_svg_(self): return self.depict() def __str__(self): return str(self.structure) __es__ = None # ad-hoc for storing associated ES
class Reaction(Mixin, StructuredNode, metaclass=ExtNodeMeta): signature = StringProperty(unique_index=True, required=True) # signature of ES2ES CGR energy = FloatProperty() brutto = RelationshipFrom('Brutto', 'B2R', cardinality=One) transition_states = RelationshipFrom('TransitionState', 'T2R', model=Mapping) reactant = RelationshipFrom('Complex', 'C2R', cardinality=One, model=M_and_B) product = RelationshipFrom('Complex', 'R2C', cardinality=One, model=M_and_B) def __init__(self, structure: ReactionContainer = None, **kwargs): """ :param structure: ReactionContainer. In reactants and products contain ES`s. In reagents contains TS. ES`s and TS contains metadata key: energy with float value. """ if structure is not None: r = structure.reactants[0] p = structure.products[0] t = structure.reagents[0] te = t.meta['energy'] # store TS ans ES's first for validation ts = TransitionState(t) rc = Complex(r) pc = Complex(p) re = rc.__es__ pe = pc.__es__ cgr = r ^ p super().__init__(signature=str(cgr), energy=te) try: self.save() except UniqueProperty: # reaction already exists self.id = self.nodes.get(signature=str(cgr), lazy=True) # get id of existing node self.refresh() if self.energy > te: # lower TS found. update barriers. if self.transition_states.is_connected(ts): raise ValueError( 'same TransitionState with different energy exists' ) self.energy = te self.save() self.transition_states.connect(ts, { 'mapping_json': next(cgr.get_mapping(self.structure)) }) # new barriers! self.reactant.relationship(rc).energy = te - rc.energy self.product.relationship(pc).energy = te - pc.energy elif not self.transition_states.is_connected( ts): # skip already connected TS self.transition_states.connect(ts, { 'mapping_json': next(cgr.get_mapping(self.structure)) }) else: # new reaction # store relation to Brutto self.brutto.connect(Brutto(t)) # connect reactant and product complexes. self.reactant.connect( rc, { 'mapping_json': next(rc.structure.get_mapping(r)), 'energy': te - rc.energy }) self.product.connect( pc, { 'mapping_json': next(pc.structure.get_mapping(p)), 'energy': te - pc.energy }) # connect TS to R self.transition_states.connect( ts, {'mapping_json': {n: n for n in t}}) # connect new TS to new ES`s if not ts.equilibrium_states.is_connected( re): # skip already connected TS-ES ts.equilibrium_states.connect(re, {'energy': te - re.energy}) if not ts.equilibrium_states.is_connected( pe): # skip already connected TS-ES ts.equilibrium_states.connect(pe, {'energy': te - pe.energy}) else: super().__init__(**kwargs) @property @db_session def structure(self): r = self.reactant.single() p = self.product.single() r = r.structure.remap(self.reactant.relationship(r).mapping, copy=True) p = p.structure.remap(self.product.relationship(p).mapping, copy=True) return r ^ p def depict(self): s = self.structure s.clean2d() return s.depict() def depict3d(self, index: int = 0) -> str: s = self.structure ts = self.transition_states.all()[index] mapping = self.transition_states.relationship(ts).mapping s._conformers.append({mapping[n]: v for n, v in ts.xyz.items()}) return s.depict3d(index) def view3d(self, index: int = 0, width='600px', height='400px'): """ Jupyter widget for 3D visualization. :param index: index of conformer :param width: widget width :param height: widget height """ return JupyterWidget(self.depict3d(index), width, height) def _repr_svg_(self): return self.depict() def __str__(self): return str(self.structure)
class Group(StructuredNode, GroupInterface): """ A Group node provides access to certain functionality for associated apps """ STATUSES = {'ENABLED': 'Enabled', 'DISABLED': 'Disabled'} # properties uid = StringProperty(unique_index=True, default=generate_uuid4) name = StringProperty(required=True) status = StringProperty(default="ENABLED", choices=STATUSES) created_at = DateTimeProperty(default_now=True) modified_at = DateTimeProperty(default_now=True) description = StringProperty() application_id = StringProperty(required=True) # relationships # incoming relationships users = RelationshipFrom('.user.User', 'IN_GROUP') # outgoing relationships data = RelationshipTo('.data.Data', 'HAS_DATA') application = RelationshipTo('.application.Application', 'HAS_APPLICATION', cardinality=One) def to_object(self, user_flag=False, *args, **kwargs) -> EGroup: group = EGroup(uid=self.uid, name=self.name, description=self.description, status=self.status, application=self.application_id, created_at=self.created_at, modified_at=self.modified_at) group.data = {x.to_object() for x in self.data.all()} if user_flag: group.users = {x.to_object() for x in self.users.all()} group._object = self return group @staticmethod def get_all(user_flag=False, limit=25, offset=0, order_by='name', *args, **kwargs) -> set: orgs = [ x.to_object(user_flag=user_flag) for x in Group.nodes.order_by(order_by)[offset:offset + limit] ] return orgs @staticmethod def get_by_uid(uid, user_flag=False, *args, **kwargs) -> EGroup: """ Retrieve a Group based on its ID :param uid: :return: """ o = None _o = Group.nodes.get_or_none(uid=uid) if _o: o = _o.to_object(user_flag=user_flag) return o @staticmethod def get_by_uids(uids, user_flag=False, *args, **kwargs) -> SetGroup: """ Retrieve a set of Groups based on its ID :param uids: :return: """ if not uids: return set() _groups = Group.nodes.filter(uid__in=tuple(uids)) return {o.to_object(user_flag=user_flag) for o in _groups} @staticmethod def create_from_object(o: EGroup) -> EGroup: """ Group names are unique within an Application - so we need to first check that we dont' already have a group with the same name in the specified application. We'll connect it to this application, so no skin off our teeth to pull it here either. :param o: :return: """ _app = Application.nodes.get(uid=o.application) for group in _app.groups.all(): if group.name == o.name.strip(): raise Exception( "A Group with this name already exists for this Application" ) with db.transaction: _o = Group(uid=o.uid or generate_uuid4(), name=o.name, description=o.description, application_id=o.application, status=o.status, created_at=o.created_at, modified_at=o.modified_at) _o.save() _o.application.connect(_app) # attach any data nodes for x in o.data: _data = Data(key=x.key, value=x.value) _data.save() _data.group.connect(_o) return _o.to_object() @staticmethod def get_object(o: EGroup): if not o._object: o._object = Group.nodes.get( uid=o.uid) # will raise exception if not found return o._object @staticmethod def update_from_object(o: EGroup) -> EGroup: if not o.edits: return o _o = Group.get_object(o) _app = _o.application.get() if 'name' in {s[0] for s in o.edits}: for group in _app.groups.all(): if group.name == o.name.strip() and group.uid != _o.uid: raise Exception( "A Group with this name already exists for this Application" ) with db.transaction: local_fields = {'name', 'description', 'status'} local_field_edits = {(s[0], s[1]) for s in o.edits if s[0] in local_fields} if local_field_edits: for field, new_value in local_field_edits: setattr(_o, field, new_value) _o.modified_at = datetime.datetime.now() _o.save() foreign_fields = { 'data', } foreign_field_edits = { s[0]: s[1] for s in o.edits if s[0] in foreign_fields } if foreign_field_edits: # CRUD on data Data.update_data_nodes(foreign_field_edits.get('data'), _o, 'group') return _o.to_object() @staticmethod def delete_from_object(o: EGroup) -> bool: _o = Group.get_object(o) with db.transaction: # delete associated data nodes first: for data in _o.data.all(): data.delete() _o.delete() return True
class Pet(StructuredNode, models.Node): """Pet model""" pet_id = UniqueIdProperty() name = StringProperty() owner = RelationshipFrom("Person", "HAS_PET")
class Organisation(StructuredNode): name = StringProperty() ORG_NAME = StringProperty(unique_index=True, required=True) LEAD_ARCH = StringProperty() ORG_TYPE = StringProperty() bef = RelationshipFrom('BusinessCapability', 'BEF')
class Country(StructuredNode): code = StringProperty(unique_index=True, required=True) # traverse incoming IS_FROM relation, inflate to Person objects inhabitant = RelationshipFrom('Person', 'IS_FROM')
class Meal_Type(StructuredNode): name = StringProperty(unique_index=True, label="meal_type") description = StringProperty(unique_index=False) meals = RelationshipFrom("Meal", IS_A_MEAL_TYPE_RELATIONSHIP)
class Person(StructuredNode): name = StringProperty(unique_index=True) ownership = RelationshipFrom('DataObject', 'IS_OWNED_BY')
class ArticleNode(StructuredNode): properties = JSONProperty() article_id = StringProperty() article_title = StringProperty() links_to = RelationshipTo('ArticleNode', 'LINKS TO') linked_from = RelationshipFrom('ArticleNode', 'LINKED FROM') article = None def update_article(self, article: WikipediaArticle) -> None: """ Sets the article field. :param article: the article to set the article field to. """ self.article = article @staticmethod def connect() -> None: """" Connects to the Neo4J instance """ user, pw, host, bolt_port = [N4J_CONF[a] for a in ['user', 'pass', 'host', 'bolt_port']] connection_url = f'bolt://{user}:{pw}@{host}:{bolt_port}' logger.debug(f'Connecting to Neo4J: {connection_url}') db.set_connection(connection_url) @classmethod def clear(cls): cls.connect() query_txt = "MATCH (n) DETACH DELETE n;" logger.debug(f'Executing clear: {query_txt}') db.cypher_query(query_txt) @classmethod def add_node(cls, article: WikipediaArticle) -> ArticleNode: ''' Adds or gets a node to the Neo4J Database by creating a node and storing all its properties as JSON data :param article: the article to add :returns: the node to use so edges can be added ''' cls.connect() properties = article.infobox article_id = article.article_url title = article.article_title # node = cls.nodes.get_or_none(article_id=article_id) results, meta = db.cypher_query("""MATCH (s) WHERE s.article_id = '""" + article_id + """' RETURN s""") nodes = [cls.inflate(row[0]) for row in results] if nodes: nodes[0].article = article return nodes[0] node = cls(article_id=article_id, article_title=title, properties=properties) # vars() converts a class to JSON data node.save() # Pushes node to the db node.article = article return node @classmethod def retrieve_node(cls, article: WikipediaArticle) -> ArticleNode: results, meta = db.cypher_query("""MATCH (s) WHERE s.article_id = '""" + article.article_url + """' RETURN s""") nodes = [cls.inflate(row[0]) for row in results] if nodes: return nodes[0] # @classmethod # def retrieve_edge(cls, source_article: ArticleNode, dest_article: ArticleNode): # results, meta = db.cypher_query('MATCH (t:Track {spotify_id: "%s"})-[:`FEATURED IN`]->(p:Playlist) RETURN p' # % spotify_id) # return [Playlist.inflate(row[0]) for row in results] @classmethod def add_edge(cls, source_article: ArticleNode, dest_article: ArticleNode) -> None: """ Connects one node to another :param source_article: the article pointing to the destination :param dest_article: the destination article to be pointed to """ cls.connect() source_article.links_to.connect(dest_article) def category(cls): """Performs same functionality as inherited class""" super().category(cls)
class Shop(Location): liked_by = RelationshipFrom("Traveller", "LIKES_SHOP", model=LikesRel) reviewed_by = RelationshipFrom("Traveller", "REVIEWED_SHOP", model=ReviewedRel) owned_by = RelationshipFrom("ShopOwner", "OWNS_SHOP", model=OwnsRel) visited_by = RelationshipFrom("Traveller", "VISITED_SHOP", model=VisitedRel)
class Country(StructuredNode): code = StringProperty(unique_index=True, required=True) inhabitant = RelationshipFrom('Person', 'IS_FROM')
class Coffee(StructuredNode): name = StringProperty(unique_index=True) price = IntegerProperty() suppliers = RelationshipFrom(Supplier, 'COFFEE SUPPLIERS', model=SupplierRel)
class Advisory(EstuaryStructuredNode): """Definition of an Errata advisory in Neo4j.""" class BuildAttachedRel(StructuredRel): """Definition of a relationship between an Advisory and a KojiBuild attached to it.""" time_attached = DateTimeProperty() actual_ship_date = DateTimeProperty() advisory_name = StringProperty(unique=True, index=True) created_at = DateTimeProperty() id_ = UniqueIdProperty(db_property='id') issue_date = DateTimeProperty() product_name = StringProperty() release_date = DateTimeProperty() security_impact = StringProperty() security_sla = DateTimeProperty() state = StringProperty() status_time = DateTimeProperty() synopsis = StringProperty() update_date = DateTimeProperty(index=True) assigned_to = RelationshipTo('.user.User', 'ASSIGNED_TO', cardinality=ZeroOrOne) attached_bugs = RelationshipTo('.bugzilla.BugzillaBug', 'ATTACHED') attached_builds = RelationshipTo('.koji.KojiBuild', 'ATTACHED', model=BuildAttachedRel) reporter = RelationshipTo('.user.User', 'REPORTED_BY', cardinality=ZeroOrOne) triggered_freshmaker_event = RelationshipFrom( '.freshmaker.FreshmakerEvent', 'TRIGGERED_BY') @property def display_name(self): """Get intuitive (human readable) display name for the node.""" return self.advisory_name @property def timeline_datetime(self): """Get the DateTime property used for the Estuary timeline.""" return self.created_at @classmethod def attached_build_time(self, advisory, build): """ Get the time that a build related to the advisory was attached. :param node build: a Neo4j node representing an attached build :return: the time the build was attached :rtype: datetime object """ rel = advisory.attached_builds.relationship(build) if rel: return rel.time_attached else: return None @classmethod def find_or_none(cls, identifier): """ Find the node using the supplied identifier. :param str identifier: the identifier to search the node by :return: the node or None :rtype: EstuaryStructuredNode or None """ if re.match(r'^\d+$', identifier): # The identifier is an ID return cls.nodes.get_or_none(id_=identifier) elif re.match(r'^RH[A-Z]{2}-\d{4}:\d+-\d+$', identifier): # The identifier is a full advisory name return cls.nodes.get_or_none(advisory_name=identifier) elif re.match(r'^RH[A-Z]{2}-\d{4}:\d+$', identifier): # The identifier is most of the advisory name, so return the latest iteration of this # advisory return cls.nodes.filter(advisory_name__regex=r'^{0}-\d+$'.format(identifier))\ .order_by('advisory_name').first_or_none() else: raise ValidationError( '"{0}" is not a valid identifier'.format(identifier))
class Question(StructuredNode): question_id = UniqueIdProperty() title = StringProperty(required=True) options = RelationshipFrom('App.models.Option', 'FOR_QUESTION', cardinality=OneOrMore)
class BaseTask(StructuredNode): # __primarykey__="Task_id" Task_id = UniqueIdProperty journey_id = StringProperty(unique_index=True) task_version = StringProperty(unique_index=True) created_on = DateTimeProperty() updated_on = DateTimeProperty() task_type = StringProperty() task_params = JSONProperty() meta_data = JSONProperty() unlock_criteria = RelationshipFrom("BaseTask", "UNLOCK_CRITERIA", model=BaseCriteria) def run(self, *args, **kwargs): """ Wrapper over Execute """ try: dt = datetime.datetime.now().timestamp() result = self.execute(*args, **kwargs) de = datetime.datetime.now().timestamp() send_to_stream( "RUN_TASK_EXECUTE", { 'event_time': dt, 'execution_data': result, 'execute_time': dt - de, }) return result except Exception as e: send_to_stream("ERROR_TASK_EXECUTE", {'stack_trace': e}) def execute(self, *args, **kwargs): pass """ Function to override and execute """ @classmethod def createNode(cls, **kwargs): task = cls() task.Task_id = uuid4() task.journey_id = kwargs.get('journey_id', uuid4()) task.created_on = datetime.datetime.now() task.updated_on = datetime.datetime.now() task.unlock_criteria = kwargs.get("unlock_criteria", { 'criteria': 'eq', 'params': { 'left': 1, 'right': 1 }, 'right': 'a' }) if kwargs.get('meta'): task.meta = kwargs.get('meta', {}) task.save() return task @classmethod def updateNode(cls, **kwargs): task = cls.nodes.get(id=kwargs.get("Task_id")) task.updated_on = datetime.datetime.now() if kwargs.get('meta'): task.meta = kwargs.get('meta', {}) task.save() return task @classmethod def deleteNode(cls, **kwargs): task = cls.nodes.get(Task_id=kwargs.get("Task_id")) task.delete() return None @classmethod def replaceNode(cls, **kwargs): task_to_replace = cls.nodes.get(Task_id=kwargs.get("id_1")) task_to_replace_with = cls.nodes.get(Task_id=kwargs.get("id_2")) t2 = task_to_replace_with task_to_replace.delete() t2.Task_id = kwargs.get("id_1") t2.save() task_to_replace_with.delete() return t2
class ProductionCountry(StructuredNode): iso_3166_1 = StringProperty(unique_index=True) name = StringProperty() produced = RelationshipFrom(".movie.Movie", "PRODUCED_IN")
class Seat(StructuredNode): ticket_id = UniqueIdProperty() seat_id = StringProperty(required=True, max_length=SEAT_ID_MAX_LEN) match = RelationshipTo('Match', 'FOR', cardinality=One) user = RelationshipFrom('User', 'RESERVED_A', cardinality=One)
class Country(StructuredNode): name = StringProperty(unique_index=True) product = RelationshipFrom('Product', 'FILMED_IN')
class ServerSettings(Settings): server = RelationshipFrom('app.dal.nodes.server.Server', 'SETTINGS', One) blocklisted_users = RelationshipTo('UserSettings', 'BLOCKLIST')
class Rating(StructuredNode): name = StringProperty(unique_index=True) product = RelationshipFrom('Product', 'RATING')
class UserSettings(Settings): user = RelationshipFrom('app.dal.nodes.user.User', 'SETTINGS', One) disabled_servers = RelationshipTo('ServerSettings', 'DISABLED')
class Director(StructuredNode): name = StringProperty(unique_index=True) product = RelationshipFrom('Product', 'DIRECTED_BY')
class Collection(StructuredNode): uid = StringProperty(unique_index=True) open = BooleanProperty() service = RelationshipFrom(Service, "Role", model=Role) user = RelationshipFrom(User, "Role", model=Role)