Пример #1
0
    def main_no_jinja():
        """Simple HTML page if jinja2 is not installed."""
        lib_util.WrtHeader('text/html')
        lib_export_html.display_html_text_header(page_title)

        WrtAsUtf("""
        <body><h2>%s</h2>
        """ % page_title)

        WrtAsUtf("""
        <table border="1" width='100%%'>
        <tr><td><b>Host name</b></td><td>%s</td></tr>
        <tr><td><b>Host address</b></td><td>%s</td></tr>
        <tr><td><b>Remote address</b></td><td>%s</td></tr>
        """ % (curr_host_nam, curr_host_addr, addr_remote))

        WrtAsUtf("""<table border="1" width='100%%'>""")
        if cred_map:
            _form_update_credentials_no_jinja(form_action, cred_map)

        _form_insert_credentials_no_jinja(form_action, cred_type_list)
        WrtAsUtf("""</table>""")

        html_footer = "".join(lib_export_html.display_html_text_footer())
        WrtAsUtf(html_footer)

        WrtAsUtf("</body></html>")
Пример #2
0
    def main_jinja():
        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        template_file_name = "www/edit_credentials.template.htm"

        # Create the jinja2 environment.
        # Notice the use of trim_blocks, which greatly helps control whitespace.
        jinja2 = lib_util.GetJinja2()
        jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(THIS_DIR), trim_blocks=True)
        jinja_template = jinja_env.get_template(template_file_name)

        ordered_map = collections.OrderedDict()
        for cred_type in sorted(cred_map):
            sub_ordered_map = collections.OrderedDict()
            for cred_nam in sorted(cred_map[cred_type]):
                sub_ordered_map[cred_nam] = cred_map[cred_type][cred_nam]
            ordered_map[cred_type] = sub_ordered_map

        jinja_render = jinja_template.render(
            page_title=page_title,
            currHostNam=curr_host_nam,
            currHostAddr=curr_host_addr,
            addrRemote=addr_remote,
            credMap=ordered_map,
            credTypeList=cred_type_list )
        lib_util.WrtHeader('text/html')
        WrtAsUtf(jinja_render)
Пример #3
0
    def enter_edition_mode(self):
        """This allow to edit the CGI parameters when in SVG (Graphviz) mode"""
        import lib_export_html
        import lib_edition_parameters

        form_action = os.environ['SCRIPT_NAME']
        DEBUG("enter_edition_mode form_action=%s", form_action)

        lib_util.WrtHeader('text/html')

        # It uses the same CSS as in HTML mode.
        lib_export_html.DisplayHtmlTextHeader(self.m_page_title +
                                              " - parameters")

        print("<body>")

        print("<h3>%s</h3><br>" % self.m_page_title)

        htmlForm = "".join(
            lib_edition_parameters.FormEditionParameters(form_action, self))
        print(htmlForm)

        print("</body>")
        print("</html>")
        sys.exit(0)
Пример #4
0
def MainNoJinja(page_title,currHostNam,currHostAddr,addrRemote,credMap,formAction,credTypeList):
    lib_util.WrtHeader('text/html')
    lib_export_html.DisplayHtmlTextHeader(page_title)

    WrtAsUtf("""
    <body><h2>%s</h2>
    """ % page_title)

    WrtAsUtf("""
    <table border="1" width='100%%'>
    <tr><td><b>Host name</b></td><td>%s</td></tr>
    <tr><td><b>Host address</b></td><td>%s</td></tr>
    <tr><td><b>Remote address</b></td><td>%s</td></tr>
    """ %(currHostNam,currHostAddr,addrRemote))

    WrtAsUtf("""<table border="1" width='100%%'>""")
    if credMap:
        FormUpdateCredentialsNoJinja(formAction,credMap)

    FormInsertCredentialsNoJinja(formAction, credTypeList)
    WrtAsUtf("""</table>""")

    htmlFooter = "".join( lib_export_html.DisplayHtmlTextFooter() )
    WrtAsUtf(htmlFooter)

    WrtAsUtf("</body></html>")
