def show_families(): """ List of Families for menu(3) """ print(f"--- {request}") print(f"--- {user_session}") # Set context by owner and the data selections u_context = UserContext(user_session, current_user, request) # Which range of data is shown u_context.set_scope_from_request(request, 'person_scope') opt = request.args.get('o', 'father', type=str) u_context.order = 'man' if opt == 'father' else 'wife' count = request.args.get('c', 100, type=int) t0 = time.time() # 'families' has Family objects families = Family_combo.get_families(o_context=u_context, opt=opt, limit=count) stk_logger(u_context, f"-> bp.scene.routes.show_families/{opt} n={len(families)}") return render_template("/scene/families.html", families=families, user_context=u_context, elapsed=time.time() - t0)
def show_places(): """ List of Places for menu(4) """ t0 = time.time() print(f"--- {request}") print(f"--- {user_session}") # Set context by owner and the data selections u_context = UserContext(user_session, current_user, request) # Which range of data is shown u_context.set_scope_from_request(request, 'place_scope') u_context.count = request.args.get('c', 50, type=int) dbdriver = Neo4jReadDriver(shareds.driver) reader = PlaceReader(dbdriver, u_context) # The list has Place objects, which include also the lists of # nearest upper and lower Places as place[i].upper[] and place[i].lower[] results = reader.get_list() elapsed = time.time() - t0 stk_logger( u_context, f"-> bp.scene.routes.show_places n={len(results['items'])} e={elapsed:.3f}" ) return render_template("/scene/places.html", places=results['items'], menuno=4, user_context=u_context, elapsed=elapsed)
def show_person(uid=None): """ One Person with all connected nodes - NEW version 3. Arguments: - uuid= persons uuid - debug=1 optinal for javascript tests """ t0 = time.time() uid = request.args.get('uuid', uid) dbg = request.args.get('debug', None) u_context = UserContext(user_session, current_user, request) # v3 Person page person, objs, jscode = get_person_full_data(uid, u_context.user, u_context.use_common()) if not person: return redirect( url_for('virhesivu', code=2, text="Ei oikeutta katsoa tätä henkilöä")) stk_logger(u_context, f"-> bp.scene.routes.show_person n={len(objs)}") #for ref in person.media_ref: print(f'media ref {ref}') last_year_allowed = datetime.now().year - shareds.PRIVACY_LIMIT return render_template("/scene/person.html", person=person, obj=objs, jscode=jscode, menuno=12, debug=dbg, root=person.root, last_year_allowed=last_year_allowed, elapsed=time.time() - t0, user_context=u_context)
def test_ownerfilter_nouser(): # UserContext(user_session) user_session = {} user_session['user_context'] = 1 f = UserContext(user_session) assert f.context == 1 assert f.owner_str() == 'Isotammi database' user_session['user_context'] = 2 assert f.context == 1 assert f.owner_str() == 'Isotammi database', "No user gets wrong data"
def read_families(): """ Lukee tietokannasta Family- objektit näytettäväksi """ u_context = UserContext(user_session, current_user, request) # Which range of data is shown u_context.set_scope_from_request(request, 'person_scope') opt = request.args.get('o', 'father', type=str) count = request.args.get('c', 100, type=int) families = Family_combo.get_families(o_context=u_context, opt=opt, limit=count) return (families)
def show_all_persons_list(opt=''): """ List all persons for menu(1) OLD MODEL WITHOUT User selection Linked from admin/refnames only The string opt may include keys 'ref', 'sn', 'pn' in arbitary order with no delimiters. You may write 'refsn', 'ref:sn' 'sn-ref' etc. TODO Should have restriction by owner's UserProfile """ logger.warning( "#TODO: fix material selection or remove action show_all_persons_list") t0 = time.time() u_context = UserContext(user_session, current_user, request) keys = ('all', ) ref = ('ref' in opt) if 'fn' in opt: order = 1 # firstname elif 'pn' in opt: order = 2 # firstname else: order = 0 # surname args = {'ref': ref, 'order': order} if current_user.is_authenticated: args['user'] = current_user.username persons = read_persons_with_events( keys, args=args) #user=user, take_refnames=ref, order=order) stk_logger(u_context, "-> bp.scene.routes.show_all_persons_list") return render_template("/scene/persons.html", persons=persons, menuno=1, user_context=u_context, order=order, rule=keys, elapsed=time.time() - t0)
def show_media(uid=None): """ One Media """ uid = request.args.get('uuid', uid) u_context = UserContext(user_session, current_user, request) if not uid: return redirect(url_for('virhesivu', code=1, text="Missing Media key")) try: medium = Media.get_one(uid) fullname, mimetype = media.get_fullname(medium.uuid) if mimetype == "application/pdf": size = 0 else: size = media.get_image_size(fullname) except KeyError as e: return redirect(url_for('virhesivu', code=1, text=str(e))) stk_logger(u_context, f"-> bp.scene.routes.show_media n={len(medium.ref)}") return render_template("/scene/media.html", media=medium, size=size, user_context=u_context, menuno=6)
def show_family_page(uid=None): """ One Family. """ uid = request.args.get('uuid', uid) if not uid: return redirect(url_for('virhesivu', code=1, text="Missing Family key")) t0 = time.time() try: u_context = UserContext(user_session, current_user, request) dbdriver = Neo4jReadDriver(shareds.driver) reader = FamilyReader(dbdriver, u_context) results = reader.get_family_data(uid) #family = Family_combo.get_family_data(uid, u_context) except KeyError as e: return redirect(url_for('virhesivu', code=1, text=str(e))) stk_logger(u_context, "-> bp.scene.routes.show_family_page") if results['status']: return redirect( url_for('virhesivu', code=1, text=results['statustext'])) return render_template("/scene/family.html", menuno=3, family=results['item'], user_context=u_context, elapsed=time.time() - t0)
def show_source_page(sourceid=None): """ Home page for a Source with referring Event and Person data """ uuid = request.args.get('uuid', sourceid) if not uuid: return redirect(url_for('virhesivu', code=1, text="Missing Source key")) u_context = UserContext(user_session, current_user, request) try: dbdriver = Neo4jReadDriver(shareds.driver) reader = SourceReader(dbdriver, u_context) results = reader.get_source_with_references(uuid, u_context) if results['status'] == Status.NOT_FOUND: msg = results.get('statustext', _('No objects found')) return redirect(url_for('virhesivu', code=1, text=msg)) if results['status'] != Status.OK: msg = results.get('statustext', _('Error')) return redirect(url_for('virhesivu', code=1, text=msg)) except KeyError as e: return redirect(url_for('virhesivu', code=1, text=str(e))) stk_logger( u_context, f"-> bp.scene.routes.show_source_page n={len(results['citations'])}") # for c in results.citations: # for i in c.citators: # if i.id[0] == "F": print(f'{c} – family {i} {i.clearname}') # else: print(f'{c} – person {i} {i.sortname}') return render_template("/scene/source_events.html", source=results['item'], citations=results['citations'], user_context=u_context)
def show_place(locid): """ Home page for a Place, shows events and place hierarchy. """ t0 = time.time() try: u_context = UserContext(user_session, current_user, request) dbdriver = Neo4jReadDriver(shareds.driver) reader = PlaceReader(dbdriver, u_context) results = reader.get_with_events(locid) if results['status'] == Status.NOT_FOUND: return redirect( url_for('virhesivu', code=1, text=f'Ei löytynyt yhtään')) if results['status'] != Status.OK: return redirect(url_for('virhesivu', code=1, text=f'Virhetilanne')) except KeyError as e: traceback.print_exc() return redirect(url_for('virhesivu', code=1, text=str(e))) stk_logger(u_context, f"-> bp.scene.routes.show_place n={len(results['events'])}") return render_template("/scene/place_events.html", place=results['place'], pl_hierarchy=results['hierarchy'], events=results['events'], user_context=u_context, elapsed=time.time() - t0)
def test_ownerfilter_user_selection(user_env): ''' Example: - Show all my data / div=2 - with common data / cmp=1 <Request 'http://127.0.0.1:5000/scene/persons_all/?div=2&cmp=1' [GET]> <User Session {'_fresh': True, '_id': '...', 'csrf_token': '...', 'lang': 'en', 'next_person': ['', '>'], 'user_context': 2, 'user_id': 'juha'}> ''' user_session, current_user, request = user_env f = UserContext(user_session, current_user, request) assert f.context == 1 assert f.owner_str() == 'Isotammi database' x = f.use_owner_filter() assert x == False, "use_owner_filter() failed" x = f.use_common() assert x == True, "use_common() failed"
def show_medias(): """ List of Medias for menu(5) """ t0 = time.time() print(f"--- {request}") print(f"--- {user_session}") # Set context by owner and the data selections u_context = UserContext(user_session, current_user, request) # Which range of data is shown u_context.set_scope_from_request(request, 'media_scope') try: medias = Media.read_my_media_list(u_context, 20) except KeyError as e: return redirect(url_for('virhesivu', code=1, text=str(e))) stk_logger(u_context, f"-> bp.scene.media.show_medias fw n={len(medias)}") return render_template("/scene/medias.html", medias=medias, user_context=u_context, elapsed=time.time() - t0)
def show_event_v1(uuid): """ Event page with accompanied persons and families. Derived from bp.tools.routes.show_baptism_data() """ u_context = UserContext(user_session, current_user, request) dbdriver = Neo4jReadDriver(shareds.driver) reader = EventReader(dbdriver, u_context) results = reader.get_event_data(uuid) status = results.get('status') if status != Status.OK: flash(f'{_("Event not found")}: {results.get("statustext")}', 'error') event = results.get('event', None) members = results.get('members', []) stk_logger(u_context, f"-> bp.scene.routes.show_event_page n={len(members)}") return render_template("/scene/event.html", event=event, participants=members)
def show_persons_by_refname(refname, opt=""): """ List persons by refname for menu(0). Called from /list/refnames """ logger.warning( "#TODO: fix material selevtion or remove action show_persons_by_refname" ) u_context = UserContext(user_session, current_user, request) keys = ('refname', refname) ref = ('ref' in opt) order = 0 args = {'ref': ref, 'order': order} if current_user.is_authenticated: args['user'] = current_user.username persons = read_persons_with_events(keys, args=args) stk_logger(u_context, f"-> bp.scene.routes.show_persons_by_refname n={len(persons)}") return render_template("/scene/persons.html", persons=persons, menuno=1, user_context=u_context, order=order, rule=keys)
def show_persons_all(): """ List all persons for menu(12). Both my own and other persons depending on sum of url attributes div + div2 or session variables. The position in persons list is defined by – 1. by attribute fw, if defined (the forward arrow or from seach field) 2. by session next_person[1], if defined (the page last visited) #TODO: next_person[0] is not in use, yet (backward arrow) 3. otherwise "" (beginning) """ print(f"--- {request}") print(f"--- {user_session}") # Set filter by owner and the data selections u_context = UserContext(user_session, current_user, request) # Which range of data is shown u_context.set_scope_from_request(request, 'person_scope') # How many objects are shown? u_context.count = int(request.args.get('c', 100)) u_context.privacy_limit = shareds.PRIVACY_LIMIT t0 = time.time() dbdriver = Neo4jReadDriver(shareds.driver) db = DBreader(dbdriver, u_context) results = db.get_person_list() elapsed = time.time() - t0 hidden = f" hide={results.num_hidden}" if results.num_hidden > 0 else "" stk_logger( u_context, f"-> bp.scene.routes.show_persons_all" f" n={len(results.items)}{hidden} e={elapsed:.3f}") # print(f"Got {len(results.items)} persons" # f" with {len(results.items)-results.num_hidden} hidden" # f" and {results.error} errors" # f" in {elapsed:.3f}s") return render_template("/scene/persons_list.html", persons=results.items, num_hidden=results.num_hidden, user_context=u_context, menuno=12, elapsed=elapsed)
def show_sources(series=None): """ Lähdeluettelon näyttäminen ruudulla for menu(5) Possible args example: ?years=1800-1899&series=birth - source years (#todo) - series, one of {"birth", "babtism", "wedding", "death", "move"} Missing series or years = all Theme may also be expressed in url path """ print(f"--- {request}") print(f"--- {user_session}") t0 = time.time() # Set context by owner and the data selections u_context = UserContext(user_session, current_user, request) # Which range of data is shown u_context.set_scope_from_request(request, 'source_scope') u_context.count = request.args.get('c', 100, type=int) dbdriver = Neo4jReadDriver(shareds.driver) reader = SourceReader(dbdriver, u_context) if series: u_context.series = series try: results = reader.get_source_list() if results['status'] == Status.NOT_FOUND: return redirect( url_for('virhesivu', code=1, text=f'Ei löytynyt yhtään')) if results['status'] != Status.OK: return redirect(url_for('virhesivu', code=1, text=f'Virhetilanne')) except KeyError as e: return redirect(url_for('virhesivu', code=1, text=str(e))) series = u_context.series if u_context.series else "all" stk_logger( u_context, f"-> bp.scene.routes.show_sources/{series} n={len(results['items'])}") return render_template("/scene/sources.html", sources=results['items'], user_context=u_context, elapsed=time.time() - t0)
def get_family_data( uuid, context: UserContext): # -> bl.family.FamilyReader.get_family_data """ Read Family information including Events, Children, Notes and Sources. 1) read (f:Family) --> (e:Event) (f:Family) -[:PARENT]-> (pp:Person) -> (np:Name) (f:Family) -[:CHILD]-> (pc:Person) -> (nc:Name) (f:Family) --> (fn:Note) (e:Event) --> (en:Note) (f:Family) --> (fac:Citation) --> (fas:Source) --> (far:Repository) (e:Event) --> (evc:Citation) --> (evs:Source) --> (evr:Repository) 2) read (pp:Person) --> (ppe:Event) --> (:Place) (pc:Person) --> (pce:Event) --> (:Place) 3) build Family_combo.mother, .names, event_birth, event_death Family_combo.father, .names, event_birth, event_death Family_combo.events Family_combo.notes Family_combo.sources / citation -> source -> repocitory ? Family_combo.children, .names, event_birth, event_death Returns a Family object with other objects included """ # Import here to handle circular dependency from .person_combo import Person_combo def set_birth_death(person, birth_node, death_node): ''' Set person.birth and person.death events from db nodes ''' if birth_node: person.event_birth = Event_combo.from_node(birth_node) if death_node: person.event_death = Event_combo.from_node(death_node) #------------ family = None with shareds.driver.session() as session: try: result = session.run(Cypher_family.get_family_data, pid=uuid) for record in result: if record['f']: # <Node id=272710 labels={'Family'} # properties={'father_sortname': '#Andersson#Anders', # 'change': 1519839324, 'rel_type': 'Married', 'handle': '_dcf94f357ea7b126cd8277f4495', # 'id': 'F0268', 'mother_sortname': 'Gröndahl#Juhantytär#Fredrika', # 'datetype': 3, 'date2': 1878089, 'date1': 1875043}> node = record['f'] family = Family_combo.from_node(node) for event_node, place_node in record['family_event']: if event_node: # event_node: # <Node id=242570 labels={'Event'} # properties={'datetype': 0, 'change': 1528183878, 'description': '', # 'handle': '_dcf94f35ea262b7e1a0a0066d6e', 'id': 'E1692', # 'date2': 1875043, 'type': 'Marriage', 'date1': 1875043}> e = Event_combo.from_node(event_node) if place_node: # place_node: <Node id=73479 labels={'Place'} properties={'coord': # [60.5625, 21.609722222222224], 'id': 'P0468', 'type': 'City', 'uuid': # 'd1d0693de1714a47acf6442d64246a50', 'pname': 'Taivassalo', 'change': # 1556953682}> e.place = PlaceBl.from_node(place_node) # Look for surrounding place: res = session.run(Cypher_person.get_places, uid_list=[e.uniq_id]) for rec in res: e.place.names = place_names_from_nodes( rec['pnames']) if rec['pi']: pl_in = PlaceBl.from_node( rec['pi']) pl_in.names = place_names_from_nodes( rec['pinames']) e.place.uppers.append(pl_in) family.events.append(e) uniq_id = -1 for role, person_node, name_node, birth_node, death_node in record[ 'parent']: # ['mother', # <Node id=235105 labels={'Person'} # properties={'sortname': 'Gröndahl#Juhantytär#Fredrika', 'datetype': 19, # 'confidence': '2.0', 'sex': 2, 'change': 1536161195, # 'handle': '_dcf94f357d9f565664a975f99f', 'id': 'I2475', # 'date2': 1937706, 'date1': 1856517}>, # <Node id=235106 labels={'Name'} # properties={'firstname': 'Fredrika', 'type': 'Married Name', # 'suffix': 'Juhantytär', 'prefix': '', 'surname': 'Gröndahl', 'order': 0}>, # <Node id=242532 labels={'Event'} # properties={'datetype': 0, 'change': 1519151217, 'description': '', # 'handle': '_dcf94f357db6f3c846e6472915f', 'id': 'E1531', # 'date2': 1856517, 'type': 'Birth', 'date1': 1856517}>, # <Node id=242536 labels={'Event'} # properties={'datetype': 0, 'change': 1519150640, 'description': '', # 'handle': '_dcf94f357e2d61f5f76e1ba7cb', 'id': 'E1532', # 'date2': 1937700, 'type': 'Death', 'date1': 1937700}> # ] if person_node: if uniq_id != person_node.id: # Skip person with double default name p = Person_combo.from_node(person_node) p.role = role if name_node: p.names.append( Name.from_node(name_node)) set_birth_death(p, birth_node, death_node) if role == 'father': family.father = p elif role == 'mother': family.mother = p if not context.use_common(): if family.father: family.father.too_new = False if family.mother: family.mother.too_new = False family.no_of_children = 0 family.num_hidden_children = 0 for person_node, name_node, birth_node, death_node in record[ 'child']: # record['child'][0]: # [<Node id=235176 labels={'Person'} # properties={'sortname': '#Andersdotter#Maria Christina', # 'datetype': 19, 'confidence': '2.0', 'sex': 2, 'change': 1532009600, # 'handle': '_dd2a65b2f8c7e05bc664bd49d54', 'id': 'I0781', 'date2': 1877226, 'date1': 1877219}>, # <Node id=235177 labels={'Name'} # properties={'firstname': 'Maria Christina', 'type': 'Birth Name', 'suffix': 'Andersdotter', # 'prefix': '', 'surname': '', 'order': 0}>, # <Node id=242697 labels={'Event'} # properties={'datetype': 0, 'change': 1532009545, 'description': '', 'handle': '_dd2a65b218a14e81692d77955d2', # 'id': 'E1886', 'date2': 1877219, 'type': 'Birth', 'date1': 1877219}>, # <Node id=242702 labels={'Event'} # properties={'datetype': 0, 'change': 1519916327, 'description': '', 'handle': '_dd2a65b218a4e85ab141faeab48', # 'id': 'E1887', 'date2': 1877226, 'type': 'Death', 'date1': 1877226}> # ] if person_node: family.no_of_children += 1 p = Person_combo.from_node(person_node) if name_node: p.names.append(Name.from_node(name_node)) set_birth_death(p, birth_node, death_node) if context.use_common(): if p.too_new: family.num_hidden_children += 1 continue else: p.too_new = False family.children.append(p) #family.no_of_children = len(family.children) for repository_node, source_node, citation_node in record[ 'sources']: # record['sources'][0]: # [<Node id=253027 labels={'Repository'} # properties={'handle': '_dcad22f5914b34fe61c341dad0', 'id': 'R0068', 'rname': 'Taivassalon seurakunnan arkisto', # 'type': 'Archive', 'change': '1546265916'}>, # <Node id=247578 labels={'Source'} # properties={'handle': '_e085cd6d68d256a94afecd2162d', 'id': 'S1418', # 'stitle': 'Taivassalon seurakunnan syntyneiden ja kastettujen luettelot 1790-1850 (I C:4)', # 'change': '1543186596'}>, # <Node id=246371 labels={'Citation'} # properties={'handle': '_dd12b0b88d5741ee11d8bef1ca5', 'id': 'C0854', 'page': 'Vigde år 1831 April 4', # /* dates missing here */, 'change': 1543186596, 'confidence': '2'}> # ] if repository_node: source = Source.from_node(source_node) cita = Citation.from_node(citation_node) repo = Repository.from_node(repository_node) source.repositories.append(repo) source.citations.append(cita) family.sources.append(source) for node in record['note']: note = Note.from_node(node) family.notes.append(note) except Exception as e: print('Error get_family_data: {} {}'.format( e.__class__.__name__, e)) raise return family
def test_ownerfilter_next_item(user_env): ''' Example: Show all my data with common data default direction (fw) - from previous next_person: start '<' - from previous next_person 'Abrahamsson##Juho Kustaa' - from previous next_person: end '>' <Request 'http://127.0.0.1:5000/scene/persons_all/?div=2&cmp=1' [GET]> <User Session {'_fresh': True, '_id': '...', 'csrf_token': '...', 'lang': 'en', 'next_person': ['', '>'], 'user_context': 2, 'user_id': 'juha'}> ''' user_session, current_user, request = user_env # 0. Initialize UserContext with current session, user and request info f = UserContext(user_session, current_user, request) # 1. In the beginning user_session['person_scope'] = ['', '<'] f.set_scope_from_request(request, 'person_scope') # Read data here --> got required amount f.update_session_scope('person_name', '##Elisabet', '#Hansson#Lars', 100, 100) x = f.next_name_fw() assert x == '', "next fw not in the beginning" # 2. At given point user_session['person_scope'] = ['Za', None] f.set_scope_from_request(request, 'person_scope') # Read data here --> reached end f.update_session_scope('person_name', 'Zakrevski##Arseni', 'Östling##Carl', 50, 28) x = f.next_name_fw() assert x == 'Zakrevski##Arseni', "next fw not at given point" # 3. At end user_session['person_scope'] = ['>', None] # Read data here --> reached end f.set_scope_from_request(request, 'person_scope') x = f.next_name_fw() assert x == '> end', "next fw not at end"
def show_event_vue(uuid): """ Show Event page template which marchals data by Vue. """ u_context = UserContext(user_session, current_user, request) return render_template("/scene/event_vue.html", uuid=uuid, user_context=u_context)
def json_get_event(): """ Get Event page data. """ t0 = time.time() try: args = request.args if args: print(f'got request args: {args}') else: args = json.loads(request.data) print(f'got request data: {args}') uuid = args.get('uuid') if not uuid: print("bp.scene.routes.json_get_person_families: Missing uuid") return jsonify({ "records": [], "status": Status.ERROR, "statusText": "Missing uuid" }) u_context = UserContext(user_session, current_user, request) dbdriver = Neo4jReadDriver(shareds.driver) reader = EventReader(dbdriver, u_context) results = reader.get_event_data(uuid, args) status = results.get('status') if status != Status.OK: flash(f'{_("Event not found")}: {results.get("statustext")}', 'error') if status == Status.NOT_FOUND: return jsonify({ "event": None, "members": [], "statusText": _('No event found'), "status": status }) elif status != Status.OK: return jsonify({ "event": None, "members": [], "statusText": _('No event found'), "status": status }) # Event event = results.get('event', None) event.type_lang = jinja_filters.translate(event.type, 'evt').title() # Event members members = results.get('members', []) for m in members: if m.label == "Person": m.href = '/scene/person?uuid=' + m.uuid m.names[0].type_lang = jinja_filters.translate( m.names[0].type, 'nt') elif m.label == "Family": m.href = '/scene/family?uuid=' + m.uuid m.role_lang = jinja_filters.translate(m.role, 'role') if m.role else '' # Actually there is one place and one pl.uppers places = results.get('places', []) for pl in places: pl.href = '/scene/location/uuid=' + pl.uuid pl.type_lang = jinja_filters.translate(pl.type, 'lt').title() for up in pl.uppers: up.href = '/scene/location/uuid=' + up.uuid up.type_lang = jinja_filters.translate(up.type, 'lt_in').title() # Event notes notes = results.get('notes', []) # Medias medias = results.get('medias', []) for m in medias: m.href = '/scene/media?uuid=' + m.uuid #TODO: The auditor may edit, not user self as here if u_context.user and u_context.context == u_context.choices.OWN: allow_edit = True else: allow_edit = False res_dict = { "event": event, 'members': members, 'notes': notes, 'places': places, 'medias': medias, 'statusText': f'Löytyi {len(members)} tapahtuman osallista', 'allow_edit': allow_edit, 'translations': { 'myself': _('Self') } } response = json.dumps(res_dict, cls=StkEncoder) print(response) t1 = time.time() - t0 stk_logger( u_context, f"-> bp.scene.routes.json_get_event n={len(members)} e={t1:.3f}") return response except Exception as e: traceback.print_exc() return jsonify({ "records": [], "status": Status.ERROR, "member": uuid, "statusText": f"Failed {e.__class__.__name__}" })
def show_person_list(selection=None): """ Show list of selected Persons for menu(0). """ t0 = time.time() u_context = UserContext(user_session, current_user, request) #u_context.set_scope_from_request(request, 'person_scope') args = {} args['user'] = u_context.user args['context_code'] = u_context.context persons = [] if request.method == 'POST': try: # Selection from search form keys = (request.form['rule'], request.form['name']) theme = keys[0] #TODO: filter by user in the read method persons = read_persons_with_events(keys, args) except Exception as e: logger.error(f"bp.scene.routes.show_person_list error {e}") flash("Valitse haettava nimi ja tyyppi", category='warning') else: # the code below is executed if the request method # was GET (no search name given) or the credentials were invalid persons = [] if selection: # Use selection context keys = selection.split('=') theme = keys[0] else: keys = ('surname', ) theme = '' #TODO: filter by user in the read method persons = read_persons_with_events(keys, args) # If Context is COMMON (1): # - show both own candidate and approved materials # - but hide candadate materials of other users # If Context is OWN (2): show all own candidate materials select_users = [None] # COMMON, no user if u_context.use_owner_filter(): #select_users.append(None) select_users.append(u_context.user) hidden = 0 persons_out = [] for p in persons: if p.too_new and p.user != u_context.user: print(f'Hide {p.sortname} too_new={p.too_new}, owner {p.user}') hidden += 1 else: #print(f'Show {p.sortname} too_new={p.too_new}, owner {p.user}') persons_out.append(p) stk_logger( u_context, f"-> bp.scene.routes.show_person_list/{theme}-{request.method}" f" {u_context.owner_or_common()}" f" n={len(persons_out)} hide={len(persons)-len(persons_out)}") return render_template("/scene/persons.html", persons=persons_out, user_context=u_context, num_hidden=hidden, menuno=0, rule=keys, elapsed=time.time() - t0)
def json_get_person_families(): """ Get all families for a Person as json structure. The families are ordered by marriage time. """ t0 = time.time() try: args = request.args if args: print(f'got request args: {args}') else: args = json.loads(request.data) print(f'got request data: {args}') uuid = args.get('uuid') if not uuid: print("bp.scene.routes.json_get_person_families: Missing uuid") return jsonify({ "records": [], "status": Status.ERROR, "statusText": "Missing uuid" }) u_context = UserContext(user_session, current_user, request) dbdriver = Neo4jReadDriver(shareds.driver) reader = FamilyReader(dbdriver, u_context) results = reader.get_person_families(uuid) if results.get('status') == Status.NOT_FOUND: return jsonify({ "member": uuid, "records": [], "statusText": _('No families'), "status": Status.NOT_FOUND }) items = results['items'] res_dict = { 'records': items, "member": uuid, 'statusText': f'Löytyi {len(items)} perhettä', 'translations': { 'family': _('Family'), 'children': _('Children') } } response = json.dumps(res_dict, cls=StkEncoder) t1 = time.time() - t0 stk_logger( u_context, f"-> bp.scene.routes.show_person_families_json n={len(items)} e={t1:.3f}" ) print(response) return response except Exception as e: traceback.print_exc() return jsonify({ "records": [], "status": Status.ERROR, "member": uuid, "statusText": f"Failed {e.__class__.__name__}" })