def save(self): ''' sends the form to the framework for saving ''' save_action = self.rdf_instructions.get('kds_saveAction') if save_action == "kdr_AuthenticateUser": rdfw().user_authentication(self) else: rdfw().save_obj(self)
def save(self): ''' sends the form to the framework for saving ''' save_action = self.rdf_instructions.get('kds_saveAction') if save_action == "kdr_AuthenticateUser": rdfw().user_authentication(self) else: rdfw().save_obj(self)
def main(args): ''' Launches application with passed in Args ''' global RDFW_RESET global SERVER_CHECK # test to see if a forced definition reset is required if cbool(args.get("rdfw_reset",True)): RDFW_RESET = True else: RDFW_RESET = False # test to see if the server status check should be skipped if cbool(args.get("server_check",True)): SERVER_CHECK = True else: SERVER_CHECK = False # initialize the rdfframework rdfw(config=app.config, reset=RDFW_RESET, server_check = SERVER_CHECK, root_file_path=os.path.realpath('./')) # load default data into the server core ctx = app.test_request_context('/') with ctx: rdfw().load_default_data() host = '0.0.0.0' port = 8081 # Debug ssl_context = 'adhoc' app.run(host=host, port=port, #threaded=True, #ssl_context=ssl_context, debug=True)
def rdf_generic_api(class_uri, prop_uri): if not DEBUG: debug = False else: debug = True if debug: print("START rdf_generic_api ----------------------------\n") subject_uri = request.args.get("id") data = request.form.get("dataValue") subject_uri = request.form.get("id",subject_uri) if debug: print("class_uri: %s prop_uri: %s" % (class_uri, prop_uri)) if debug: print('subject_uri: ', subject_uri) if debug: print('data: ', data) if prop_uri in ["obi_claimDate","kds_errorLog"] and class_uri == "obi_Assertion": if hasattr(request, "form"): csrf = request.form.get("csrf") else: if debug: print("aborting **************") return abort(400) subject_uri = request.args.get("id") data = request.form.get("dataValue") subject_uri = request.form.get("id",subject_uri) #if debug: print("REQUEST dict: \n", pp.pformat(request.__dict__)) rdf_class = getattr(rdfw(), class_uri) prop_json = rdf_class.kds_properties.get(prop_uri) prop_json['kds_classUri'] = class_uri prop_json['kds_apiFieldName'] = prop_uri prop = RdfProperty(prop_json, data, subject_uri) base_url = "%s%s" % (request.url_root[:-1], url_for("open_badge.base_path")) current_url = request.url base_api_url = "%s%sapi/form_generic_prop/" % (request.url_root[:-1], url_for("open_badge.base_path")) if debug: print('rdf_class: ', rdf_class) print('prop_json: ', prop_json) print('prop: ', prop) print('base_url: ', base_url) print('current_url: ', current_url) print('base_api_url: ', base_api_url) api_url = request.base_url rdf_obj = Api(subject_uri=subject_uri, data_class_uri=class_uri, data_prop_uri=prop_uri, rdf_field_list=[prop_json], prop_list = [prop], base_url=base_url, current_url=current_url, base_api_url=base_api_url, api_url=api_url) if request.method == "POST": save_result = rdf_obj.save() if debug: print("**** save_result:\n",pp.pformat(save_result.__dict__)) if debug: print("END rdf_generic_api POST -------------------------\n") return jsonify(save_result.save_results[0]) else: api_data = rdfw().get_obj_data(rdf_obj) if debug: print("\t**** api_data:\n",pp.pprint(api_data)) if debug: print("END rdf_generic_api GET --------------------------\n") return json.dumps(api_data['obj_json'], indent=4)
def redirect_url(self, id_value=None, **kwargs): ''' formats the redirect url for the form in its current state ''' if id_value is None: id_value = self.save_subject_uri if self.save_state == "success": _url_instructions = self.rdf_instructions.get("kds_submitSuccessRedirect") if not _url_instructions: return base_url elif self.save_state == "fail": _url_instructions = self.rdf_instructions.get("submitFailRedirect") if not _url_instructions: return "!--currentpage" if _url_instructions == "!--currentpage": return self.current_url elif _url_instructions == "!--homepage": return "/" elif _url_instructions == "!--source": return kwargs.get("params", {}).get("source",\ kwargs.get("params", {}).get("next","/")) elif _url_instructions is not None: _form_url = rdfw().get_form_path(self.form_uri, _url_instructions) if _form_url is not None: return "{}{}?id={}".format(self.base_url, _form_url, quote(nz(id_value,''))) else: return _url_instructions else: return self.base_url
def _set_class_links(self): ''' reads the classes used in the form fields and determines the linkages between the classes and sets the the following attributes: self.dep_classes self.indep_classes self.dependancies self.reverse_dependancies ''' _class_set = set() # get all of the unique rdf classes in the passed in form for _field in self.rdf_field_list: if isinstance(_field, dict): _class_set.add(_field['kds_classUri']) else: _class_set.add(_field.kds_classUri) _class_set = remove_null(_class_set) try: _class_set.remove("kds_NoClass") except: pass class_links = rdfw().get_class_links(_class_set) self.class_set = _class_set self.dep_classes = class_links['dep_classes'] self.indep_classes = class_links['indep_classes'] self.dependancies = class_links['dependancies'] self.reverse_dependancies = class_links['reverse_dependancies']
def redirect_url(self, id_value=None, **kwargs): ''' formats the redirect url for the form in its current state ''' if id_value is None: id_value = self.save_subject_uri if self.save_state == "success": _url_instructions = self.rdf_instructions.get( "kds_submitSuccessRedirect") if not _url_instructions: return base_url elif self.save_state == "fail": _url_instructions = self.rdf_instructions.get("submitFailRedirect") if not _url_instructions: return "!--currentpage" if _url_instructions == "!--currentpage": return self.current_url elif _url_instructions == "!--homepage": return "/" elif _url_instructions == "!--source": return kwargs.get("params", {}).get("source",\ kwargs.get("params", {}).get("next","/")) elif _url_instructions is not None: _form_url = rdfw().get_form_path(self.form_uri, _url_instructions) if _form_url is not None: return "{}{}?id={}".format(self.base_url, _form_url, quote(nz(id_value, ''))) else: return _url_instructions else: return self.base_url
def query_select_options(field): ''' returns a list of key value pairs for a select field ''' _prefix = rdfw().get_prefix() _select_query = field.kds_fieldType.get('kds_selectQuery', None) _select_list = {} _options = [] if _select_query: # send query to triplestore _select_list = requests.post(fw_config().get('TRIPLESTORE_URL'), data={ "query": _prefix + _select_query, "format": "json" }) _raw_options = _select_list.json().get('results', {}).get('bindings', []) _bound_var = field.kds_fieldType.get('kds_selectBoundValue', ''\ ).replace("?", "") _display_var = field.kds_fieldType.get('kds_selectDisplay', ''\ ).replace("?", "") # format query result into key value pairs for row in _raw_options: _options.append({ "id": iri(row.get(_bound_var, {}).get('value', '')), "value": row.get(_display_var, {}).get('value', '') }) return _options
def query_select_options(field): ''' returns a list of key value pairs for a select field ''' _prefix = rdfw().get_prefix() _select_query = field.kds_fieldType.get('kds_selectQuery', None) _select_list = {} _options = [] if _select_query: # send query to triplestore _select_list = requests.post( fw_config().get('TRIPLESTORE_URL'), data={"query": _prefix + _select_query, "format": "json"}) _raw_options = _select_list.json().get('results', {}).get('bindings', []) _bound_var = field.kds_fieldType.get('kds_selectBoundValue', ''\ ).replace("?", "") _display_var = field.kds_fieldType.get('kds_selectDisplay', ''\ ).replace("?", "") # format query result into key value pairs for row in _raw_options: _options.append( { "id":iri(row.get(_bound_var, {}).get('value', '')), "value":row.get(_display_var, {}).get('value', '') }) return _options
def __init__(self, *args, **kwargs): super(Form, self).__init__(*args, **kwargs) self.obj_type = "form" self.xsd_load = "string" self.form_changed = False self.base_url = kwargs.get("base_url", self.base_url) self.current_url = kwargs.get("current_url", self.current_url) self.form_uri = self.form_uri self.save_state = None self.save_subject_uri = None self.save_results = None self.data_subject_uri = kwargs.get("subject_uri", self.data_subject_uri) edit_path = rdfw().get_form_path(self.form_uri, "kdr_EditForm") self.edit_path = None if edit_path: self.edit_path = "{}{}?id={}".format(\ self.base_url, edit_path, quote(nz(self.data_subject_uri,''))) self.display_path = "{}{}?id={}".format(\ self.base_url, rdfw().get_form_path(self.form_uri, "kdr_DisplayForm"), quote(nz(self.data_subject_uri,''))) self.data_class_uri = self.data_class_uri self.has_subobj = self.has_subobj self.is_subobj = self.is_subobj self.rdf_field_list = self.rdf_field_list self.rdf_instructions = self.rdf_instructions self.instance_uri = self.instance_uri self.data_class_uri = self.data_class_uri self.data_prop_uri = self.data_prop_uri self._set_class_links() self._tie_wtf_fields_to_field_list() if not kwargs.get('no_query'): #self._get_form_data() self._load_form_select_options() for fld in self.rdf_field_list: pretty_data = pp.pformat(fld.__dict__) setattr(fld, 'debug_data', pretty_data) pretty_data = pp.pformat(self.__dict__) self.debug_data = pretty_data self.original_fields = copy_obj(self._fields) self._renumber_field_rows()
def __init__(self, *args, **kwargs): super(Form, self).__init__(*args, **kwargs) self.obj_type = "form" self.xsd_load = "string" self.form_changed = False self.base_url = kwargs.get("base_url", self.base_url) self.current_url = kwargs.get("current_url", self.current_url) self.form_uri = self.form_uri self.save_state = None self.save_subject_uri = None self.save_results = None self.data_subject_uri = kwargs.get("subject_uri",self.data_subject_uri) edit_path = rdfw().get_form_path(self.form_uri, "kdr_EditForm") self.edit_path = None if edit_path: self.edit_path = "{}{}?id={}".format(\ self.base_url, edit_path, quote(nz(self.data_subject_uri,''))) self.display_path = "{}{}?id={}".format(\ self.base_url, rdfw().get_form_path(self.form_uri, "kdr_DisplayForm"), quote(nz(self.data_subject_uri,''))) self.data_class_uri = self.data_class_uri self.has_subobj = self.has_subobj self.is_subobj = self.is_subobj self.rdf_field_list = self.rdf_field_list self.rdf_instructions = self.rdf_instructions self.instance_uri = self.instance_uri self.data_class_uri = self.data_class_uri self.data_prop_uri = self.data_prop_uri self._set_class_links() self._tie_wtf_fields_to_field_list() if not kwargs.get('no_query'): #self._get_form_data() self._load_form_select_options() for fld in self.rdf_field_list: pretty_data = pp.pformat(fld.__dict__) setattr(fld, 'debug_data', pretty_data) pretty_data = pp.pformat(self.__dict__) self.debug_data = pretty_data self.original_fields = copy_obj(self._fields) self._renumber_field_rows()
def rdf_lookup_api(class_uri, prop_uri): if not DEBUG: debug = False else: debug = True if debug: print("START rdf_lookup_api ----------------------------\n") return abort(400) referer = request.environ.get("HTTP_REFERER") form_function_path = url_for("app.rdf_class_forms", form_name="form_name", form_instance="form_instance") base_form_path = \ form_function_path.replace("form_name/form_instance.html", "") form_path = referer[referer.find(base_form_path)+len(base_form_path):\ ].replace('.html','') form_exists = rdfw().form_exists(form_path) if not form_exists: return abort(400) form_class = rdf_framework_form_factory(form_path)() if debug: print("form_path: ", form_path) if debug: print("Source Form: ", referer) #if debug: print("form dict:\n", pp.pformat(form_class.__dict__)) related_fields = [] for fld in form_class.rdf_field_list: print(fld.__dict__, "\n") if fld.kds_classUri == class_uri: related_fields.append(fld) for _range in make_list(fld.rdfs_range): if _range.get("rangeClass") == class_uri: related_fields.append(fld) if fld.type == "FieldList": if fld.entries[0].type == "FormField": for _fld in fld.entries[0].rdf_field_list: if class_uri == _fld.kds_classUri: related_fields.append(_fld) for fld in related_fields: print("field: ", fld.name) subject_uri = request.args.get("id") data = request.args.get("dataValue") subject_uri = request.form.get("id", subject_uri) if debug: print("REQUEST dict: \n", pp.pformat(request.__dict__)) rdf_class = getattr(rdfw(), class_uri) '''prop_json = rdf_class.kds_properties.get(prop_uri)
def rdf_lookup_api(class_uri, prop_uri): if not DEBUG: debug = False else: debug = True if debug: print("START rdf_lookup_api ----------------------------\n") return abort(400) referer = request.environ.get("HTTP_REFERER") form_function_path = url_for("open_badge.rdf_class_forms", form_name="form_name", form_instance="form_instance") base_form_path = \ form_function_path.replace("form_name/form_instance.html", "") form_path = referer[referer.find(base_form_path)+len(base_form_path):\ ].replace('.html','') form_exists = rdfw().form_exists(form_path) if not form_exists: return abort(400) form_class = rdf_framework_form_factory(form_path)() if debug: print("form_path: ",form_path) if debug: print("Source Form: ", referer) #if debug: print("form dict:\n", pp.pformat(form_class.__dict__)) related_fields = [] for fld in form_class.rdf_field_list: print(fld.__dict__,"\n") if fld.kds_classUri == class_uri: related_fields.append(fld) for _range in make_list(fld.rdfs_range): if _range.get("rangeClass") == class_uri: related_fields.append(fld) if fld.type == "FieldList": if fld.entries[0].type == "FormField": for _fld in fld.entries[0].rdf_field_list: if class_uri == _fld.kds_classUri: related_fields.append(_fld) for fld in related_fields: print("field: ",fld.name) subject_uri = request.args.get("id") data = request.args.get("dataValue") subject_uri = request.form.get("id",subject_uri) if debug: print("REQUEST dict: \n", pp.pformat(request.__dict__)) rdf_class = getattr(rdfw(), class_uri) '''prop_json = rdf_class.kds_properties.get(prop_uri)
def run_sparql_query(sparql, **kwargs): ''' run the passed in sparql query and returns the results ''' _prefix = rdfw().get_prefix() if sparql is not None: _results = requests.post(fw_config().get('TRIPLESTORE_URL'), data={"prefix": _prefix, "query": sparql, "format": "json"}) return _results.json().get('results', {}).get('bindings', []) else: return None
def app_defintions(): '''View displays the RDF json''' defs = [{ "id": "app", "name": "Application", "data": rdfw().rdf_app_dict }, { "id": "rdfclass", "name": "Rdf Classes", "data": rdfw().rdf_class_dict }, { "id": "formpath", "name": "Form Paths", "data": rdfw().form_list }, { "id": "formdef", "name": "Form Definitons", "data": rdfw().rdf_form_dict }, { "id": "apipath", "name": "API Paths", "data": rdfw().api_list }, { "id": "apidef", "name": "API Definitons", "data": rdfw().rdf_api_dict }] template = render_template("/app_definitions.html", defs=defs) return template
def run_sparql_query(sparql, **kwargs): ''' run the passed in sparql query and returns the results ''' _prefix = rdfw().get_prefix() if sparql is not None: _results = requests.post(fw_config().get('TRIPLESTORE_URL'), data={ "prefix": _prefix, "query": sparql, "format": "json" }) return _results.json().get('results', {}).get('bindings', []) else: return None
def get_api_instructions_json(instructions, instance): ''' This function will read through the RDF defined info and proccess the json to retrun the correct instructions for the specified form instance.''' _rdf_app = rdfw().app #print("inst------", instructions) # get form instance info _api_instance_info = {} _api_instance_type_list = make_list(instructions.get('kds_apiInstance', [])) for _api_instance in _api_instance_type_list: if _api_instance.get('kds_apiInstanceType') == instance: _api_instance_info = _api_instance _new_instr = {} #print("------", _form_instance_info) #Determine the api paramaters _new_instr['kds_apiTitle'] = _api_instance_info.get('kds_apiTitle', \ instructions.get("kds_apiTitle", "")) _new_instr['kds_apiDescription'] = _api_instance_info.get('kds_apiDescription', \ instructions.get("kds_apiDescription", "")) _new_instr['kds_apiMethod'] = _api_instance_info.get('kds_apiMethod', \ instructions.get("kds_apiMethod", "")) _new_instr['kds_lookupClassUri'] = _api_instance_info.get('kds_lookupClassUri', \ instructions.get("kds_lookupClassUri", "")) _new_instr['kds_lookupPropertyUri'] =\ _api_instance_info.get('kds_lookupPropertyUri',\ instructions.get("kds_lookupPropertyUri", "")) _new_instr['kds_submitSuccessRedirect'] = \ _api_instance_info.get('kds_submitSuccessRedirect', instructions.get(\ "kds_submitSuccessRedirect", "")) _new_instr['kds_submitFailRedirect'] = \ _api_instance_info.get('kds_submitFailRedirect', instructions.get("kds_submitFailRedirect", "")) _new_instr['kds_saveAction'] = \ _api_instance_info.get('kds_saveAction', instructions.get("kds_saveAction", "")) _new_instr['kds_returnType'] = \ _api_instance_info.get('kds_returnType', instructions.get("kds_returnType", "")) _new_instr['kds_mimeType'] = \ _api_instance_info.get('kds_mimeType', instructions.get("kds_mimeType", "")) _new_instr['kds_subjectUriTransform'] = \ _api_instance_info.get('kds_subjectUriTransform', instructions.get("kds_subjectUriTransform", "")) return _new_instr
def app_defintions(): '''View displays the RDF json''' defs = [{"id":"app", "name":"Application", "data":rdfw().rdf_app_dict}, {"id":"rdfclass", "name":"Rdf Classes", "data":rdfw().rdf_class_dict}, {"id":"formpath", "name":"Form Paths", "data":rdfw().form_list}, {"id":"formdef", "name":"Form Definitons", "data":rdfw().rdf_form_dict}, {"id":"apipath", "name":"API Paths", "data":rdfw().api_list}, {"id":"apidef", "name":"API Definitons", "data":rdfw().rdf_api_dict}] template = render_template( "/app_definitions.html", defs=defs) return template
def form_rdf_class(): """View displays the RDF json""" form_dict = rdfw().rdf_form_dict class_dict = rdfw().rdf_class_dict app_dict = rdfw().rdf_app_dict api_dict = rdfw().rdf_api_dict table_template = ''' <style> table.fixed {{ table-layout:fixed; width: 2000px }} table.fixed td {{ overflow: hidden; vertical-align:top; }} </style> <table class="fixed"> <col width="20%" /> <col width="20%" /> <col width="20%" /> <col width="20%" /> <col width="20%" /> <col width="20%" /> <tr> <td><h1>Application JSON</h1></td> <td><h1>Class JSON</h1></td> <td><h1>Form Paths</h1></td> <td><h1>Form Json</h1></td> <td><h1>API List</h1></td> <td><h1>API Json</h1></td> </tr> <tr> <td><pre>{0}</pre></td> <td><pre>{2}</pre></td> <td><pre>{1}</pre></td> <td><pre>{3}</pre></td> <td><pre>{5}</pre></td> <td><pre>{4}</pre></td> </tr> </table>''' return table_template.format( json.dumps(app_dict, indent=2), json.dumps(rdfw().form_list, indent=2), json.dumps(class_dict, indent=2), json.dumps(form_dict, indent=2), json.dumps(api_dict, indent=2), json.dumps(rdfw().api_list, indent=2))
def form_rdf_class(): """View displays the RDF json""" form_dict = rdfw().rdf_form_dict class_dict = rdfw().rdf_class_dict app_dict = rdfw().rdf_app_dict api_dict = rdfw().rdf_api_dict table_template = ''' <style> table.fixed {{ table-layout:fixed; width: 2000px }} table.fixed td {{ overflow: hidden; vertical-align:top; }} </style> <table class="fixed"> <col width="20%" /> <col width="20%" /> <col width="20%" /> <col width="20%" /> <col width="20%" /> <col width="20%" /> <tr> <td><h1>Application JSON</h1></td> <td><h1>Class JSON</h1></td> <td><h1>Form Paths</h1></td> <td><h1>Form Json</h1></td> <td><h1>API List</h1></td> <td><h1>API Json</h1></td> </tr> <tr> <td><pre>{0}</pre></td> <td><pre>{2}</pre></td> <td><pre>{1}</pre></td> <td><pre>{3}</pre></td> <td><pre>{5}</pre></td> <td><pre>{4}</pre></td> </tr> </table>''' return table_template.format(json.dumps(app_dict, indent=2), json.dumps(rdfw().form_list, indent=2), json.dumps(class_dict, indent=2), json.dumps(form_dict, indent=2), json.dumps(api_dict, indent=2), json.dumps(rdfw().api_list, indent=2))
def _set_class_links(self): ''' reads the classes used in the form fields and determines the linkages between the classes and sets the the following attributes: self.dep_classes self.indep_classes self.dependancies self.reverse_dependancies ''' _class_set = set() # get all of the unique rdf classes in the passed in form for _field in self.rdf_field_list: if isinstance(_field, dict): _class_set.add(_field['kds_classUri']) else: _class_set.add(_field.kds_classUri) class_links = rdfw().get_class_links(_class_set) self.class_set = _class_set self.dep_classes = class_links['dep_classes'] self.indep_classes = class_links['indep_classes'] self.dependancies = class_links['dependancies'] self.reverse_dependancies = class_links['reverse_dependancies']
def rdf_class_forms(form_name, form_instance=None): """View for displaying forms Args: form_name -- main form url part form_instance -- specific instance of the form (new, edit) params: id -- the lookup value for the form to lookup data """ _display_mode = False _form_path = "/".join(remove_null([form_name, form_instance])) # test to see if the form exists _form_exists = rdfw().form_exists(_form_path) if _form_exists is False: return render_template("error_page_template.html", error_message="The web address is invalid") # if the form exists continue instance_uri = _form_exists.get("instance_uri") form_uri = _form_exists.get("form_uri") # generate the form class form_class = rdf_framework_form_factory(_form_path, \ base_url=url_for("rdfw_core.base_path"), current_url=request.url) # test to see if the form requires a login login_message = None if cbool(form_class.rdf_instructions.get("kds_loginRequired",False)) is \ True: if isinstance(current_user.is_authenticated, bool): auth = current_user.is_authenticated else: auth = current_user.is_authenticated() if not auth: current_app.login_manager.login_message = \ "Please log in to access this page" #return current_app.login_manager.unauthorized() # if request method is post if request.method == "POST": # let form load with post data form = form_class(subject_uri=request.args.get("id")) # validate the form if form.validate(): # if validated save the form obj = form.save() if form.save_state == "success": if isinstance(form.save_results, User): login_user(form.save_results) return redirect(form.redirect_url(params=request.args)) else: redirect_url = form.redirect_url(params=request.args) if redirect_url != "!--currentpage": return redirect(redirect_url) #form = form_class(subject_uri=request.args.get("id")) # if not POST, check the args and form instance else: # if params are present for any forms that are not in any of # the below forms remove the params if instance_uri not in ["kdr_EditForm", "kdr_DisplayForm", "kdr_Login"]\ and request.args.get("id"): redirect_url = url_for("app.rdf_class_forms", form_name=form_name, form_instance=form_instance) return redirect(redirect_url) # if the there is no ID argument and on the editform instance -> # redirect to NewForm if instance_uri in ["kdr_EditForm","kdr_DisplayForm"] and \ not request.args.get("id"): redirect_url = url_for("app.base_path") + \ rdfw().get_form_path(form_uri, "kdr_NewForm") return redirect(redirect_url) # if the display form does not have an ID return an error if instance_uri in ["kdr_DisplayForm"] and not request.args.get("id"): return render_template("error_page_template.html", error_message="The item does not exist") # if the there is an ID argument and on the editform instance -> # query for the save item if request.args.get("id") and instance_uri \ in ["kdr_EditForm","kdr_DisplayForm"]: if instance_uri == "kdr_DisplayForm": _display_mode = True form_data = rdfw().get_obj_data(form_class(\ no_query=True, subject_uri=request.args.get("id"))) #pp.pprint(form_data) form = form_class(form_data['obj_data'],\ query_data=form_data['query_data'],\ subject_uri=request.args.get("id")) #pp.pprint(form) if not (len(form_data['query_data']) > 0): return render_template("error_page_template.html", error_message="The item does not exist") # if not on EditForm or DisplayForm render form else: form = form_class() template = render_template( "/forms/default/app_form_template.html", actionUrl=request.url, form=form, display_mode = _display_mode, dateFormat = rdfw().app.get(\ 'kds_dataFormats',{}).get('kds_javascriptDateFormat',''), debug=request.args.get("debug",False), login_message=login_message) return template
def rdf_api(api_name, id_value=None, ext=None): """View for displaying forms Args: api_name -- url path of the api (new, edit) ext -- url extension for the api ie (.json, .html) params: id -- the item to lookup """ if not DEBUG: debug = False else: debug = False if debug: print("START rdf_api blueprint.py ---------------------------\n") api_repsonder = falcon.API() _api_path = "|".join(remove_null([api_name, ext])) _api_exists = rdfw().api_exists(_api_path) if _api_exists is False: return render_template("error_page_template.html", error_message="The web address is invalid") api_uri = _api_exists.get("api_uri") # generate the api class base_url = "%s%s" % (request.url_root[:-1], url_for("app.base_path")) current_url = request.url base_api_url = "%s%sapi/" % (request.url_root[:-1], url_for("app.base_path")) api_url = request.base_url api_class = rdf_framework_api_factory(_api_path, base_url=base_url, current_url=current_url, base_api_url=base_api_url, api_url=api_url) # if request method is post if request.method == "POST": # let api load with post data api = api_class(id_value=id_value) # validate the form if api.validate(): # if validated save the form api.save() if api.save_state == "success": if debug: print("END rdf_api blueprint.py ---POST--------\n") return api.return_message # if not POST, check the args and api instance/extension else: api = api_class() api_data = rdfw().get_obj_data(api, id_value=id_value) #pp.pprint(api_data['form_data']) if not (len(api_data['query_data']) > 0): '''return render_template( "error_page_template.html", error_message="The item does not exist") ''' return abort(400) else: return_type = api.rdf_instructions.get("kds_returnType") if return_type == "file": repo_uri = clean_iri(list(api_data['obj_json'].values())[0]) repo_link = urlopen(repo_uri) repo_file = repo_link.read() # The File wrapper is causing issues in the live environment # need to delete before sending byte stream if debug: print("\t wsgi.file_wrapper pre: ",\ request.environ.get('wsgi.file_wrapper')) if request.environ.get('wsgi.file_wrapper') is not None: del (request.environ['wsgi.file_wrapper']) if debug: print("\t wsgi.file_wrapper post: ",\ request.environ.get('wsgi.file_wrapper')) if debug: print("END rdf_api blueprint.py --- file send ---\n") return send_file( io.BytesIO(repo_file), #return send_file(repo_link, attachment_filename="%s.%s" % (id_value, ext), mimetype=api.rdf_instructions.get("kds_mimeType")) else: #return "<pre>{}</pre>".format(json.dumps(api_data['obj_json'],indent=4)) if debug: print("END rdf_api blueprint.py --- json --------\n") return jsonify(api_data['obj_json'])
def get_field_json(field, instructions, instance, user_info, item_permissions=None): '''This function will read through the RDF defined info and proccess the json to return the correct values for the instance, security and details''' debug = False if item_permissions is None: item_permissions = [] _rdf_app = rdfw().app instance = instance.replace(".html", "") # Determine Security Access _new_field = {} _access_level = get_field_security_access(field, user_info, item_permissions) if "acl_Read" not in _access_level: return None _new_field['accessLevel'] = _access_level # get form instance info _form_instance_info = {} _form_field_instance_type_list = make_list(field.get('kds_formInstance', field.get(\ 'kds_formDefault', {}).get('kds_formInstance', []))) #print("instance type list: ",_form_field_instance_type_list) #print("instance: ", instance) for _field_instance in _form_field_instance_type_list: if _field_instance.get('kds_formInstanceType') == instance: _form_instance_info = _field_instance #print("instance info\n",_form_instance_info) # Determine the field paramaters _new_field['kds_formFieldName'] = _form_instance_info.get('kds_formFieldName', field.get(\ "kds_formFieldName", field.get('kds_formDefault', {}).get(\ 'kds_formFieldName', ""))) _new_field['kds_fieldType'] = _form_instance_info.get('kds_fieldType', field.get(\ 'kds_fieldType', field.get('kds_formDefault', {}).get('kds_fieldType', ""))) if not isinstance(_new_field['kds_fieldType'], dict): _new_field['kds_fieldType'] = {"rdf_type": _new_field['kds_fieldType']} _new_field['kds_formLabelName'] = _form_instance_info.get('kds_formLabelName', \ field.get("kds_formLabelName", field.get('kds_formDefault', {}).get(\ 'kds_formLabelName', ""))) _new_field['kds_formFieldHelp'] = _form_instance_info.get('kds_formFieldHelp', \ field.get("formFieldHelp", field.get('formDefault', {}).get(\ 'kds_formFieldHelp', ""))) _new_field['kds_formFieldOrder'] = _form_instance_info.get('kds_formFieldOrder', \ field.get("kds_formFieldOrder", field.get('kds_formDefault', {}).get(\ 'kds_formFieldOrder', ""))) _new_field['kds_formLayoutRow'] = _form_instance_info.get('kds_formLayoutRow', \ field.get("kds_formLayoutRow", field.get('kds_formDefault', {}).get(\ 'kds_formLayoutRow', ""))) _new_field['kds_propUri'] = field.get('kds_propUri') _new_field['kds_classUri'] = field.get('kds_classUri') _new_field['rdfs_range'] = field.get('rdfs_range') _new_field['kds_defaultVal'] = _form_instance_info.get('kds_defaultVal',\ field.get('kds_defaultVal')) # get applicationActionList _new_field['kds_actionList'] = make_set(_form_instance_info.get(\ 'kds_applicationAction', set())) _new_field['kds_actionList'].union( make_set(field.get('kds_applicationAction', set()))) _new_field['kds_actionList'] = list(_new_field['kds_actionList']) #print("action List:_______________", _new_field['kds_actionList']) if "kdr_RemoveFromForm" in\ _new_field['kds_actionList']: return None # get valiator list if field.get('kds_overrideValidation'): _new_field['kds_validators'] = field.get('kds_overrideValidation') else: _new_field['kds_validators'] = make_list(\ _form_instance_info.get('kds_formValidation', [])) _new_field['kds_validators'] += make_list(\ field.get('kds_formValidation', [])) _new_field['kds_validators'] += make_list(\ field.get('kds_propertyValidation', [])) # get processing list _new_field['kds_processors'] = make_list( _form_instance_info.get('kds_formProcessing', [])) _new_field['kds_processors'] += make_list( field.get('kds_formProcessing', [])) _new_field['kds_processors'] += make_list( field.get('kds_propertyProcessing', [])) if debug: if field['kds_propUri'] == "schema_image": x = 1 # get required state _required = False _field_req_var = cbool(field.get('kds_requiredField')) if (field.get('kds_propUri') in make_list(field.get('kds_classInfo', {}).get(\ 'kds_primaryKey', []))) or _field_req_var: _required = True if field.get('kds_classUri') in make_list( field.get('kds_requiredByDomain', {})): _required = True if _field_req_var == False: _required = False _new_field['kds_required'] = _required # Determine EditState if ("acl_Write" in _access_level) and ("kdr_NotEditable" \ not in _new_field['kds_actionList']): _new_field['editable'] = True else: _new_field['editable'] = False # Determine css classes css = _form_instance_info.get('kds_overrideCss', field.get('kds_overrideCss', \ instructions.get('kds_overrideCss', None))) if css is None: css = _rdf_app.get('kds_formDefault', {}).get('kds_fieldCss', '') css = css.strip() + " " + instructions.get('kds_propertyAddOnCss', '') css = css.strip() + " " + _form_instance_info.get('kds_addOnCss', field.get(\ 'kds_addOnCss', field.get('kds_formDefault', {}).get('kds_addOnCss', ''))) css = css.strip() _new_field['kds_css'] = css #print("field_json:\n", json.dumps(_new_field, indent=4)) return _new_field
def get_api_field_json(field, instructions, instance, user_info, item_permissions=None): '''This function will read through the RDF defined info and proccess the json to return the correct values for the instance, security and details''' if DEBUG: debug = True else: debug = False if item_permissions is None: item_permissions = [] _rdf_app = rdfw().app instance = instance.replace(".html", "") # get class property info try: _class_prop = getattr(rdfw(), field.get(\ 'kds_classUri')).kds_properties.get(field.get('kds_propUri'),{}) except: _class_prop = {} # merge the class prop attributes with the api prop #field = {**_class_prop, **field} temp_field = _class_prop.copy() temp_field.update(field) field = temp_field # Determine Security Access _new_field = {} _access_level = get_field_security_access(field, user_info, item_permissions) if "acl_Read" not in _access_level: return None _new_field['accessLevel'] = _access_level # get api instance info _api_instance_info = {} _api_field_instance_type_list = make_list(field.get('kds_apiInstance', field.get(\ 'kds_apiDefault', {}).get('kds_apiInstance', []))) if debug: print("instance type list: ",_api_field_instance_type_list) if debug: print("instance: ", instance) for _field_instance in _api_field_instance_type_list: if _field_instance.get('kds_apiInstanceType') == instance: _api_instance_info = _field_instance if debug: print("instance info\n",_api_instance_info) # Determine the field paramaters _new_field['kds_apiFieldName'] = _api_instance_info.get('kds_apiFieldName', field.get(\ "kds_apiFieldName", field.get('kds_apiDefault', {}).get(\ 'kds_apiFieldName', ""))) _new_field['kds_fieldType'] = _api_instance_info.get('kds_fieldType', field.get(\ 'kds_fieldType', field.get('kds_apiDefault', {}).get('kds_fieldType', ""))) if not isinstance(_new_field['kds_fieldType'], dict): _new_field['kds_fieldType'] = {"rdf_type":_new_field['kds_fieldType']} _new_field['kds_apiLabelName'] = _api_instance_info.get('kds_apiLabelName', \ field.get("kds_apiLabelName", field.get('kds_apiDefault', {}).get(\ 'kds_apiLabelName', ""))) _new_field['kds_apiFieldHelp'] = _api_instance_info.get('kds_apiFieldHelp', \ field.get("apiFieldHelp", field.get('apiDefault', {}).get(\ 'kds_apiFieldHelp', ""))) _new_field['kds_apiFieldOrder'] = _api_instance_info.get('kds_apiFieldOrder', \ field.get("kds_apiFieldOrder", field.get('kds_apiDefault', {}).get(\ 'kds_apiFieldOrder', ""))) _new_field['kds_apiLayoutRow'] = _api_instance_info.get('kds_apiLayoutRow', \ field.get("kds_apiLayoutRow", field.get('kds_apiDefault', {}).get(\ 'kds_apiLayoutRow', ""))) _new_field['rdfs_range'] = field.get('rdfs_range') _new_field['kds_defaultVal'] = _api_instance_info.get('kds_defaultVal',\ field.get('kds_defaultVal')) _new_field['kds_propUri'] = field.get('kds_propUri') _new_field['kds_classUri'] = field.get('kds_classUri') _new_field['kds_returnValue'] = field.get('kds_returnValue') # get applicationActionList _new_field['kds_actionList'] = make_set(_api_instance_info.get(\ 'kds_applicationAction', set())) _new_field['kds_actionList'].union(make_set(field.get('kds_applicationAction', set()))) _new_field['kds_actionList'] = list(_new_field['kds_actionList']) if debug: print("action List:_______________", _new_field['kds_actionList']) if "kdr_RemoveFromApi" in\ _new_field['kds_actionList']: return None # get valiator list if field.get('kds_overrideValidation'): _new_field['kds_validators'] = field.get('kds_overrideValidation') else: _new_field['kds_validators'] = make_list(\ _api_instance_info.get('kds_apiValidation', [])) _new_field['kds_validators'] += make_list(\ field.get('kds_apiValidation', [])) _new_field['kds_validators'] += make_list(\ field.get('kds_propertyValidation', [])) # get processing list _new_field['kds_processors'] = make_list(_api_instance_info.get('kds_apiProcessing', [])) _new_field['kds_processors'] += make_list(field.get('kds_apiProcessing', [])) _new_field['kds_processors'] += make_list(field.get('kds_propertyProcessing', [])) if debug: if field['kds_propUri'] == "schema_image": x=1 # get required state _required = False _field_req_var = cbool(field.get('kds_requiredField')) if (field.get('kds_propUri') in make_list(field.get('kds_classInfo', {}).get(\ 'kds_primaryKey', []))) or _field_req_var: _required = True if field.get('kds_classUri') in make_list(field.get('kds_requiredByDomain', {})): _required = True if _field_req_var == False: _required = False _new_field['kds_required'] = _required # Determine EditState if ("acl_Write" in _access_level) and ("kdr_NotEditable" \ not in _new_field['kds_actionList']): _new_field['editable'] = True else: _new_field['editable'] = False return _new_field
def get_wtform_field(field, instance='', **kwargs): ''' return a wtform field ''' _form_field = None _field_label = field.get("kds_formLabelName", '') #print("______label:", _field_label) _field_name = field.get("kds_formFieldName", '') _field_type_obj = field.get("kds_fieldType", {}) if isinstance(_field_type_obj.get('rdf_type'), list): _field_type_obj = _field_type_obj['rdf_type'][0] _field_validators = get_wtform_validators(field) _field_type = _field_type_obj.get('rdf_type', '') _field_row = float(field.get("kds_formLayoutRow",0)) _default_val = calculate_default_value(field) if _field_type == 'kdr_TextField': _form_field = StringField(_field_label, _field_validators, description=field.get('kds_formFieldHelp', '')) elif _field_type == 'kdr_OpenBadgeSenderField': _form_field = ButtonActionField(_field_label, description=field.get('kds_formFieldHelp', ''), #button_action="mozillaBackpackSender", #button_text={'true':"Resend",'false':'Claim now'} ) field['kds_call_in_display'] = True field['kds_buttonAction']="mozillaBackpackSender" field['kds_buttonText']={'true':"Resend",'false':'Claim now'} field['kds_errorLogPropUri']="kds_errorLog" #x=y elif _field_type == 'kdr_ServerField': _form_field = None #form_field = StringField(_field_label, _field_validators, description= \ #field.get('kds_formFieldHelp', '')) elif _field_type == 'kdr_TextAreaField': _form_field = TextAreaField(_field_label, _field_validators, description=field.get('kds_formFieldHelp', '')) elif _field_type == 'kdr_PasswordField': #print("!!!! Mode: ", _field_type_obj.get('fieldMode')) _field_mode = _field_type_obj.get('kds_fieldMode', '') if _field_mode == "kdr_InitialPassword": _form_field = [{"kds_fieldName":_field_name, "kds_field":PasswordField(_field_label, _field_validators, description=\ field.get('kds_formFieldHelp',\ ''))}, {"kds_fieldName":_field_name + "_confirm", "kds_field":PasswordField("Re-enter"), "doNotSave":True}] elif _field_mode == "kdr_ChangePassword": _form_field = [{"kds_fieldName":_field_name + "_old", "kds_field":PasswordField("Current"), "doNotSave":True}, {"kds_fieldName":_field_name, "kds_field":PasswordField("New"), "kds_formLayoutRow":_field_row + .01}, {"kds_fieldName":_field_name + "_confirm", "kds_field":PasswordField("Re-enter"), "doNotSave":True, "kds_formLayoutRow":_field_row + .02}] elif _field_mode == "kdr_LoginPassword": _form_field = PasswordField(_field_label, [InputRequired()], description=\ field.get('kds_formFieldHelp', '')) elif _field_type == 'kdr_BooleanField': _form_field = BooleanField(_field_label, _field_validators, description=field.get('kds_formFieldHelp', '')) elif _field_type == 'kdr_FileField': _form_field = FileField(_field_label, _field_validators, description=field.get('kds_formFieldHelp', '')) elif _field_type == 'kdr_HiddenField': _form_field = FileField(_field_label, _field_validators, description=field.get('kds_formFieldHelp', '')) elif _field_type == 'kdr_DateField': _date_format = rdfw().app.get(\ 'kds_dataFormats', {}).get('kds_pythonDateFormat', '') #print("date validators:\n", _field_validators) _add_optional = True for _val in _field_validators: if isinstance(_val, InputRequired): _add_optional = False break if _add_optional: _field_validators = [Optional()] + _field_validators _form_field = DateField(_field_label, _field_validators, description=field.get('kds_formFieldHelp', ''), default=_default_val, format=_date_format) field['kds_css'] += " dp" elif _field_type == 'kdr_DateTimeField': _form_field = DateTimeField(_field_label, _field_validators, description=field.get('kds_formFieldHelp', '')) elif _field_type == 'kdr_SelectField': #print("--Select Field: ", _field_label, _field_validators, description= \ #field.get('kds_formFieldHelp', '')) _form_field = SelectField(_field_label, _field_validators, description=field.get('kds_formFieldHelp', '')) #_form_field = StringField(_field_label, _field_validators, description= \ #field.get('kds_formFieldHelp', '')) elif _field_type == 'kdr_ImageFileOrURLField': if instance == "kdr_DisplayForm": _form_field = StringField(_field_label, description=field.get('kds_formFieldHelp', '')) field['kds_formFieldName'] = field['kds_formFieldName'] + "_image" print(" image count ") else: _form_field = [{"kds_fieldName":_field_name +"_image", "kds_field":FileField("Image File")}, {"kds_fieldName":_field_name + "_url", "kds_field":StringField("Image Url", [URL])}] elif _field_type == 'kdr_SubForm': from .rdfforms import rdf_framework_form_factory _sub_form_instance = _field_type_obj.get('kds_subFormInstance',\ 'kdr_LinkWithParent') if _sub_form_instance == 'kdr_LinkWithParent': _sub_form_instance = instance _form_path = rdfw().get_form_path(\ _field_type_obj.get('kds_subFormUri'), instance) kwargs['is_subobj'] = True _sub_form = FormField(\ rdf_framework_form_factory(_form_path, is_subobj=True), widget=BsGridTableWidget()) if "RepeatingSubForm" in _field_type_obj.get("kds_subFormMode"): _form_field = FieldList(_sub_form, _field_label, min_entries=1, widget=RepeatingSubFormWidget()) setattr(_form_field,"frameworkField","RepeatingSubForm") else: _form_field = _sub_form setattr(_form_field,"frameworkField","subForm") elif _field_type == 'kdr_FieldList': _field_json = dict.copy(field) _field_type_obj['rdf_type'] = _field_type_obj['kds_listFieldType'] _field_json['kds_fieldType'] = _field_type_obj list_field = get_wtform_field(_field_json, instance, **kwargs)['fld'] _form_field = FieldList(list_field, _field_label, min_entries=1) else: _form_field = StringField(_field_label, _field_validators, description=field.get('kds_formFieldHelp', '')) #print("--_form_field: ", _form_field) return {"fld": _form_field, "fld_json": field, "form_js": None}
def get_api_field_json(field, instructions, instance, user_info, item_permissions=None): '''This function will read through the RDF defined info and proccess the json to return the correct values for the instance, security and details''' if DEBUG: debug = True else: debug = False if item_permissions is None: item_permissions = [] _rdf_app = rdfw().app instance = instance.replace(".html", "") # get class property info try: _class_prop = getattr(rdfw(), field.get(\ 'kds_classUri')).kds_properties.get(field.get('kds_propUri'),{}) except: _class_prop = {} # merge the class prop attributes with the api prop #field = {**_class_prop, **field} temp_field = _class_prop.copy() temp_field.update(field) field = temp_field # Determine Security Access _new_field = {} _access_level = get_field_security_access(field, user_info, item_permissions) if "acl_Read" not in _access_level: return None _new_field['accessLevel'] = _access_level # get api instance info _api_instance_info = {} _api_field_instance_type_list = make_list(field.get('kds_apiInstance', field.get(\ 'kds_apiDefault', {}).get('kds_apiInstance', []))) if debug: print("instance type list: ", _api_field_instance_type_list) if debug: print("instance: ", instance) for _field_instance in _api_field_instance_type_list: if _field_instance.get('kds_apiInstanceType') == instance: _api_instance_info = _field_instance if debug: print("instance info\n", _api_instance_info) # Determine the field paramaters _new_field['kds_apiFieldName'] = _api_instance_info.get('kds_apiFieldName', field.get(\ "kds_apiFieldName", field.get('kds_apiDefault', {}).get(\ 'kds_apiFieldName', ""))) _new_field['kds_fieldType'] = _api_instance_info.get('kds_fieldType', field.get(\ 'kds_fieldType', field.get('kds_apiDefault', {}).get('kds_fieldType', ""))) if not isinstance(_new_field['kds_fieldType'], dict): _new_field['kds_fieldType'] = {"rdf_type": _new_field['kds_fieldType']} _new_field['kds_apiLabelName'] = _api_instance_info.get('kds_apiLabelName', \ field.get("kds_apiLabelName", field.get('kds_apiDefault', {}).get(\ 'kds_apiLabelName', ""))) _new_field['kds_apiFieldHelp'] = _api_instance_info.get('kds_apiFieldHelp', \ field.get("apiFieldHelp", field.get('apiDefault', {}).get(\ 'kds_apiFieldHelp', ""))) _new_field['kds_apiFieldOrder'] = _api_instance_info.get('kds_apiFieldOrder', \ field.get("kds_apiFieldOrder", field.get('kds_apiDefault', {}).get(\ 'kds_apiFieldOrder', ""))) _new_field['kds_apiLayoutRow'] = _api_instance_info.get('kds_apiLayoutRow', \ field.get("kds_apiLayoutRow", field.get('kds_apiDefault', {}).get(\ 'kds_apiLayoutRow', ""))) _new_field['rdfs_range'] = field.get('rdfs_range') _new_field['kds_defaultVal'] = _api_instance_info.get('kds_defaultVal',\ field.get('kds_defaultVal')) _new_field['kds_propUri'] = field.get('kds_propUri') _new_field['kds_classUri'] = field.get('kds_classUri') _new_field['kds_returnValue'] = field.get('kds_returnValue') # get applicationActionList _new_field['kds_actionList'] = make_set(_api_instance_info.get(\ 'kds_applicationAction', set())) _new_field['kds_actionList'].union( make_set(field.get('kds_applicationAction', set()))) _new_field['kds_actionList'] = list(_new_field['kds_actionList']) if debug: print("action List:_______________", _new_field['kds_actionList']) if "kdr_RemoveFromApi" in\ _new_field['kds_actionList']: return None # get valiator list if field.get('kds_overrideValidation'): _new_field['kds_validators'] = field.get('kds_overrideValidation') else: _new_field['kds_validators'] = make_list(\ _api_instance_info.get('kds_apiValidation', [])) _new_field['kds_validators'] += make_list(\ field.get('kds_apiValidation', [])) _new_field['kds_validators'] += make_list(\ field.get('kds_propertyValidation', [])) # get processing list _new_field['kds_processors'] = make_list( _api_instance_info.get('kds_apiProcessing', [])) _new_field['kds_processors'] += make_list( field.get('kds_apiProcessing', [])) _new_field['kds_processors'] += make_list( field.get('kds_propertyProcessing', [])) if debug: if field['kds_propUri'] == "schema_image": x = 1 # get required state _required = False _field_req_var = cbool(field.get('kds_requiredField')) if (field.get('kds_propUri') in make_list(field.get('kds_classInfo', {}).get(\ 'kds_primaryKey', []))) or _field_req_var: _required = True if field.get('kds_classUri') in make_list( field.get('kds_requiredByDomain', {})): _required = True if _field_req_var == False: _required = False _new_field['kds_required'] = _required # Determine EditState if ("acl_Write" in _access_level) and ("kdr_NotEditable" \ not in _new_field['kds_actionList']): _new_field['editable'] = True else: _new_field['editable'] = False return _new_field
def rdf_api(api_name, id_value=None, ext=None): """View for displaying forms Args: api_name -- url path of the api (new, edit) ext -- url extension for the api ie (.json, .html) params: id -- the item to lookup """ if not DEBUG: debug = False else: debug = False if debug: print("START rdf_api blueprint.py ---------------------------\n") api_repsonder = falcon.API() _api_path = "|".join(remove_null([api_name, ext])) _api_exists = rdfw().api_exists(_api_path) if _api_exists is False: return render_template( "error_page_template.html", error_message="The web address is invalid") api_uri = _api_exists.get("api_uri") # generate the api class base_url = "%s%s" % (request.url_root[:-1], url_for("open_badge.base_path")) current_url = request.url base_api_url = "%s%sapi/" % (request.url_root[:-1], url_for("open_badge.base_path")) api_url = request.base_url api_class = rdf_framework_api_factory(_api_path, base_url=base_url, current_url=current_url, base_api_url=base_api_url, api_url=api_url) # if request method is post if request.method == "POST": # let api load with post data api = api_class(id_value=id_value) # validate the form if api.validate(): # if validated save the form api.save() if api.save_state == "success": if debug: print("END rdf_api blueprint.py ---POST--------\n") return api.return_message # if not POST, check the args and api instance/extension else: api = api_class() api_data = rdfw().get_obj_data(api, id_value=id_value) #pp.pprint(api_data['form_data']) if not (len(api_data['query_data']) > 0): '''return render_template( "error_page_template.html", error_message="The item does not exist") ''' return abort(400) else: return_type = api.rdf_instructions.get("kds_returnType") if return_type == "file": repo_uri = clean_iri(list(api_data['obj_json'].values())[0]) repo_link = urlopen(repo_uri) repo_file = repo_link.read() # The File wrapper is causing issues in the live environment # need to delete before sending byte stream if debug: print("\t wsgi.file_wrapper pre: ",\ request.environ.get('wsgi.file_wrapper')) if request.environ.get('wsgi.file_wrapper') is not None: del(request.environ['wsgi.file_wrapper']) if debug: print("\t wsgi.file_wrapper post: ",\ request.environ.get('wsgi.file_wrapper')) if debug: print("END rdf_api blueprint.py --- file send ---\n") return send_file(io.BytesIO(repo_file), #return send_file(repo_link, attachment_filename="%s.%s" % (id_value, ext), mimetype=api.rdf_instructions.get("kds_mimeType")) else: #return "<pre>{}</pre>".format(json.dumps(api_data['obj_json'],indent=4)) if debug: print("END rdf_api blueprint.py --- json --------\n") return jsonify(api_data['obj_json'])
def test_rdf_class(): """View for displaying a test RDF class""" f=rdfw() #This is an intentional error to cause a break in the code y=z return "<pre>{}</pre>".format(json.dumps({"message": "test rdf class"}))
def get_wtform_field(field, instance='', **kwargs): ''' return a wtform field ''' _form_field = None _field_label = field.get("kds_formLabelName", '') #print("______label:", _field_label) _field_name = field.get("kds_formFieldName", '') _field_type_obj = field.get("kds_fieldType", {}) if isinstance(_field_type_obj.get('rdf_type'), list): _field_type_obj = _field_type_obj['rdf_type'][0] _field_validators = get_wtform_validators(field) _field_type = _field_type_obj.get('rdf_type', '') _field_row = float(field.get("kds_formLayoutRow", 0)) _default_val = calculate_default_value(field) if _field_type == 'kdr_TextField': _form_field = StringField(_field_label, _field_validators, description=field.get( 'kds_formFieldHelp', '')) elif _field_type == 'kdr_OpenBadgeSenderField': _form_field = ButtonActionField( _field_label, description=field.get('kds_formFieldHelp', ''), #button_action="mozillaBackpackSender", #button_text={'true':"Resend",'false':'Claim now'} ) field['kds_call_in_display'] = True field['kds_buttonAction'] = "mozillaBackpackSender" field['kds_buttonText'] = {'true': "Resend", 'false': 'Claim now'} field['kds_errorLogPropUri'] = "kds_errorLog" #x=y elif _field_type == 'kdr_ServerField': _form_field = None #form_field = StringField(_field_label, _field_validators, description= \ #field.get('kds_formFieldHelp', '')) elif _field_type == 'kdr_TextAreaField': _form_field = TextAreaField(_field_label, _field_validators, description=field.get( 'kds_formFieldHelp', '')) elif _field_type == 'kdr_PasswordField': #print("!!!! Mode: ", _field_type_obj.get('fieldMode')) _field_mode = _field_type_obj.get('kds_fieldMode', '') if _field_mode == "kdr_InitialPassword": _form_field = [{"kds_fieldName":_field_name, "kds_field":PasswordField(_field_label, _field_validators, description=\ field.get('kds_formFieldHelp',\ ''))}, {"kds_fieldName":_field_name + "_confirm", "kds_field":PasswordField("Re-enter"), "doNotSave":True}] elif _field_mode == "kdr_ChangePassword": _form_field = [{ "kds_fieldName": _field_name + "_old", "kds_field": PasswordField("Current"), "doNotSave": True }, { "kds_fieldName": _field_name, "kds_field": PasswordField("New"), "kds_formLayoutRow": _field_row + .01 }, { "kds_fieldName": _field_name + "_confirm", "kds_field": PasswordField("Re-enter"), "doNotSave": True, "kds_formLayoutRow": _field_row + .02 }] elif _field_mode == "kdr_LoginPassword": _form_field = PasswordField(_field_label, [InputRequired()], description=\ field.get('kds_formFieldHelp', '')) elif _field_type == 'kdr_BooleanField': _form_field = BooleanField(_field_label, _field_validators, description=field.get( 'kds_formFieldHelp', '')) elif _field_type == 'kdr_FileField': _form_field = FileField(_field_label, _field_validators, description=field.get('kds_formFieldHelp', '')) elif _field_type == 'kdr_HiddenField': _form_field = FileField(_field_label, _field_validators, description=field.get('kds_formFieldHelp', '')) elif _field_type == 'kdr_DateField': _date_format = rdfw().app.get(\ 'kds_dataFormats', {}).get('kds_pythonDateFormat', '') #print("date validators:\n", _field_validators) _add_optional = True for _val in _field_validators: if isinstance(_val, InputRequired): _add_optional = False break if _add_optional: _field_validators = [Optional()] + _field_validators _form_field = DateField(_field_label, _field_validators, description=field.get('kds_formFieldHelp', ''), default=_default_val, format=_date_format) field['kds_css'] += " dp" elif _field_type == 'kdr_DateTimeField': _form_field = DateTimeField(_field_label, _field_validators, description=field.get( 'kds_formFieldHelp', '')) elif _field_type == 'kdr_SelectField': #print("--Select Field: ", _field_label, _field_validators, description= \ #field.get('kds_formFieldHelp', '')) _form_field = SelectField(_field_label, _field_validators, description=field.get( 'kds_formFieldHelp', '')) #_form_field = StringField(_field_label, _field_validators, description= \ #field.get('kds_formFieldHelp', '')) elif _field_type == 'kdr_ImageFileOrURLField': if instance == "kdr_DisplayForm": _form_field = StringField(_field_label, description=field.get( 'kds_formFieldHelp', '')) field['kds_formFieldName'] = field['kds_formFieldName'] + "_image" print(" image count ") else: _form_field = [{ "kds_fieldName": _field_name + "_image", "kds_field": FileField("Image File") }, { "kds_fieldName": _field_name + "_url", "kds_field": StringField("Image Url", [URL]) }] elif _field_type == 'kdr_SubForm': from .rdfforms import rdf_framework_form_factory _sub_form_instance = _field_type_obj.get('kds_subFormInstance',\ 'kdr_LinkWithParent') if _sub_form_instance == 'kdr_LinkWithParent': _sub_form_instance = instance _form_path = rdfw().get_form_path(\ _field_type_obj.get('kds_subFormUri'), instance) kwargs['is_subobj'] = True _sub_form = FormField(\ rdf_framework_form_factory(_form_path, is_subobj=True), widget=BsGridTableWidget()) if "RepeatingSubForm" in _field_type_obj.get("kds_subFormMode"): _form_field = FieldList(_sub_form, _field_label, min_entries=1, widget=RepeatingSubFormWidget()) setattr(_form_field, "frameworkField", "RepeatingSubForm") else: _form_field = _sub_form setattr(_form_field, "frameworkField", "subForm") elif _field_type == 'kdr_FieldList': _field_json = dict.copy(field) _field_type_obj['rdf_type'] = _field_type_obj['kds_listFieldType'] _field_json['kds_fieldType'] = _field_type_obj list_field = get_wtform_field(_field_json, instance, **kwargs)['fld'] _form_field = FieldList(list_field, _field_label, min_entries=1) else: _form_field = StringField(_field_label, _field_validators, description=field.get( 'kds_formFieldHelp', '')) #print("--_form_field: ", _form_field) return {"fld": _form_field, "fld_json": field, "form_js": None}
def create_data_sparql_query(obj, **kwargs): ''' generates the sparql query for getting an object's data ''' if not DEBUG: debug = False else: debug = False if debug: print("START create_data_sparql_query -----------------------\n") if debug: print("*** kwargs ***: \n%s \n*** obj ***:\n%s" % (pp.pformat(kwargs), pp.pformat(obj.__dict__))) from rdfframework import RdfDataType subject_uri = kwargs.get("subject_uri", obj.data_subject_uri) _class_uri = kwargs.get("class_uri", obj.data_class_uri) _formated_val = None _lookup_triple = "" if obj.rdf_instructions.get("kds_subjectUriTransform"): if obj.rdf_instructions.get("kds_subjectUriTransform") == \ "kdr_UidToRepositoryUri": id_value = kwargs.get("id_value") if kwargs.get("id_value"): _subject_uri = uid_to_repo_uri(id_value) subject_uri = _subject_uri obj.data_subject_uri = _subject_uri elif obj.rdf_instructions.get("kds_subjectUriTransform") == \ "kdr_UidToTriplestoreUri": id_value = kwargs.get("id_value") if kwargs.get("id_value"): rdf_class = getattr(rdfw(), obj.data_class_uri) subject_uri = rdf_class.uri_patterner(id_value) obj.data_subject_uri = subject_uri elif kwargs.get("id_value") or obj.rdf_instructions.get("kds_lookupPropertyUri"): # find the details for formating the sparql query for the supplied # id_value or lookup via a property Value id_value = kwargs.get("id_value") if not id_value: id_value = subject_uri _kds_propUri = obj.rdf_instructions.get("kds_lookupPropertyUri") _rdf_class_uri = obj.rdf_instructions.get("kds_lookupPropertyClass") if not _rdf_class_uri: _rdf_class_uri = obj.rdf_instructions.get("kds_lookupClassUri") _rdf_class = getattr(rdfw(),_rdf_class_uri) _rdf_prop = _rdf_class.kds_properties[_kds_propUri] _range = make_list(_rdf_prop.get("rdfs_range"))[0] _formated_val = RdfDataType(_range.get("rangeClass")).sparql(id_value) _lookup_triple = "\t{}\n\t{}\n\t".format( make_triple("?subject", "a", iri(uri(_rdf_class.kds_classUri))), make_triple("?subject", iri(uri(_kds_propUri)), _formated_val)) subject_uri = "?subject" subject_lookup = kwargs.get("subject_lookup") if subject_lookup: # subject lookup will pull a subject and all of its related data _kds_propUri = iri(uri(subject_lookup.kds_propUri)) _data_type = uri(make_list(subject_lookup.rdfs_range)[0]) _prop_value = RdfDataType(_data_type).sparql(\ str(subject_lookup.data)) _sparql = render_without_request("sparqlRelatedItemDataTemplate.rq", prefix=rdfw().get_prefix(), kds_propUri=_kds_propUri, prop_value=_prop_value) return _sparql _lookup_class_uri = _class_uri _sparql_args = None _sparql_constructor = copy.deepcopy(obj.dependancies) if debug: print("+++++++++++++++++++++++ Dependancies:") pp.pprint(_sparql_constructor) _base_subject_finder = None _linked_class = None _linked_prop = False _sparql_elements = [] _subform_data = {} _data_list = obj.is_subobj _parent_field = None if is_not_null(subject_uri): # find the primary linkage between the supplied subjectId and # other form classes for _rdf_class in _sparql_constructor: for _prop in _sparql_constructor[_rdf_class]: try: if _class_uri == _prop.get("kds_classUri"): _sparql_args = _prop _linked_class = _rdf_class _sparql_constructor[_rdf_class].remove(_prop) if _rdf_class != _lookup_class_uri: _linked_prop = True except: pass # generate the triple pattern for linked class if debug: print("+++++++++++++++++++++++ SPARQL Constructor") pp.pprint(_sparql_constructor) if _sparql_args: # create a binding for multi-item results if _data_list: _list_binding = "BIND(?classID AS ?itemID) ." else: _list_binding = '' # provide connection triples for the id subject and associated # rdf class format_string = "{}BIND({} AS ?baseSub) .\n\t{}\n\t{}\n\t{}" _base_subject_finder = format_string.format( _lookup_triple, iri(subject_uri), make_triple("?baseSub", "a", iri(uri(_lookup_class_uri))), make_triple("?classID", iri(uri(_sparql_args.get("kds_propUri"))), "?baseSub"), _list_binding) # if there is a linkage between subject_uri and another associated # property in object if _linked_prop: # create a binding for multi-item results if _data_list: _list_binding = "BIND(?s AS ?itemID) ." else: _list_binding = '' format_string = \ "{}BIND({} AS ?baseSub) .\n\t{}\n\t{}\n\t{}\n\t?s ?p ?o ." _sparql_elements.append(format_string.format(\ _lookup_triple, iri(subject_uri), make_triple("?baseSub", "a", iri(uri(_lookup_class_uri))), make_triple("?s", iri(uri(_sparql_args.get("kds_propUri"))), "?baseSub"), _list_binding)) # iterrate though the classes used in the object and generate the # spaqrl triples to pull the data for that class for _rdf_class in _sparql_constructor: if _rdf_class == _class_uri: if _data_list: _list_binding = "BIND(?s AS ?itemID) ." else: _list_binding = '' if is_not_null(_lookup_triple) and is_not_null(_list_binding): format_string = \ "{}BIND({} AS ?basesub).\n\t{}\n\t{}\n\t{}\n\t?s ?p ?o ." _sparql_elements.append(format_string.format( _lookup_triple, iri(subject_uri), make_triple('?baseSub','a',iri(uri(_lookup_class_uri))), make_triple('?classID',iri(uri(_sparql_args.get("kds_propUri"))),'?s'), "BIND(?classID AS ?itemID) .")) else: format_string = \ "\t{}BIND({} AS ?s) .\n\t{}\n\t{}\n\t?s ?p ?o ." _sparql_elements.append(format_string.format( _lookup_triple, iri(subject_uri), make_triple("?s", "a", iri(uri(_lookup_class_uri))), _list_binding)) for _prop in _sparql_constructor[_rdf_class]: if _rdf_class == _class_uri: if _data_list: _list_binding = "BIND(?s AS ?itemID) ." else: _list_binding = '' format_string = \ "\t{}BIND({} AS ?baseSub) .\n\t{}\n\t{}\n\t{}\n\t?s ?p ?o ." _sparql_arg = format_string.format(\ _lookup_triple, iri(subject_uri), make_triple("?baseSub", "a", iri(uri(_lookup_class_uri))), make_triple("?baseSub", iri(uri(_prop.get("kds_propUri"))), "?s"), _list_binding) _sparql_elements.append(_sparql_arg) elif _rdf_class == _linked_class: _sparql_elements.append( "\t{}\n\t{}\n\t?s ?p ?o .".format( _base_subject_finder, make_triple("?classID", iri(uri(_prop.get("kds_propUri"))), "?s") ) ) '''**** The case where an ID looking up a the triples for a non-linked related is not functioning i.e. password ClassID not looking up person org triples if the org class is not used in the form. This may not be a problem ... the below comment out is a start to solving if it is a problem elif _linked_class != self.get_class_name(prop.get(\ "classUri")): _sparql_elements.append( "\t" +_base_subject_finder + "\n " + "\t"+ make_triple("?classID", iri(prop.get(\ "propUri")), "?s") + "\n\t?s ?p ?o .")''' # merge the sparql elements for each class used into one combined # sparql union statement _sparql_unions = "{{\n{}\n}}".format("\n} UNION {\n".join(\ _sparql_elements)) if _data_list: _list_binding = "?itemID" else: _list_binding = '' # render the statment in the jinja2 template _sparql = render_without_request("sparqlItemTemplate.rq", prefix=rdfw().get_prefix(), query=_sparql_unions, list_binding=_list_binding) if debug: print("SPARQL query") print(_sparql) if debug: print("END create_data_sparql_query ---------------------\n") return _sparql
def rdf_class_forms(form_name, form_instance=None): """View for displaying forms Args: form_instance -- Type of form (new, edit) params: id -- the subject uri of the form data to lookup """ _display_mode = False _form_path = "/".join(remove_null([form_name, form_instance])) # test to see if the form exists _form_exists = rdfw().form_exists(_form_path) if _form_exists is False: return render_template( "error_page_template.html", error_message="The web address is invalid") # if the form exists continue instance_uri = _form_exists.get("instance_uri") form_uri = _form_exists.get("form_uri") # generate the form class form_class = rdf_framework_form_factory(_form_path, \ base_url=url_for("open_badge.base_path"), current_url=request.url) # test to see if the form requires a login login_message = None if cbool(form_class.rdf_instructions.get("kds_loginRequired",False)) is \ True: if isinstance(current_user.is_authenticated, bool): auth = current_user.is_authenticated else: auth = current_user.is_authenticated() if not auth: current_app.login_manager.login_message = \ "Please log in to access this page" return current_app.login_manager.unauthorized() # if request method is post if request.method == "POST": # let form load with post data form = form_class(subject_uri=request.args.get("id")) # validate the form if form.validate(): # if validated save the form obj = form.save() if form.save_state == "success": if isinstance(form.save_results, User): login_user(form.save_results) #x=y return redirect(form.redirect_url(params=request.args)) #form = form_class(subject_uri=request.args.get("id")) # if not POST, check the args and form instance else: # if params are present for any forms that are not in any of # the below forms remove the params if instance_uri not in ["kdr_EditForm", "kdr_DisplayForm", "kdr_Login"]\ and request.args.get("id"): redirect_url = url_for("open_badge.rdf_class_forms", form_name=form_name, form_instance=form_instance) return redirect(redirect_url) # if the there is no ID argument and on the editform instance -> # redirect to NewForm if instance_uri in ["kdr_EditForm","kdr_DisplayForm"] and \ not request.args.get("id"): redirect_url = url_for("open_badge.base_path") + \ rdfw().get_form_path(form_uri, "kdr_NewForm") return redirect(redirect_url) # if the display form does not have an ID return an error if instance_uri in ["kdr_DisplayForm"] and not request.args.get("id"): return render_template( "error_page_template.html", error_message="The item does not exist") # if the there is an ID argument and on the editform instance -> # query for the save item if request.args.get("id") and instance_uri \ in ["kdr_EditForm","kdr_DisplayForm"]: if instance_uri == "kdr_DisplayForm": _display_mode = True form_data = rdfw().get_obj_data(form_class(\ no_query=True, subject_uri=request.args.get("id"))) #pp.pprint(form_data['form_data']) form = form_class(form_data['obj_data'],\ query_data=form_data['query_data'],\ subject_uri=request.args.get("id")) if not (len(form_data['query_data']) > 0): return render_template( "error_page_template.html", error_message="The item does not exist") # if not on EditForm or DisplayForm render form else: form = form_class() template = render_template( "/forms/default/app_form_template.html", actionUrl=request.url, form=form, display_mode = _display_mode, dateFormat = rdfw().app.get(\ 'kds_dataFormats',{}).get('kds_javascriptDateFormat',''), debug=request.args.get("debug",False), login_message=login_message) return template
def rdf_generic_api(class_uri, prop_uri): if not DEBUG: debug = False else: debug = True if debug: print("START rdf_generic_api ----------------------------\n") subject_uri = request.args.get("id") data = request.form.get("dataValue") subject_uri = request.form.get("id", subject_uri) if debug: print("class_uri: %s prop_uri: %s" % (class_uri, prop_uri)) if debug: print('subject_uri: ', subject_uri) if debug: print('data: ', data) if prop_uri in ["obi_claimDate", "kds_errorLog" ] and class_uri == "obi_Assertion": if hasattr(request, "form"): csrf = request.form.get("csrf") else: if debug: print("aborting **************") return abort(400) subject_uri = request.args.get("id") data = request.form.get("dataValue") subject_uri = request.form.get("id", subject_uri) #if debug: print("REQUEST dict: \n", pp.pformat(request.__dict__)) rdf_class = getattr(rdfw(), class_uri) prop_json = rdf_class.kds_properties.get(prop_uri) prop_json['kds_classUri'] = class_uri prop_json['kds_apiFieldName'] = prop_uri prop = RdfProperty(prop_json, data, subject_uri) base_url = "%s%s" % (request.url_root[:-1], url_for("app.base_path")) current_url = request.url base_api_url = "%s%sapi/form_generic_prop/" % (request.url_root[:-1], url_for("app.base_path")) if debug: print('rdf_class: ', rdf_class) print('prop_json: ', prop_json) print('prop: ', prop) print('base_url: ', base_url) print('current_url: ', current_url) print('base_api_url: ', base_api_url) api_url = request.base_url rdf_obj = Api(subject_uri=subject_uri, data_class_uri=class_uri, data_prop_uri=prop_uri, rdf_field_list=[prop_json], prop_list=[prop], base_url=base_url, current_url=current_url, base_api_url=base_api_url, api_url=api_url) if request.method == "POST": save_result = rdf_obj.save() if debug: print("**** save_result:\n", pp.pformat(save_result.__dict__)) if debug: print("END rdf_generic_api POST -------------------------\n") return jsonify(save_result.save_results[0]) else: api_data = rdfw().get_obj_data(rdf_obj) if debug: print("\t**** api_data:\n", pp.pprint(api_data)) if debug: print("END rdf_generic_api GET --------------------------\n") return json.dumps(api_data['obj_json'], indent=4)
def get_form_instructions_json(instructions, instance): ''' This function will read through the RDF defined info and proccess the json to retrun the correct instructions for the specified form instance.''' _rdf_app = rdfw().app #print("inst------", instructions) # get form instance info _form_instance_info = {} _form_instance_type_list = make_list(instructions.get('kds_formInstance', [])) for _form_instance in _form_instance_type_list: if _form_instance.get('kds_formInstanceType') == instance: _form_instance_info = _form_instance _new_instr = {} #print("------", _form_instance_info) #Determine the form paramaters _new_instr['kds_formTitle'] = _form_instance_info.get('kds_formTitle', \ instructions.get("kds_formTitle", "")) _new_instr['kds_formDescription'] = _form_instance_info.get('kds_formDescription', \ instructions.get("kds_formDescription", "")) _new_instr['kds_form_Method'] = _form_instance_info.get('kds_form_Method', \ instructions.get("kds_form_Method", "")) _new_instr['kds_form_enctype'] = _form_instance_info.get('kds_form_enctype', \ instructions.get("kds_form_enctype", "")) _new_instr['kds_propertyAddOnCss'] = _form_instance_info.get('kds_propertyAddOnCss', \ instructions.get("kds_propertyAddOnCss", "")) _new_instr['kds_lookupClassUri'] = _form_instance_info.get('kds_lookupClassUri', \ instructions.get("kds_lookupClassUri", "")) _new_instr['kds_lookupPropertyUri'] =\ _form_instance_info.get('kds_lookupPropertyUri',\ instructions.get("kds_lookupPropertyUri")) _new_instr['kds_submitSuccessRedirect'] = \ _form_instance_info.get('kds_submitSuccessRedirect', instructions.get(\ "kds_submitSuccessRedirect", "")) _new_instr['kds_submitFailRedirect'] = \ _form_instance_info.get('kds_submitFailRedirect', instructions.get("kds_submitFailRedirect", "")) _new_instr['kds_saveAction'] = \ _form_instance_info.get('kds_saveAction', instructions.get("kds_saveAction", "")) _new_instr["kds_lookupPropertyClass"] = \ _form_instance_info.get('"kds_lookupPropertyClass"', instructions.get("kds_lookupPropertyClass")) _new_instr["kds_loginRequired"] = \ _form_instance_info.get('"kds_loginRequired"', instructions.get("kds_loginRequired")) # Determine css classes #form row css css = _form_instance_info.get('kds_rowOverideCss', instructions.get(\ 'kds_rowOverideCss', None)) if css is None: css = _rdf_app.get('kds_formDefault', {}).get('kds_rowCss', '') css = css.strip() + " " + _form_instance_info.get('kds_rowAddOnCss', \ instructions.get('kds_rowAddOnCss', '')) css = css.strip() css.strip() _new_instr['kds_rowCss'] = css #form general css css = _form_instance_info.get('kds_formOverideCss', instructions.get(\ 'kds_formOverideCss', None)) if css is None: css = _rdf_app.get('kds_formDefault', {}).get('kds_formCss', '') css = css.strip() + " " + _form_instance_info.get('kds_formAddOnCss', \ instructions.get('kds_formAddOnCss', '')) css = css.strip() css.strip() _new_instr['kds_formCss'] = css return _new_instr
def xsd_to_python(value, data_type, rdf_type="literal", output="python"): ''' This will take a value and xsd data_type and convert it to a python variable''' from rdfframework import get_framework as rdfw if data_type: data_type = data_type.replace(str(XSD), "") if not value: return value elif rdf_type == "uri": return iri(value) elif not is_not_null(value): return value elif data_type == "xsd_anyURI": # URI (Uniform Resource Identifier) return value elif data_type == "xsd_base64Binary": # Binary content coded as "base64" return value.decode() elif data_type == "xsd_boolean": # Boolean (true or false) return cbool(value) elif data_type == "xsd_byte": # Signed value of 8 bits return value.decode() elif data_type == "xsd_date": ## Gregorian calendar date _temp_value = parse(value) if output == "string": _date_format = rdfw().app['kds_dataFormats'].get(\ 'kds_pythonDateFormat', '') return _temp_value.strftime(_date_format) elif output == "python": return _temp_value elif data_type == "xsd_dateTime": ## Instant of time (Gregorian calendar) _temp_value = parse(value) if output == "string": _date_format = rdfw().app['kds_dataFormats'].get(\ 'kds_pythonDateTimeFormat', '') return _temp_value.strftime(_date_format) elif output == "python": return _temp_value elif data_type == "xsd_decimal": # Decimal numbers return float(value) elif data_type == "xsd_double": # IEEE 64 return float(value) elif data_type == "xsd_duration": # Time durations return timedelta(milleseconds=float(value)) elif data_type == "xsd_ENTITIES": # Whitespace return value elif data_type == "xsd_ENTITY": # Reference to an unparsed entity return value elif data_type == "xsd_float": # IEEE 32 return float(value) elif data_type == "xsd_gDay": # Recurring period of time: monthly day return value elif data_type == "xsd_gMonth": # Recurring period of time: yearly month return value elif data_type == "xsd_gMonthDay": # Recurring period of time: yearly day return value elif data_type == "xsd_gYear": # Period of one year return value elif data_type == "xsd_gYearMonth": # Period of one month return value elif data_type == "xsd_hexBinary": # Binary contents coded in hexadecimal return value elif data_type == "xsd_ID": # Definition of unique identifiers return value elif data_type == "xsd_IDREF": # Definition of references to unique identifiers return value elif data_type == "xsd_IDREFS": # Definition of lists of references to unique identifiers return value elif data_type == "xsd_int": # 32 return value elif data_type == "xsd_integer": # Signed integers of arbitrary length return int(value) elif data_type == "xsd_language": # RFC 1766 language codes return value elif data_type == "xsd_long": # 64 return int(value) elif data_type == "xsd_Name": # XML 1.O name return value elif data_type == "xsd_NCName": # Unqualified names return value elif data_type == "xsd_negativeInteger": # Strictly negative integers of arbitrary length return abs(int(value)) * -1 elif data_type == "xsd_NMTOKEN": # XML 1.0 name token (NMTOKEN) return value elif data_type == "xsd_NMTOKENS": # List of XML 1.0 name tokens (NMTOKEN) return value elif data_type == "xsd_nonNegativeInteger": # Integers of arbitrary length positive or equal to zero return abs(int(value)) elif data_type == "xsd_nonPositiveInteger": # Integers of arbitrary length negative or equal to zero return abs(int(value)) * -1 elif data_type == "xsd_normalizedString": # Whitespace return value elif data_type == "xsd_NOTATION": # Emulation of the XML 1.0 feature return value elif data_type == "xsd_positiveInteger": # Strictly positive integers of arbitrary length return abs(int(value)) elif data_type == "xsd_QName": # Namespaces in XML return value elif data_type == "xsd_short": # 32 return value elif data_type == "xsd_string": # Any string return value elif data_type == "xsd_time": # Point in time recurring each day return parse(value) elif data_type == "xsd_token": # Whitespace return value elif data_type == "xsd_unsignedByte": # Unsigned value of 8 bits return value.decode() elif data_type == "xsd_unsignedInt": # Unsigned integer of 32 bits return int(value) elif data_type == "xsd_unsignedLong": # Unsigned integer of 64 bits return int(value) elif data_type == "xsd_unsignedShort": # Unsigned integer of 16 bits return int(value) else: return value
def rdf_framework_form_factory(form_url, **kwargs): ''' Generates a form class based on the form definitions in the kds-app.ttl file keyword Args: class_uri: the classUri used for a form with loaded data ***** has to be the class of the subject_uri for the form data lookup subject_uri: the uri of the object that you want to lookup is_subform: True or False. States whether the form is a subform of another form ''' # find the form name and instance from the url _form_location = rdfw().form_exists(form_url) # exit factory if form does not exist if _form_location is False: return None _form_uri = _form_location['form_uri'] _instance = _form_location['instance_uri'] rdf_form = type(_form_uri, (Form, ), {}) setattr(rdf_form, "form_uri", _form_uri) _app_form = rdfw().rdf_form_dict.get(_form_uri, {}) fields = _app_form.get('kds_properties') instructions = get_form_instructions_json(\ _app_form.get('kds_formInstructions'), _instance) _lookup_class_uri = kwargs.get("classUri",\ instructions.get("kds_lookupClassUri")) _lookup_prop_uri = kwargs.get("propUri", \ instructions.get("kds_lookupPropUri")) _lookup_subject_uri = kwargs.get("subject_uri") kwargs['subject_uri'] = _lookup_subject_uri kwargs["propUri"] = _lookup_prop_uri kwargs["classUri"] = _lookup_class_uri # ************************** Testing Variable ************************* user_info = { "kds_userGroups":["kdr_SysAdmin-SG"], 'kds_applicationSecurity':["acl_Read", "acl_Write"] } # ********************************************************************* _has_subobj = False rdf_field_list = [] for fld in fields: #print(fld) field = get_field_json(fld, instructions, _instance, user_info) if field: field_item = get_wtform_field(field, _instance, **kwargs) form_field = field_item.get('fld') field = field_item.get('fld_json') if isinstance(form_field, list): i = 0 for nfld in form_field: #print(fld) if nfld.get('kds_field'): _new_field = dict.copy(field) _new_field['kds_formFieldName'] = nfld['kds_fieldName'] _new_field['kds_formFieldOrder'] = \ float(_new_field['kds_formFieldOrder']) + i _new_field['kds_formLayoutRow'] = \ nfld.get("kds_formLayoutRow", _new_field['kds_formLayoutRow']) if nfld.get("doNotSave") == True: _new_field['doNotSave'] = True else: _new_field['doNotSave'] = False augmented_field = add_field_attributes(\ nfld['kds_field'],_new_field) rdf_field_list.append(_new_field) setattr(rdf_form, nfld['kds_fieldName'], augmented_field) i += .01 else: #print(field['formFieldName'], " - ", form_field) if form_field: #print("set --- ", field) augmented_field = add_field_attributes(form_field, field) field['doNotSave'] = False rdf_field_list.append(field) setattr(rdf_form, field['kds_formFieldName'], augmented_field) if hasattr(augmented_field,"frameworkField"): if "subform" in form_field.frameworkField.lower(): _has_subobj = True if kwargs.get("is_subobj"): field = {'kds_formFieldName':'subjectUri', 'kds_fieldType':{'rdf_type':'ReferenceField'}, 'kds_formLabelName':'Hidden dataSubjectUri', 'kds_classUri':_lookup_class_uri, 'kds_propUri':'subjectUri', 'kds_processors':[], 'kds_css':'form-control', 'editable': False, 'doNotSave': False} rdf_field_list.append(field) augmented_field = add_field_attributes(HiddenField('dataSubjectUri'), field) setattr(rdf_form, 'subjectUri', augmented_field) setattr(rdf_form, 'is_subobj', True) else: setattr(rdf_form, 'is_subobj', False) setattr(rdf_form, 'has_subobj', _has_subobj) setattr(rdf_form, 'rdf_field_list', rdf_field_list) setattr(rdf_form, "rdf_instructions", instructions) setattr(rdf_form, "instance_uri", _instance) setattr(rdf_form, "data_class_uri", _lookup_class_uri) setattr(rdf_form, "data_subject_uri", _lookup_subject_uri) setattr(rdf_form, "data_prop_uri", _lookup_prop_uri) setattr(rdf_form, "base_url", kwargs.get("base_url")) setattr(rdf_form, "current_url", kwargs.get("current_url")) #pp.pprint(rdf_form.__dict__) return rdf_form
def test_rdf_class(): """View for displaying a test RDF class""" f = rdfw() #This is an intentional error to cause a break in the code y = z return "<pre>{}</pre>".format(json.dumps({"message": "test rdf class"}))
def rdf_framework_form_factory(form_url, **kwargs): ''' Generates a form class based on the form definitions in the kds-app.ttl file keyword Args: class_uri: the classUri used for a form with loaded data ***** has to be the class of the subject_uri for the form data lookup subject_uri: the uri of the object that you want to lookup is_subform: True or False. States whether the form is a subform of another form ''' # find the form name and instance from the url _form_location = rdfw().form_exists(form_url) # exit factory if form does not exist if _form_location is False: return None _form_uri = _form_location['form_uri'] _instance = _form_location['instance_uri'] rdf_form = type(_form_uri, (Form, ), {}) setattr(rdf_form, "form_uri", _form_uri) _app_form = rdfw().rdf_form_dict.get(_form_uri, {}) fields = _app_form.get('kds_properties') instructions = get_form_instructions_json(\ _app_form.get('kds_formInstructions'), _instance) _lookup_class_uri = kwargs.get("classUri",\ instructions.get("kds_lookupClassUri")) _lookup_prop_uri = kwargs.get("propUri", \ instructions.get("kds_lookupPropUri")) _lookup_subject_uri = kwargs.get("subject_uri") kwargs['subject_uri'] = _lookup_subject_uri kwargs["propUri"] = _lookup_prop_uri kwargs["classUri"] = _lookup_class_uri # ************************** Testing Variable ************************* user_info = { "kds_userGroups": ["kdr_SysAdmin-SG"], 'kds_applicationSecurity': ["acl_Read", "acl_Write"] } # ********************************************************************* _has_subobj = False rdf_field_list = [] for fld in fields: #print(fld) field = get_field_json(fld, instructions, _instance, user_info) if field: field_item = get_wtform_field(field, _instance, **kwargs) form_field = field_item.get('fld') field = field_item.get('fld_json') if isinstance(form_field, list): i = 0 for nfld in form_field: #print(fld) if nfld.get('kds_field'): _new_field = dict.copy(field) _new_field['kds_formFieldName'] = nfld['kds_fieldName'] _new_field['kds_formFieldOrder'] = \ float(_new_field['kds_formFieldOrder']) + i _new_field['kds_formLayoutRow'] = \ nfld.get("kds_formLayoutRow", _new_field['kds_formLayoutRow']) if nfld.get("doNotSave") == True: _new_field['doNotSave'] = True else: _new_field['doNotSave'] = False augmented_field = add_field_attributes(\ nfld['kds_field'],_new_field) rdf_field_list.append(_new_field) setattr(rdf_form, nfld['kds_fieldName'], augmented_field) i += .01 else: #print(field['formFieldName'], " - ", form_field) if form_field: #print("set --- ", field) augmented_field = add_field_attributes(form_field, field) field['doNotSave'] = False rdf_field_list.append(field) setattr(rdf_form, field['kds_formFieldName'], augmented_field) if hasattr(augmented_field, "frameworkField"): if "subform" in form_field.frameworkField.lower(): _has_subobj = True if kwargs.get("is_subobj"): field = { 'kds_formFieldName': 'subjectUri', 'kds_fieldType': { 'rdf_type': 'ReferenceField' }, 'kds_formLabelName': 'Hidden dataSubjectUri', 'kds_classUri': _lookup_class_uri, 'kds_propUri': 'subjectUri', 'kds_processors': [], 'kds_css': 'form-control', 'editable': False, 'doNotSave': False } rdf_field_list.append(field) augmented_field = add_field_attributes(HiddenField('dataSubjectUri'), field) setattr(rdf_form, 'subjectUri', augmented_field) setattr(rdf_form, 'is_subobj', True) else: setattr(rdf_form, 'is_subobj', False) setattr(rdf_form, 'has_subobj', _has_subobj) setattr(rdf_form, 'rdf_field_list', rdf_field_list) setattr(rdf_form, "rdf_instructions", instructions) setattr(rdf_form, "instance_uri", _instance) setattr(rdf_form, "data_class_uri", _lookup_class_uri) setattr(rdf_form, "data_subject_uri", _lookup_subject_uri) setattr(rdf_form, "data_prop_uri", _lookup_prop_uri) setattr(rdf_form, "base_url", kwargs.get("base_url")) setattr(rdf_form, "current_url", kwargs.get("current_url")) #pp.pprint(rdf_form.__dict__) return rdf_form
def get_field_json(field, instructions, instance, user_info, item_permissions=None): '''This function will read through the RDF defined info and proccess the json to return the correct values for the instance, security and details''' debug = False if item_permissions is None: item_permissions = [] _rdf_app = rdfw().app instance = instance.replace(".html", "") # Determine Security Access _new_field = {} _access_level = get_field_security_access(field, user_info, item_permissions) if "acl_Read" not in _access_level: return None _new_field['accessLevel'] = _access_level # get form instance info _form_instance_info = {} _form_field_instance_type_list = make_list(field.get('kds_formInstance', field.get(\ 'kds_formDefault', {}).get('kds_formInstance', []))) #print("instance type list: ",_form_field_instance_type_list) #print("instance: ", instance) for _field_instance in _form_field_instance_type_list: if _field_instance.get('kds_formInstanceType') == instance: _form_instance_info = _field_instance #print("instance info\n",_form_instance_info) # Determine the field paramaters _new_field['kds_formFieldName'] = _form_instance_info.get('kds_formFieldName', field.get(\ "kds_formFieldName", field.get('kds_formDefault', {}).get(\ 'kds_formFieldName', ""))) _new_field['kds_fieldType'] = _form_instance_info.get('kds_fieldType', field.get(\ 'kds_fieldType', field.get('kds_formDefault', {}).get('kds_fieldType', ""))) if not isinstance(_new_field['kds_fieldType'], dict): _new_field['kds_fieldType'] = {"rdf_type":_new_field['kds_fieldType']} _new_field['kds_formLabelName'] = _form_instance_info.get('kds_formLabelName', \ field.get("kds_formLabelName", field.get('kds_formDefault', {}).get(\ 'kds_formLabelName', ""))) _new_field['kds_formFieldHelp'] = _form_instance_info.get('kds_formFieldHelp', \ field.get("formFieldHelp", field.get('formDefault', {}).get(\ 'kds_formFieldHelp', ""))) _new_field['kds_formFieldOrder'] = _form_instance_info.get('kds_formFieldOrder', \ field.get("kds_formFieldOrder", field.get('kds_formDefault', {}).get(\ 'kds_formFieldOrder', ""))) _new_field['kds_formLayoutRow'] = _form_instance_info.get('kds_formLayoutRow', \ field.get("kds_formLayoutRow", field.get('kds_formDefault', {}).get(\ 'kds_formLayoutRow', ""))) _new_field['kds_propUri'] = field.get('kds_propUri') _new_field['kds_classUri'] = field.get('kds_classUri') _new_field['rdfs_range'] = field.get('rdfs_range') _new_field['kds_defaultVal'] = _form_instance_info.get('kds_defaultVal',\ field.get('kds_defaultVal')) # get applicationActionList _new_field['kds_actionList'] = make_set(_form_instance_info.get(\ 'kds_applicationAction', set())) _new_field['kds_actionList'].union(make_set(field.get('kds_applicationAction', set()))) _new_field['kds_actionList'] = list(_new_field['kds_actionList']) #print("action List:_______________", _new_field['kds_actionList']) if "kdr_RemoveFromForm" in\ _new_field['kds_actionList']: return None # get valiator list if field.get('kds_overrideValidation'): _new_field['kds_validators'] = field.get('kds_overrideValidation') else: _new_field['kds_validators'] = make_list(\ _form_instance_info.get('kds_formValidation', [])) _new_field['kds_validators'] += make_list(\ field.get('kds_formValidation', [])) _new_field['kds_validators'] += make_list(\ field.get('kds_propertyValidation', [])) # get processing list _new_field['kds_processors'] = make_list(_form_instance_info.get('kds_formProcessing', [])) _new_field['kds_processors'] += make_list(field.get('kds_formProcessing', [])) _new_field['kds_processors'] += make_list(field.get('kds_propertyProcessing', [])) if debug: if field['kds_propUri'] == "schema_image": x=1 # get required state _required = False _field_req_var = cbool(field.get('kds_requiredField')) if (field.get('kds_propUri') in make_list(field.get('kds_classInfo', {}).get(\ 'kds_primaryKey', []))) or _field_req_var: _required = True if field.get('kds_classUri') in make_list(field.get('kds_requiredByDomain', {})): _required = True if _field_req_var == False: _required = False _new_field['kds_required'] = _required # Determine EditState if ("acl_Write" in _access_level) and ("kdr_NotEditable" \ not in _new_field['kds_actionList']): _new_field['editable'] = True else: _new_field['editable'] = False # Determine css classes css = _form_instance_info.get('kds_overrideCss', field.get('kds_overrideCss', \ instructions.get('kds_overrideCss', None))) if css is None: css = _rdf_app.get('kds_formDefault', {}).get('kds_fieldCss', '') css = css.strip() + " " + instructions.get('kds_propertyAddOnCss', '') css = css.strip() + " " + _form_instance_info.get('kds_addOnCss', field.get(\ 'kds_addOnCss', field.get('kds_formDefault', {}).get('kds_addOnCss', ''))) css = css.strip() _new_field['kds_css'] = css #print("field_json:\n", json.dumps(_new_field, indent=4)) return _new_field
def get_form_instructions_json(instructions, instance): ''' This function will read through the RDF defined info and proccess the json to retrun the correct instructions for the specified form instance.''' _rdf_app = rdfw().app #print("inst------", instructions) # get form instance info _form_instance_info = {} _form_instance_type_list = make_list( instructions.get('kds_formInstance', [])) for _form_instance in _form_instance_type_list: if _form_instance.get('kds_formInstanceType') == instance: _form_instance_info = _form_instance _new_instr = {} #print("------", _form_instance_info) #Determine the form paramaters _new_instr['kds_formTitle'] = _form_instance_info.get('kds_formTitle', \ instructions.get("kds_formTitle", "")) _new_instr['kds_formDescription'] = _form_instance_info.get('kds_formDescription', \ instructions.get("kds_formDescription", "")) _new_instr['kds_form_Method'] = _form_instance_info.get('kds_form_Method', \ instructions.get("kds_form_Method", "")) _new_instr['kds_form_enctype'] = _form_instance_info.get('kds_form_enctype', \ instructions.get("kds_form_enctype", "")) _new_instr['kds_propertyAddOnCss'] = _form_instance_info.get('kds_propertyAddOnCss', \ instructions.get("kds_propertyAddOnCss", "")) _new_instr['kds_lookupClassUri'] = _form_instance_info.get('kds_lookupClassUri', \ instructions.get("kds_lookupClassUri", "")) _new_instr['kds_lookupPropertyUri'] =\ _form_instance_info.get('kds_lookupPropertyUri',\ instructions.get("kds_lookupPropertyUri")) _new_instr['kds_submitSuccessRedirect'] = \ _form_instance_info.get('kds_submitSuccessRedirect', instructions.get(\ "kds_submitSuccessRedirect", "")) _new_instr['kds_submitFailRedirect'] = \ _form_instance_info.get('kds_submitFailRedirect', instructions.get("kds_submitFailRedirect", "")) _new_instr['kds_saveAction'] = \ _form_instance_info.get('kds_saveAction', instructions.get("kds_saveAction", "")) _new_instr["kds_lookupPropertyClass"] = \ _form_instance_info.get('"kds_lookupPropertyClass"', instructions.get("kds_lookupPropertyClass")) _new_instr["kds_loginRequired"] = \ _form_instance_info.get('"kds_loginRequired"', instructions.get("kds_loginRequired")) # Determine css classes #form row css css = _form_instance_info.get('kds_rowOverideCss', instructions.get(\ 'kds_rowOverideCss', None)) if css is None: css = _rdf_app.get('kds_formDefault', {}).get('kds_rowCss', '') css = css.strip() + " " + _form_instance_info.get('kds_rowAddOnCss', \ instructions.get('kds_rowAddOnCss', '')) css = css.strip() css.strip() _new_instr['kds_rowCss'] = css #form general css css = _form_instance_info.get('kds_formOverideCss', instructions.get(\ 'kds_formOverideCss', None)) if css is None: css = _rdf_app.get('kds_formDefault', {}).get('kds_formCss', '') css = css.strip() + " " + _form_instance_info.get('kds_formAddOnCss', \ instructions.get('kds_formAddOnCss', '')) css = css.strip() css.strip() _new_instr['kds_formCss'] = css return _new_instr
SERVER_CHECK = True __version_info__ = ('0', '0', '1') __version__ = '.'.join(__version_info__) __author__ = "Jeremy Nelson, Mike Stabile" __license__ = 'MIT' __copyright__ = '(c) 2016 by Jeremy Nelson and Mike Stabile' app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile('config.py') app.jinja_env.filters['quote_plus'] = lambda u: quote_plus(u) app.jinja_env.filters['slugify'] = lambda u: slugify(u) app.jinja_env.filters['pjson'] = lambda u: json.dumps(u, indent=4) app.jinja_env.filters['is_list'] = lambda u: isinstance(u, list) app.jinja_env.filters['separate_props'] = lambda u: separate_props(u) app.jinja_env.filters['app_item'] = lambda u: rdfw().app.get(u,str(u)) # register the main site views app.register_blueprint(base_site, url_prefix='') # register the rdfw core application views app.register_blueprint(rdfw_core, url_prefix='') # register any additional rdfw modules mail=Mail(app) #Intialize Flask Login Manager login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = "/login" @app.route("/emailtest") def index(): msg = Message(
def xsd_to_python(value, data_type, rdf_type="literal", output="python"): ''' This will take a value and xsd data_type and convert it to a python variable''' from rdfframework import get_framework as rdfw if data_type: data_type = data_type.replace(str(XSD), "") if not value: return value elif rdf_type == "uri": return iri(value) elif not is_not_null(value): return value elif data_type == "xsd_anyURI": # URI (Uniform Resource Identifier) return value elif data_type == "xsd_base64Binary": # Binary content coded as "base64" return value.decode() elif data_type == "xsd_boolean": # Boolean (true or false) return cbool(value) elif data_type == "xsd_byte": # Signed value of 8 bits return value.decode() elif data_type == "xsd_date": ## Gregorian calendar date _temp_value = parse(value) if output == "string": _date_format = rdfw().app['kds_dataFormats'].get(\ 'kds_pythonDateFormat', '') return _temp_value.strftime(_date_format) elif output == "python": return _temp_value elif data_type == "xsd_dateTime": ## Instant of time (Gregorian calendar) _temp_value = parse(value) if output == "string": _date_format = rdfw().app['kds_dataFormats'].get(\ 'kds_pythonDateTimeFormat', '') return _temp_value.strftime(_date_format) elif output == "python": return _temp_value elif data_type == "xsd_decimal": # Decimal numbers return float(value) elif data_type == "xsd_double": # IEEE 64 return float(value) elif data_type == "xsd_duration": # Time durations return timedelta(milleseconds=float(value)) elif data_type == "xsd_ENTITIES": # Whitespace return value elif data_type == "xsd_ENTITY": # Reference to an unparsed entity return value elif data_type == "xsd_float": # IEEE 32 return float(value) elif data_type == "xsd_gDay": # Recurring period of time: monthly day return value elif data_type == "xsd_gMonth": # Recurring period of time: yearly month return value elif data_type == "xsd_gMonthDay": # Recurring period of time: yearly day return value elif data_type == "xsd_gYear": # Period of one year return value elif data_type == "xsd_gYearMonth": # Period of one month return value elif data_type == "xsd_hexBinary": # Binary contents coded in hexadecimal return value elif data_type == "xsd_ID": # Definition of unique identifiers return value elif data_type == "xsd_IDREF": # Definition of references to unique identifiers return value elif data_type == "xsd_IDREFS": # Definition of lists of references to unique identifiers return value elif data_type == "xsd_int": # 32 return value elif data_type == "xsd_integer": # Signed integers of arbitrary length return int(value) elif data_type == "xsd_language": # RFC 1766 language codes return value elif data_type == "xsd_long": # 64 return int(value) elif data_type == "xsd_Name": # XML 1.O name return value elif data_type == "xsd_NCName": # Unqualified names return value elif data_type == "xsd_negativeInteger": # Strictly negative integers of arbitrary length return abs(int(value))*-1 elif data_type == "xsd_NMTOKEN": # XML 1.0 name token (NMTOKEN) return value elif data_type == "xsd_NMTOKENS": # List of XML 1.0 name tokens (NMTOKEN) return value elif data_type == "xsd_nonNegativeInteger": # Integers of arbitrary length positive or equal to zero return abs(int(value)) elif data_type == "xsd_nonPositiveInteger": # Integers of arbitrary length negative or equal to zero return abs(int(value))*-1 elif data_type == "xsd_normalizedString": # Whitespace return value elif data_type == "xsd_NOTATION": # Emulation of the XML 1.0 feature return value elif data_type == "xsd_positiveInteger": # Strictly positive integers of arbitrary length return abs(int(value)) elif data_type == "xsd_QName": # Namespaces in XML return value elif data_type == "xsd_short": # 32 return value elif data_type == "xsd_string": # Any string return value elif data_type == "xsd_time": # Point in time recurring each day return parse(value) elif data_type == "xsd_token": # Whitespace return value elif data_type == "xsd_unsignedByte": # Unsigned value of 8 bits return value.decode() elif data_type == "xsd_unsignedInt": # Unsigned integer of 32 bits return int(value) elif data_type == "xsd_unsignedLong": # Unsigned integer of 64 bits return int(value) elif data_type == "xsd_unsignedShort": # Unsigned integer of 16 bits return int(value) else: return value
def create_data_sparql_query(obj, **kwargs): ''' generates the sparql query for getting an object's data ''' if not DEBUG: debug = False else: debug = False if debug: print("START create_data_sparql_query -----------------------\n") if debug: print("*** kwargs ***: \n%s \n*** obj ***:\n%s" % (pp.pformat(kwargs), pp.pformat(obj.__dict__))) from rdfframework import RdfDataType subject_uri = kwargs.get("subject_uri", obj.data_subject_uri) _class_uri = kwargs.get("class_uri", obj.data_class_uri) _formated_val = None _lookup_triple = "" if obj.rdf_instructions.get("kds_subjectUriTransform"): if obj.rdf_instructions.get("kds_subjectUriTransform") == \ "kdr_UidToRepositoryUri": id_value = kwargs.get("id_value") if kwargs.get("id_value"): _subject_uri = uid_to_repo_uri(id_value) subject_uri = _subject_uri obj.data_subject_uri = _subject_uri elif obj.rdf_instructions.get("kds_subjectUriTransform") == \ "kdr_UidToTriplestoreUri": id_value = kwargs.get("id_value") if kwargs.get("id_value"): rdf_class = getattr(rdfw(), obj.data_class_uri) subject_uri = rdf_class.uri_patterner(id_value) obj.data_subject_uri = subject_uri elif kwargs.get("id_value") or obj.rdf_instructions.get( "kds_lookupPropertyUri"): # find the details for formating the sparql query for the supplied # id_value or lookup via a property Value id_value = kwargs.get("id_value") if not id_value: id_value = subject_uri _kds_propUri = obj.rdf_instructions.get("kds_lookupPropertyUri") _rdf_class_uri = obj.rdf_instructions.get("kds_lookupPropertyClass") if not _rdf_class_uri: _rdf_class_uri = obj.rdf_instructions.get("kds_lookupClassUri") _rdf_class = getattr(rdfw(), _rdf_class_uri) _rdf_prop = _rdf_class.kds_properties[_kds_propUri] _range = make_list(_rdf_prop.get("rdfs_range"))[0] _formated_val = RdfDataType(_range.get("rangeClass")).sparql(id_value) _lookup_triple = "\t{}\n\t{}\n\t".format( make_triple("?subject", "a", iri(uri(_rdf_class.kds_classUri))), make_triple("?subject", iri(uri(_kds_propUri)), _formated_val)) subject_uri = "?subject" subject_lookup = kwargs.get("subject_lookup") if subject_lookup: # subject lookup will pull a subject and all of its related data _kds_propUri = iri(uri(subject_lookup.kds_propUri)) _data_type = uri(make_list(subject_lookup.rdfs_range)[0]) _prop_value = RdfDataType(_data_type).sparql(\ str(subject_lookup.data)) _sparql = render_without_request("sparqlRelatedItemDataTemplate.rq", prefix=rdfw().get_prefix(), kds_propUri=_kds_propUri, prop_value=_prop_value) return _sparql _lookup_class_uri = _class_uri _sparql_args = None _sparql_constructor = copy.deepcopy(obj.dependancies) if debug: print("+++++++++++++++++++++++ Dependancies:") pp.pprint(_sparql_constructor) _base_subject_finder = None _linked_class = None _linked_prop = False _sparql_elements = [] _subform_data = {} _data_list = obj.is_subobj _parent_field = None if is_not_null(subject_uri): # find the primary linkage between the supplied subjectId and # other form classes for _rdf_class in _sparql_constructor: for _prop in _sparql_constructor[_rdf_class]: try: if _class_uri == _prop.get("kds_classUri"): _sparql_args = _prop _linked_class = _rdf_class _sparql_constructor[_rdf_class].remove(_prop) if _rdf_class != _lookup_class_uri: _linked_prop = True except: pass # generate the triple pattern for linked class if debug: print("+++++++++++++++++++++++ SPARQL Constructor") pp.pprint(_sparql_constructor) if _sparql_args: # create a binding for multi-item results if _data_list: _list_binding = "BIND(?classID AS ?itemID) ." else: _list_binding = '' # provide connection triples for the id subject and associated # rdf class format_string = "{}BIND({} AS ?baseSub) .\n\t{}\n\t{}\n\t{}" _base_subject_finder = format_string.format( _lookup_triple, iri(subject_uri), make_triple("?baseSub", "a", iri(uri(_lookup_class_uri))), make_triple("?classID", iri(uri(_sparql_args.get("kds_propUri"))), "?baseSub"), _list_binding) # if there is a linkage between subject_uri and another associated # property in object if _linked_prop: # create a binding for multi-item results if _data_list: _list_binding = "BIND(?s AS ?itemID) ." else: _list_binding = '' format_string = \ "{}BIND({} AS ?baseSub) .\n\t{}\n\t{}\n\t{}\n\t?s ?p ?o ." _sparql_elements.append(format_string.format(\ _lookup_triple, iri(subject_uri), make_triple("?baseSub", "a", iri(uri(_lookup_class_uri))), make_triple("?s", iri(uri(_sparql_args.get("kds_propUri"))), "?baseSub"), _list_binding)) # iterrate though the classes used in the object and generate the # spaqrl triples to pull the data for that class for _rdf_class in _sparql_constructor: if _rdf_class == _class_uri: if _data_list: _list_binding = "BIND(?s AS ?itemID) ." else: _list_binding = '' if is_not_null(_lookup_triple) and is_not_null(_list_binding): format_string = \ "{}BIND({} AS ?basesub).\n\t{}\n\t{}\n\t{}\n\t?s ?p ?o ." _sparql_elements.append( format_string.format( _lookup_triple, iri(subject_uri), make_triple('?baseSub', 'a', iri(uri(_lookup_class_uri))), make_triple( '?classID', iri(uri(_sparql_args.get("kds_propUri"))), '?s'), "BIND(?classID AS ?itemID) .")) else: format_string = \ "\t{}BIND({} AS ?s) .\n\t{}\n\t{}\n\t?s ?p ?o ." _sparql_elements.append( format_string.format( _lookup_triple, iri(subject_uri), make_triple("?s", "a", iri(uri(_lookup_class_uri))), _list_binding)) for _prop in _sparql_constructor[_rdf_class]: if _rdf_class == _class_uri: if _data_list: _list_binding = "BIND(?s AS ?itemID) ." else: _list_binding = '' format_string = \ "\t{}BIND({} AS ?baseSub) .\n\t{}\n\t{}\n\t{}\n\t?s ?p ?o ." _sparql_arg = format_string.format(\ _lookup_triple, iri(subject_uri), make_triple("?baseSub", "a", iri(uri(_lookup_class_uri))), make_triple("?baseSub", iri(uri(_prop.get("kds_propUri"))), "?s"), _list_binding) _sparql_elements.append(_sparql_arg) elif _rdf_class == _linked_class: _sparql_elements.append("\t{}\n\t{}\n\t?s ?p ?o .".format( _base_subject_finder, make_triple("?classID", iri(uri(_prop.get("kds_propUri"))), "?s"))) '''**** The case where an ID looking up a the triples for a non-linked related is not functioning i.e. password ClassID not looking up person org triples if the org class is not used in the form. This may not be a problem ... the below comment out is a start to solving if it is a problem elif _linked_class != self.get_class_name(prop.get(\ "classUri")): _sparql_elements.append( "\t" +_base_subject_finder + "\n " + "\t"+ make_triple("?classID", iri(prop.get(\ "propUri")), "?s") + "\n\t?s ?p ?o .")''' # merge the sparql elements for each class used into one combined # sparql union statement _sparql_unions = "{{\n{}\n}}".format("\n} UNION {\n".join(\ _sparql_elements)) if _data_list: _list_binding = "?itemID" else: _list_binding = '' # render the statment in the jinja2 template _sparql = render_without_request("sparqlItemTemplate.rq", prefix=rdfw().get_prefix(), query=_sparql_unions, list_binding=_list_binding) if debug: print("SPARQL query") print(_sparql) if debug: print("END create_data_sparql_query ---------------------\n") return _sparql
def _make_unique_value_qry(self, form, field): debug = False _sparql_args = [] # determine the property and class details of the field _prop_uri = field.kds_propUri _class_uri = field.kds_classUri _range = field.rdfs_range # make the base triples for the query if _prop_uri: _data_value = RdfDataType(None, class_uri=_class_uri, prop_uri=_prop_uri).sparql(field.data) _sparql_args.append(make_triple("?uri", "a", iri(uri(_class_uri)))) _sparql_args.append(make_triple("?uri", iri(uri(_prop_uri)), _data_value)) # see if the form is based on a set of triplestore data. if it is # remove that triple from consideration in the query if hasattr(form, "data_subject_uri"): _subject_uri = form.data_subject_uri _lookup_class_uri = form.data_class_uri # if the subject class is the same as the field class if _lookup_class_uri == _class_uri and _subject_uri: _sparql_args.append("FILTER(?uri!={}) .".format(\ iri(_subject_uri))) if debug: x=y # If not need to determine how the subject is related to the field # property elif _subject_uri: # class links shows the relationship between the classes in a form _class_links = form.dependancies _linked_lookup_class_uri = None # cycle through the class links to find the subject linkage for _rdf_class in _class_links: for _prop in _class_links[_rdf_class]: if _lookup_class_uri == _prop.get("kds_classUri"): _linked_lookup_class_uri = _rdf_class _linked_lookup_prop = _prop.get("kds_propUri") break # if there is a direct link between the subject class and # field class add the sparql arguments if _linked_lookup_class_uri == _class_uri: _sparql_args.append(\ "OPTIONAL{{?uri {} ?linkedUri}} .".format(\ iri(uri(_linked_lookup_prop)))) else: # find the indirect linkage i.e. # field in class A that links to class B with a lookup # subject in class C for _rdf_class in _class_links: for _prop in _class_links[_rdf_class]: if _class_uri == _prop.get("kds_classUri"): _linked_field_class_uri = _rdf_class _linked_field_prop = _prop.get("kds_propUri") break if _linked_lookup_class_uri == _linked_field_class_uri: _sparql_args.append("OPTIONAL {") _sparql_args.append("?pass {} ?uri .".format(\ iri(uri(_linked_field_prop)))) _sparql_args.append("?pass {} ?linkedUri .".format(\ iri(uri(_linked_lookup_prop)))) _sparql_args.append("} .") _sparql_args.append(\ "BIND(IF(bound(?linkedUri),?linkedUri,'') AS ?link)") _sparql_args.append("FILTER(?link!={}).".format(\ iri(_subject_uri))) return '''{}\nSELECT (COUNT(?uri)>0 AS ?uniqueValueViolation) {{\n{}\n}}\nGROUP BY ?uri'''.format(rdfw().get_prefix(), "\n\t".join(_sparql_args))