Пример #5
0
def DisplayHtmlTextHeader(page_title):
    """
	This is the common Survol header, ideally for all HTML documents.
	"""

    lib_util.WrtHeader('text/html')
    WrtAsUtf("<head>")

    # TODO: Encode HTML special characters.
    WrtAsUtf("<title>%s</title>" % page_title)

    # The href must be absolute so it will work with any script.
    # We must calculate its prefix.
    # In the mean time, this solution adapts to our three kind of different hosting types:
    # - OVH mutialised hosting, with a specific CGI script survol.cgi
    # - With the Python class HttpServer as Web server.
    # - Hosted with Apache.

    WrtAsUtf("""
		<link rel='stylesheet' type='text/css' href=/ui/css/html_exports.css>
		<link rel='stylesheet' type='text/css' href='/survol/www/css/html_exports.css'>
		<link rel='stylesheet' type='text/css' href='../survol/www/css/html_exports.css'>
		""")

    WrtAsUtf('</head>')
Пример #6
0
def MainNoJinja():
    lib_util.WrtHeader('text/html')
    lib_export_html.DisplayHtmlTextHeader("Configuration")

    WrtAsUtf("""
    <body><h2>Edit Survol configuration</h2>
    """)

    WrtAsUtf("""
    <form method="post" action="edit_configuration.py" name="ServerConfiguration">
    <table border="0">
    <tr>
    <td>CGI server port number:</td>
    <td>&nbsp;<input name="server_port" value="8000"></td>
    </tr>
    <tr>
    <td>Bookmarks file or URL:</td>
    <td>&nbsp;<input name="bookmark_url" value="bookmarks.htm"></td>
    </tr>
    <tr>
    <td>HTML Jinja2 templates:</td>
    <td><input type="checkbox" name="html_jinja2"></td>
    </tr>
    <tr>
    <td colspan="2"><input value="Submit configuration" name="Hello" type="submit"></td>
    </tr>
    </table>
    </form>
    """)

    htmlFooter = "".join(lib_export_html.DisplayHtmlTextFooter())
    WrtAsUtf(htmlFooter)

    WrtAsUtf("</body></html>")
Пример #7
0
def WriteJsonHeader(bufJson, withContentLength=False):
    arrHeaders = [
        ('Access-Control-Allow-Origin', '*'),
        ('Access-Control-Allow-Methods', 'POST,GET,OPTIONS'),
        ('Access-Control-Allow-Headers',
         'Origin, X-Requested-With, Content-Type, Accept'),
    ]

    # It is difficult to calculate the length because the output is encoded
    # in Base64, which takes more room than JSon. And also, at least on Windows,
    # each line gets an extra character ("\n\r" ?).
    # So it is confusing.
    # The reason for adding the length is: When an error is detected, sometimes a second error
    # comes immediately after the one, even if the thread (or process ?) quits.
    #
    # Also, with Chrome and Android, sometimes it is not happy with the length,
    # even if we checked it. It works without the length, except if this is an error message.
    if withContentLength:
        numLines = bufJson.count("\n")
        lenBuf = len(bufJson) + numLines

        arrHeaders.append(('Content-Length', str(lenBuf)))

    lib_util.WrtHeader('application/json', arrHeaders)

    # No text conversion.
    # lib_util.outputHttp.write(bufJson)
    lib_util.WrtAsUtf(bufJson)
Пример #8
0
def Grph2Rdf(grph):
    lib_util.WrtHeader('text/rdf')

    # Format support can be extended with plugins,
    # but 'xml', 'n3', 'nt', 'trix', 'rdfa' are built in.
    out_dest = lib_util.DfltOutDest()
    grph.serialize(destination=out_dest, format="xml")
Пример #9
0
def _dot_to_svg(dot_filnam_after, logfil, viztype, out_dest):
    DEBUG("viztype=%s", viztype)
    tmp_svg_fil = TmpFile("_dot_to_svg", "svg")
    svg_out_filnam = tmp_svg_fil.Name
    # dot -Kneato

    # Dot/Graphviz no longer changes PATH at installation. It must be done BEFORE.
    dot_path = "dot"

    if lib_util.isPlatformLinux:
        # TODO: This is arbitrary because old Graphviz version.
        # TODO: Take the fonts from html_exports.css
        # dot_fonts = ["-Gfontpath=/usr/share/fonts/TTF", "-Gfontnames=svg", "-Nfontname=VeraBd.ttf","-Efontname=VeraBd.ttf"]
        dot_fonts = [
            # "-Gfontpath=/usr/share/fonts/dejavu",
            "-Gfontpath=/usr/share/fonts",
            "-Gfontnames=svg",
            "-Nfontname=DejaVuSans.ttf",
            "-Efontname=DejaVuSans.ttf"
        ]
    else:
        dot_fonts = []

    # Old versions of dot need the layout on the command line.
    # This is maybe a bit faster than os.open because no shell and direct write to the output.
    svg_command = [
        dot_path, "-K", viztype, "-Tsvg", dot_filnam_after, "-o",
        svg_out_filnam, "-v", "-Goverlap=false"
    ] + dot_fonts
    msg = "svg_command=" + " ".join(svg_command)
    DEBUG(msg)
    logfil.write(TimeStamp() + " " + msg + "\n")

    ret = subprocess.call(svg_command,
                          stdout=logfil,
                          stderr=logfil,
                          shell=False)
    logfil.write(TimeStamp() + " Process ret=%d\n" % ret)

    if not os.path.isfile(svg_out_filnam):
        ErrorMessageHtml("SVG file " + svg_out_filnam +
                         " could not be created.")

    # TODO: If there is an error, we should write it as an HTML page.
    # On the other hand it is impossible to pipe the output because it would assume a SVG document.

    # https://stackoverflow.com/questions/5667576/can-i-set-the-html-title-of-a-pdf-file-served-by-my-apache-web-server
    dictHttpProperties = [("Content-Disposition",
                           'inline; filename="Survol_Download"')]

    logfil.write(TimeStamp() + " Writing SVG header\n")
    lib_util.WrtHeader("image/svg+xml", dictHttpProperties)

    # Here, we are sure that the output file is closed.
    copy_to_output_destination(logfil, svg_out_filnam, out_dest)
Пример #10
0
 def WriteTripleStoreAsString(self, grph):
     lib_util.WrtHeader(self.m_mime_format)
     try:
         # pip install rdflib-jsonld
         # No plugin registered for (json-ld, <class 'rdflib.serializer.Serializer'>)
         # rdflib_format = "pretty-xml"
         strRdf = grph.serialize(format=self.m_rdflib_format)
     except Exception as exc:
         logging.error("Caught:%s" % exc)
         return
     lib_util.WrtAsUtf(strRdf)
Пример #11
0
def output_rdf_graph_as_html(theCgi, top_url, error_msg, gbl_cgi_env_list):
    """The list gbl_cgi_env_list contains a list of URL which are merged
    into the current URLs. There are displayed for informational purpose.
    """
    lib_util.WrtHeader('text/html')
    if lib_util.GetJinja2():
        output_rdf_graph_as_html_jinja(theCgi, top_url, error_msg,
                                       gbl_cgi_env_list)
    else:
        _output_rdf_graph_as_html_no_jinja(theCgi, top_url, error_msg,
                                           gbl_cgi_env_list)
Пример #12
0
def Dot2Svg(dot_filnam_after,logfil, viztype, out_dest ):
	sys.stderr.write("viztype=%s\n"%(viztype) )
	tmpSvgFil = TmpFile("Dot2Svg","svg")
	svg_out_filnam = tmpSvgFil.Name
	# dot -Kneato

	# Dot/Graphviz no longer changes PATH at installation. It must be done BEFORE.
	dot_path = "dot"

	if lib_util.isPlatformLinux:
		# TODO: This is arbitrary because old Graphviz version.
		# TODO: Take the fonts from html_exports.css
		# dotFonts = ["-Gfontpath=/usr/share/fonts/TTF", "-Gfontnames=svg", "-Nfontname=VeraBd.ttf","-Efontname=VeraBd.ttf"]
		dotFonts = [
                    # "-Gfontpath=/usr/share/fonts/dejavu", 
                    "-Gfontpath=/usr/share/fonts", 
                    "-Gfontnames=svg",
                    "-Nfontname=DejaVuSans.ttf",
                    "-Efontname=DejaVuSans.ttf"]
	else:
		dotFonts = []

	# Old versions of dot need the layout on the command line.
	# This is maybe a bit faster than os.open because no shell and direct write to the output.
	svg_command = [ dot_path,"-K",viztype,"-Tsvg",dot_filnam_after,"-o",svg_out_filnam, \
		"-v","-Goverlap=false" ] + dotFonts
	msg = "svg_command=" + " ".join(svg_command) + "\n"
	sys.stderr.write(msg)
	logfil.write(TimeStamp()+" "+msg)

	ret = subprocess.call( svg_command, stdout=logfil, stderr=logfil, shell=False )
	logfil.write(TimeStamp()+" Process ret=%d\n" % ret)

	if not os.path.isfile( svg_out_filnam ):
		ErrorMessageHtml("SVG file " + svg_out_filnam + " could not be created." )
	
	# If there is an error, we should write it as an HTML page.
	# On the other hand it will be impossible to pipe the output
	# because it would assume a SVG document.
	# TODO: See that later.

	# For the specific case when it writes into a socket. Strange behaviour:
	# Without this, it wraps our SVG code in HTML tags, adds its own HTTP header, etc...
	# The test on stdout comes at the end because it does not work on old Python versions.
	if lib_util.isPlatformWindows and sys.version_info >= (3,4,) and out_dest != sys.stdout.buffer :
		logfil.write( TimeStamp() + " SVG Header removed\n" )
	else:
		logfil.write( TimeStamp() + " Writing SVG header\n" )
		lib_util.WrtHeader( "image/svg+xml" )

	# Here, we are sure that the output file is closed.
	CopyToOut(logfil,svg_out_filnam,out_dest)
Пример #13
0
 def WriteTripleStoreAsString(self,grph):
     lib_util.WrtHeader(self.m_mime_format)
     try:
         # pip install rdflib-jsonld
         # No plugin registered for (json-ld, <class 'rdflib.serializer.Serializer'>)
         # rdflib_format = "pretty-xml"
         # sys.stderr.write("len grph=%d\n"%len(grph))
         strRdf = grph.serialize(format=self.m_rdflib_format)
     except Exception as exc:
         sys.stderr.write("Caught:%s\n"%exc)
         return
     # sys.stderr.write("strRdf=%s\n"%strRdf)
     lib_util.WrtAsUtf(strRdf)
Пример #14
0
def Grph2Rdf(grph):
    DEBUG("Grph2Rdf entering")

    new_grph = AddOntology(grph)

    # Neither "xml/rdf" nor "text/rdf" are correct MIME-types.
    # It should be "application/xml+rdf" or possibly "application/xml" or "text/xml"
    # 'text/rdf' and 'xml/rdf' are OK with Protege
    # 'application/xml+rdf' creates a file.
    lib_util.WrtHeader('application/xml')

    out_dest = lib_util.get_default_output_destination()

    lib_kbase.triplestore_to_stream_xml(new_grph, out_dest, 'xml')
    DEBUG("Grph2Rdf leaving")
Пример #15
0
def MainJinja():
    THIS_DIR = os.path.dirname(os.path.abspath(__file__))
    template_file_name = "www/edit_configuration.template.htm"

    jinja2 = lib_util.GetJinja2()

    # Create the jinja2 environment.
    # Notice the use of trim_blocks, which greatly helps control whitespace.
    jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(THIS_DIR),
                                   trim_blocks=True)
    jinja_template = jinja_env.get_template(template_file_name)

    jinja_render = jinja_template.render()
    lib_util.WrtHeader('text/html')
    WrtAsUtf(jinja_render)
Пример #16
0
def FlushOrSaveRdfGraph(grph, output_rdf_filename):
    INFO("FlushOrSaveRdfGraph l=%s sys.argv=%s", len(sys.argv), str(sys.argv))

    try:
        os.environ["QUERY_STRING"]
        INFO("FlushOrSaveRdfGraph to stream")
        lib_util.WrtHeader('text/html')

        out_dest = lib_util.get_default_output_destination()
        lib_kbase.triplestore_to_stream_xml(grph, out_dest, 'pretty-xml')

    except KeyError:
        INFO("FlushOrSaveRdfGraph onto_filnam=%s", output_rdf_filename)
        outfil = open(output_rdf_filename, "w")
        lib_kbase.triplestore_to_stream_xml(grph, outfil, 'pretty-xml')
        outfil.close()
Пример #17
0
    def enter_edition_mode(self):
        """This allow to edit the CGI parameters when in SVG (Graphviz) mode"""

        form_action = os.environ['SCRIPT_NAME']
        logging.debug("enter_edition_mode form_action=%s", form_action)

        # HTTP header.
        lib_util.WrtHeader('text/html')

        # HTML <HEAD> tag. It uses the same CSS as in HTML mode.
        lib_export_html.display_html_text_header(self.m_page_title + " - parameters")

        # Display the HTML page for editing the parameters of the script.
        lib_edition_parameters.DisplayEditionParametersPage(form_action, self)

        # Now leave: The user will edit the parameters and click "submit".
        sys.exit(0)
Пример #18
0
def output_rdf_graph_as_rdf(grph):
    """Used by all CGI scripts when they have finished adding triples to the current RDF graph.
    The RDF comment is specifically processed to be used by ontology editors such as Protege."""
    logging.debug("Grph2Rdf entering, len_graph=%d", len(grph))

    new_grph = _add_ontology(grph)

    # Neither "xml/rdf" nor "text/rdf" are correct MIME-types.
    # It should be "application/xml+rdf" or possibly "application/xml" or "text/xml"
    # 'text/rdf' and 'xml/rdf' are OK with Protege
    # 'application/xml+rdf' creates a file.
    lib_util.WrtHeader('application/xml')

    out_dest = lib_util.get_default_output_destination()

    lib_kbase.triplestore_to_stream_xml(new_grph, out_dest, 'xml')
    logging.debug("Grph2Rdf leaving, len(new_grph)=%d", len(new_grph))
Пример #19
0
def WriteRdfError(message, broken_url):
    """This is called only by ErrorMessageHtml when an error is detected and the output format is RDF.
    After that, the calling function makes an exit.
    """

    new_grph = rdflib.Graph()
    new_grph.add(
        (rdflib.term.URIRef(broken_url), lib_properties.pc.property_error,
         rdflib.Literal(message)))

    # Neither "xml/rdf" nor "text/rdf" are correct MIME-types.
    # It should be "application/xml+rdf" or possibly "application/xml" or "text/xml"
    # 'text/rdf' and 'xml/rdf' are OK with Protege
    # 'application/xml+rdf' creates a file.
    lib_util.WrtHeader('application/xml')

    out_dest = lib_util.get_default_output_destination()

    lib_kbase.triplestore_to_stream_xml(new_grph, out_dest, 'xml')
Пример #20
0
def MainJinja(url_supervisor_control, urls_daemons_dict):
    MainNoJinja(url_supervisor_control, urls_daemons_dict)
    return
    lib_common.ErrorMessageHtml("Not implemented yet")

    THIS_DIR = os.path.dirname(os.path.abspath(__file__))
    template_file_name = "www/edit_supervisor.template.htm"

    jinja2 = lib_util.GetJinja2()

    # Create the jinja2 environment.
    # Notice the use of trim_blocks, which greatly helps control whitespace.
    jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(THIS_DIR),
                                   trim_blocks=True)
    jinja_template = jinja_env.get_template(template_file_name)

    jinja_render = jinja_template.render()
    lib_util.WrtHeader('text/html')
    WrtAsUtf(jinja_render)
Пример #21
0
def _write_json_header(buf_json, with_content_length=False):
    """
    This writes to the output a JSON content with the appropriate HTTP header.
    It for example used by the Javascript interface, to get a contextual menu.

    What must be avoided: Cross-Origin Request Blocked:
    The Same Origin Policy disallows reading the remote resource at
    http://192.168.0.17/Survol/survol/sources_types/enumerate_CIM_Process.py?xid=.&mode=json.
    (Reason: CORS header 'Access-Control-Allow-Origin' missing)

    https://stackoverflow.com/questions/5027705/error-in-chrome-content-type-is-not-allowed-by-access-control-allow-headers
    The body of the reply is base-64 encoded.
    """
    arr_headers = [
        ('Access-Control-Allow-Origin', '*'),
        ('Access-Control-Allow-Methods', 'POST,GET,OPTIONS'),
        ('Access-Control-Allow-Headers',
         'Origin, X-Requested-With, Content-Type, Accept'),
    ]

    # It is difficult to calculate the length because the output is encoded
    # in Base64, which takes more room than JSon. And also, at least on Windows,
    # each line gets an extra character ("\n\r" ?).
    # So it is confusing.
    # The reason for adding the length is: When an error is detected, sometimes a second error
    # comes immediately after the one, even if the thread (or process ?) quits.
    #
    # Also, with Chrome and Android, sometimes it is not happy with the length,
    # even if we checked it. It works without the length, except if this is an error message.
    if with_content_length:
        num_lines = buf_json.count("\n")
        len_buf = len(buf_json) + num_lines

        arr_headers.append(('Content-Length', str(len_buf)))

    lib_util.WrtHeader('application/json', arr_headers)

    # No text conversion.
    lib_util.WrtAsUtf(buf_json)
Пример #22
0
def flush_or_save_rdf_graph(grph, output_rdf_filename):
    """This dumps the triplestore graph to the current output socket if called in a HTTP server.
    Otherwise it saves the result to a text file, for testing or debugging."""
    logging.info("l=%s sys.argv=%s", len(sys.argv), str(sys.argv))

    try:
        # This is a hack to test if the caller is in command-line mode or runs in a web server.
        os.environ["QUERY_STRING"]
        logging.info("Writing to stream")
        lib_util.WrtHeader('text/html')

        out_dest = lib_util.get_default_output_destination()
        lib_kbase.triplestore_to_stream_xml(grph, out_dest, 'xml')
    except KeyError:
        # Just write the content to a file, no HTTP header is needed.
        logging.info("onto_filnam=%s", output_rdf_filename)
        # With Python3, open in binary mode, otherwise it raises "TypeError: write() argument must be str, not bytes".
        # Maybe this is an issue with a specific rdflib version.
        open_flag = "bw" if lib_util.is_py3 else "w"
        outfil = open(output_rdf_filename, open_flag)
        lib_kbase.triplestore_to_stream_xml(grph, outfil, 'xml')
        outfil.close()
Пример #23
0
def MainNoJinja(url_supervisor_control, urls_daemons_dict):
    lib_util.WrtHeader('text/html')
    lib_export_html.display_html_text_header("Events generators")

    WrtAsUtf("""
    <body><h2>Display events generators</h2>
    """)

    if url_supervisor_control:
        WrtAsUtf("""
        <a href="%s">Supervisor Control</a>
        """ % url_supervisor_control)

    WrtAsUtf("""
    <br><br>
    
    <table border="1" width="100%">
    <tr><td>Daemon url</td><td>Object url</td><td>Triples number</td><td>Start time</td><td>State</td><td>Pid</td></tr>
    """)

    for daemon_url, daemon_object in urls_daemons_dict.items():
        WrtAsUtf("""
        <tr><td><a href="%s">%s</a></td><td><a href="%s">%s</a></td><td>%d</td><td>%s</td><td>%s</td><td>%d</td></tr>
        """ % (daemon_url, daemon_object['url_title'],
               daemon_object['object_url'], daemon_object['object_title'],
               daemon_object['triples_number'], daemon_object['start_time'],
               daemon_object['statename'], daemon_object['pid']))

    WrtAsUtf("""
    </table>
    <br><br>
    """)

    html_footer = "".join(lib_export_html.display_html_text_footer())
    WrtAsUtf(html_footer)

    WrtAsUtf("</body></html>")
Пример #24
0
def Main():
    lib_util.SetLoggingConfig(logging.ERROR)

    # https://hhs.github.io/meshrdf/sparql-and-uri-requests

    # Parameter name, SELECT queries, CONSTRUCT queries, default, help.
    # format
    # Accepts HTML*, XML, CSV, TSV or JSON
    # Accepts HTML*, XML, JSON-LD, RDF/XML, TURTLE or N3
    # Default: HTML*
    # Returns a file with the specified syntax.

    # inference
    # Accepts true or false
    # Accepts true or false
    # Default: false
    # Running a query with inference set to "true" will return results
    # for all subclasses and subproperties of those classes and properties you specify in your query.
    # For example, there are no direct instances of meshv:Descriptor,
    # but if you run a query with inference and look for rdf:type meshv:Descriptor,
    # you will get all instances of meshv:Descriptor's subclasses - meshv:TopicalDescriptor,
    # meshv:GeographicalDescriptor, meshv:PublicationType and meshv:CheckTag.
    # Running a query with inference=true may affect performance.

    # limit
    # Accepts positive integers up to 1000
    # N/A
    # Default: 1000
    # Limits the number of results per request. The maximum number of results per request for SELECT queries is 1,000.
    # This parameter does not affect CONSTRUCT queries.
    # CONSTRUCT queries will return all triples requested up to a limit of 10,000 triples.

    # offset
    # Accepts positive integers
    # N/A
    # Default: 0
    # When offset=n, this parameter will return results starting with the nth result.
    # Use this parameter to loop through multiple requests for large result sets.

    # query
    # Accepts a SELECT SPARQL query
    # Accepts a CONSTRUCT SPARQL query
    # Default: N/A
    # This parameter is required and must contain a SPARQL query. For an example of how these are formatted,
    # run a query from the SPARQL query editor and view the resulting URL.

    # year
    # Accepts "current" or a year.
    # Accepts "current" or a year.
    # Default: current
    # Queries either the current MeSH graph (http://id.nlm.nih.gov/mesh) or a versioned MeSH graph,
    # for example: (http://id.nlm.nih.gov/mesh/2015).
    import cgi
    arguments = cgi.FieldStorage()

    # See lib_uris.SmbShareUri and the HTTP server which collapses duplicated slashes "//" into one,
    # in URL, because they are interpreted as file names.
    # SparqlWrapper does not encode slashes with urllib.quote_plus(param.encode('UTF-8'), safe='/')
    # in Wrapper.py.
    # See modules CGIHTTPServer, BaseHTTPServer, CGIHTTPRequestHandler
    # 'HTTP_USER_AGENT': 'sparqlwrapper 1.8.4 (rdflib.github.io/sparqlwrapper)'
    # sys.stderr.write("Environ=%s\n"%str(os.environ))
    # QUERY_STRING='query=%0A++++++++++++++++PREFIX+wmi%3A++%3Chttp%3A/www.primhillcomputers.com/ontology/wmi%23%3E%0A++++++++++++++++PREFIX+survol%3A++%3Chttp%3A/primhillcomputers.com/survol%23%3E%0A++++++++++++++++PREFIX+rdfs%3A++++%3Chttp%3A/www.w3.org/2000/01/rdf-schema%
    # 23%3E%0A++++++++++++++++SELECT+%3Fcaption%0A++++++++++++++++WHERE%0A++++++++++++++++%7B%0A++++++++++++++++++++%3Furl_user+rdf%3Atype+survol%3AWin32_UserAccount+.%0A++++++++++++++++++++%3Furl_user+survol%3AName+%27rchateau%27+.%0A++++++++++++++++++++%3Furl_user+sur
    # vol%3ACaption+%3Fcaption+.%0A++++++++++++++++++++%3Furl_user+rdfs%3AseeAlso+%22WMI%22+.%0A++++++++++++++++%7D%0A++++++++++++++++&output=json&results=json&format=json'
    sparql_query = arguments["query"].value

    # 'SERVER_SOFTWARE': 'SimpleHTTP/0.6 Python/2.7.10'
    # 'SERVER_SOFTWARE': 'SimpleHTTP/0.6 Python/3.6.3'
    sys.stderr.write("SERVER_SOFTWARE=%s\n" % os.environ['SERVER_SOFTWARE'])
    if os.environ['SERVER_SOFTWARE'].startswith("SimpleHTTP"):
        # Beware, only with Python2. Not needed on Linux and Python 3.
        # Maybe because the Python class processes the CGI arguments like filenames.
        if not lib_util.is_py3 and lib_util.isPlatformWindows:
            sparql_query = re.sub("([^a-z]*)http:/([^a-z]*)", r"\1http://\2", sparql_query)
            sys.stderr.write("Substitution 'http://' and 'http:///'\n")

    sys.stderr.write("sparql_server sparql_query=%s\n" % sparql_query.replace(" ","="))

    try:
        result_format = arguments["format"].value
    except KeyError:
        result_format = "HTML*"

    sys.stderr.write("\n")

    query_result = __run_sparql_query(sparql_query)

    sys.stderr.write("sparql_server After query len(query_result)=%d\n" % len(query_result))
    sys.stderr.write("sparql_server After query query_result=%s\n" % str(query_result))

    # TODO: This does not work "select *", so maybe should read the first row.
    row_header = __query_header(sparql_query)

    # https://docs.aws.amazon.com/neptune/latest/userguide/sparql-api-reference-mime.html

    if result_format.upper() == "JSON":
        mime_format = "application/sparql-results+json"
        # https://www.w3.org/TR/2013/REC-sparql11-results-json-20130321/
        # This document describes how to serialize SPARQL results (SELECT and ASK query forms) in a JSON format.
        # {
        #     "head": {"vars": ["book", "title"]
        #              },
        #     "results": {
        #         "bindings": [
        #             {
        #                 "book": {"type": "uri", "value": "http://example.org/book/book6"},
        #                 "title": {"type": "literal", "value": "Harry Potter and the Half-Blood Prince"}
        #             },
        bindings_list = []
        for one_row in query_result:
            dict_row = {}
            for ix in range(len(row_header)):
                one_element = one_row[ix]

                if lib_kbase.IsLiteral(one_element):
                    json_element = {"type":"literal", "value": str(one_element)}
                elif lib_kbase.IsURIRef(one_element):
                    json_element = {"type":"url", "value": str(one_element)}
                else:
                    raise Exception("SparqlServer: Invalid type:%s"%str(one_element))
                one_variable = row_header[ix]
                dict_row[one_variable] = json_element

            bindings_list.append(dict_row)
        sys.stderr.write("bindings_list=%s\n"%str(bindings_list))

        json_output = {
            "head": {"vars": row_header},
            "results": {"bindings": bindings_list}}
        str_output = json.dumps(json_output)
    elif result_format.upper() == "XML":
        mime_format = "application/sparql-results+xml"
        # https://www.w3.org/TR/rdf-sparql-XMLres/
        # This document describes an XML format for the variable binding and boolean results formats provided by the SPARQL query language for RDF
        # <?xml version="1.0"?>
        # <sparql xmlns="http://www.w3.org/2005/sparql-results#">
        #   <head>
        #     <variable name="x"/>
        #     <variable name="hpage"/>
        #   </head>
        #
        #   <results>
        #     <result>
        #       <binding name="x"> ... </binding>
        #       <binding name="hpage"> ... </binding>
        #     </result>

        root = ET.Element("sparql")
        head = ET.SubElement(root, "head")
        for one_variable in row_header:
            ET.SubElement(head, "variable", name=one_variable)

        results = ET.SubElement(root, "results")
        for one_row in query_result:
            result = ET.SubElement(results, "result")
            for ix in range(len(row_header)):
                one_variable = row_header[ix]
                ET.SubElement(result, "binding", name=one_variable).text = one_row[ix]

        str_output = ET.tostring(root, encoding='utf8', method='xml')
        sys.stderr.write("sparql_server str_output=%s\n"%str_output)

    else:
        raise Exception("Results format %s not implemented yet"%result_format)

    sys.stderr.write("sparql_server result_format=%s str_output=%s\n"%(result_format, str_output))

    lib_util.WrtHeader(mime_format)
    lib_util.WrtAsUtf(str_output)
Пример #25
0
def Grph2Html(theCgi, topUrl, error_msg, isSubServer, gblCgiEnvList):
    lib_util.WrtHeader('text/html')
    if lib_util.GetJinja2():
        Grph2HtmlJinja(theCgi, topUrl, error_msg, isSubServer, gblCgiEnvList)
    else:
        Grph2HtmlNoJinja(theCgi, topUrl, error_msg, isSubServer, gblCgiEnvList)