def karyotype(connection, ENDPOINT, PARAMS, arguments, context):
    try:
        specie = taking_out_space(arguments["species"][0])
    except KeyError:
        if len(arguments.keys()) == 0:
            cont_type = 'text/html'
            context["karyotype"] = "ERROR"
            contents = su.read_template_html_file("./HTML/info/karyotype.html").render(context=context)
            return contents, cont_type
        elif len(arguments.keys()) == 1:
            cont_type = 'application/json'
            context["karyotype"] = "ERROR"
            contents = json.dumps(context, indent=4, sort_keys=True)
            return contents, cont_type
    connection.request("GET", ENDPOINT + specie + PARAMS)
    response = connection.getresponse()
    if response.status == 200:
        response_dict = json.loads(response.read().decode())
        # print(json.dumps(response_dict, indent=4, sort_keys=True))
        karyotype = response_dict["karyotype"]
        # print(karyotype)
        context["species"] = arguments["species"][0]
        context["karyotype"] = karyotype
        if "json" in arguments.keys():
            if arguments["json"][0] == "1":
                cont_type = 'application/json'
                contents = json.dumps(context, indent=4, sort_keys=True)
                return contents, cont_type
        else:
            cont_type = 'text/html'
            contents = su.read_template_html_file("./HTML/info/karyotype.html").render(context=context)
            return contents, cont_type
def geneSeq(connection, ENDPOINT, PARAMS, arguments, context, DICT_GENES):
    try:
        gene = arguments["gene"][0]
    except KeyError:
        if len(arguments.keys()) == 0:
            cont_type = 'text/html'
            context["seq"] = "ERROR"
            contents = su.read_template_html_file("./HTML/info/geneSeq.html").render(context=context)
            return contents, cont_type
        elif len(arguments.keys()) == 1:
            cont_type = 'application/json'
            context["seq"] = "ERROR"
            contents = json.dumps(context, indent=4, sort_keys=True)
            return contents, cont_type
    id = DICT_GENES[gene]
    connection.request("GET", ENDPOINT + id + PARAMS)
    response = connection.getresponse()
    if response.status == 200:
        response_dict = json.loads(response.read().decode())
        # print(json.dumps(response_dict, indent=4, sort_keys=True))
        context["gene"] = arguments["gene"][0]
        context["seq"] = response_dict["seq"]
        if "json" in arguments.keys():
            if arguments["json"][0] == "1":
                cont_type = 'application/json'
                contents = json.dumps(context, indent=4, sort_keys=True)
                return contents, cont_type
        else:
            cont_type = 'text/html'
            contents = su.read_template_html_file("./HTML/info/geneSeq.html").render(context=context)
            return contents, cont_type
    def do_GET(self):
        """This method is called whenever the client invokes the GET method
        in the HTTP protocol request"""
        termcolor.cprint(self.requestline, 'green')
        termcolor.cprint(self.path, 'blue')

        o = urlparse(self.path)
        path_name = o.path
        arguments = parse_qs(o.query)
        print("Resource requested: ", path_name)
        print("Parameters: ", arguments)
        context = {}
        if path_name == '/':
            context["n_sequences"] = len(list_sequences)
            context["list_genes"] = list_genes
            contents = su.read_template_html_file('./index.html').render(
                context=context)
        elif path_name == "/test":
            contents = su.read_template_html_file("./test.html").render()
        elif path_name == "/ping":
            contents = su.read_template_html_file("./ping.html").render()
        elif path_name == "/get":
            number_sequence = arguments["sequence"][0]
            contents = su.get(list_sequences, number_sequence)
        elif path_name == "/gene":
            gene = arguments["gene"][0]
            contents = su.gene(gene)
        elif path_name == "/operation":
            sequence = arguments["sequence"][0]
            calculation = arguments["calculation"][0]
            if calculation == "Info":
                contents = su.info(sequence)
            elif calculation == "Comp":
                contents = su.comp(sequence)
            elif calculation == "Rev":
                contents = su.rev(sequence)
            else:
                contents = su.read_template_html_file('./Error.html').render()
        else:
            contents = su.read_template_html_file("./Error.html").render()
        self.send_response(200)  # -- Status line: OK!

        # Define the content-type header:
        self.send_header('Content-Type', 'text/html')
        self.send_header('Content-Length', len(contents.encode()))
        # The header is finished
        self.end_headers()
        # Send the response message
        self.wfile.write(contents.encode())
        return
Exemplo n.º 4
0
    def do_GET(self):
        termcolor.cprint(self.requestline, 'green')
        termcolor.cprint(self.path, 'blue')

        o = urlparse(self.path)
        path_name = o.path
        arguments = parse_qs(o.query)
        print("Resource requested: ", path_name)
        print("Parameters: ", arguments)
        # IN this simple server version:
        # We are NOT processing the client's request
        # It is a happy server: It always returns a message saying
        # that everything is ok
        context = {}
        # Message to send back to the client
        if path_name == '/':
            context["n_sequences"] = len(list_sequences)
            context["list_genes"] = list_genes
            contents = su.read_template_html_file('./html/index.html').render(
                context=context)
        elif path_name == "/ping":
            contents = su.read_template_html_file("./html/ping.html").render()
        elif path_name == "/get":
            number_sequence = arguments["sequence"][0]
            contents = su.get(list_sequences, number_sequence)
        elif path_name == "/gene":
            gene = arguments["gene"][0]
            contents = su.gene(gene)
        elif path_name == "/operation":
            sequence = arguments['sequence'][0]
            calculation = arguments['calculation'][0]
            if calculation == 'Info':
                contents = su.info(sequence)
            elif calculation == 'Comp':
                contents = su.comp(sequence)
            elif calculation == 'Rev':
                contents = su.rev(sequence)
            else:
                contents = su.read_template_html_file(
                    "./html/ERROR.html").render()
        else:
            contents = su.read_template_html_file("./html/ERROR.html").render()

        self.send_response(200)
        self.send_header('Content-Type', 'text/html')
        self.send_header('Content-Length', len(contents.encode()))
        self.end_headers()
        self.wfile.write(contents.encode())

        return
def list_species(connection, ENDPOINT, PARAMS, arguments, context):
    connection.request("GET", ENDPOINT + PARAMS)
    response = connection.getresponse()
    if response.status == 200:
        response_dict = json.loads(response.read().decode())
        # print(json.dumps(response_dict, indent=4, sort_keys=True))
        if arguments == {}:
            cont_type = 'text/html'
            context["limit"] = "ERROR"
            contents = su.read_template_html_file("./HTML/info/list_species.html").render(context=context)
            return contents, cont_type
        elif len(arguments.keys()) == 1 and "json" in arguments.keys():
            cont_type = 'application/json'
            context["limit"] = "ERROR"
            contents = json.dumps(context, indent=4, sort_keys=True)
            return contents, cont_type
        else:
            species_list = []
            amount_species = len(response_dict["species"])
            context["amount_species"] = amount_species
            limit = int(arguments["limit"][0])
            context["limit"] = limit
            if limit < amount_species:
                for n in range(0, limit):
                    species_list.append(response_dict["species"][n]["common_name"])
                context["names"] = species_list
            else:
                for n in range(0, amount_species):
                    species_list.append(response_dict["species"][n]["common_name"])
                context["names"] = species_list
            if "json" in arguments.keys():
                if arguments["json"][0] == "1":
                    cont_type = 'application/json'
                    contents = json.dumps(context, indent=4, sort_keys=True)
                    return contents, cont_type
            else:
                cont_type = 'text/html'
                contents = su.read_template_html_file("./HTML/info/list_species.html").render(context=context)
                return contents, cont_type
def geneCalc(connection, ENDPOINT, PARAMS, arguments, context, DICT_GENES):
    try:
        gene = arguments["gene"][0]
    except KeyError:
        if len(arguments.keys()) == 0:
            cont_type = 'text/html'
            context["bases"] = "ERROR"
            contents = su.read_template_html_file("./HTML/info/geneCalc.html").render(context=context)
            return contents, cont_type
        elif len(arguments.keys()) == 1:
            cont_type = 'application/json'
            context["bases"] = "ERROR"
            contents = json.dumps(context, indent=4, sort_keys=True)
            return contents, cont_type
    id = DICT_GENES[gene]
    connection.request("GET", ENDPOINT + id + PARAMS)
    response = connection.getresponse()
    if response.status == 200:
        response_dict = json.loads(response.read().decode())
        # print(json.dumps(response_dict, indent=4, sort_keys=True))
        sequence = Seq(response_dict["seq"])
        dict_bases, percentage_list = Seq.count_base_2(sequence)
        context["gene"] = gene
        context["length"] = Seq.len(sequence)
        context["bases"] = {
            "A": str(dict_bases["A"]) + " (" + str(percentage_list[0]) + "%)",
            "C": str(dict_bases["C"]) + " (" + str(percentage_list[1]) + "%)",
            "T": str(dict_bases["T"]) + " (" + str(percentage_list[2]) + "%)",
            "G": str(dict_bases["G"]) + " (" + str(percentage_list[3]) + "%)"
        }
        if "json" in arguments.keys():
            if arguments["json"][0] == "1":
                cont_type = 'application/json'
                contents = json.dumps(context, indent=4, sort_keys=True)
                return contents, cont_type
        else:
            cont_type = 'text/html'
            contents = su.read_template_html_file("./HTML/info/geneCalc.html").render(context=context)
            return contents, cont_type
def geneInfo(connection, ENDPOINT, PARAMS, arguments, context, DICT_GENES):
    try:
        gene = arguments["gene"][0]
    except KeyError:
        if len(arguments.keys()) == 0:
            cont_type = 'text/html'
            context["dict_info"] = "ERROR"
            contents = su.read_template_html_file("./HTML/info/geneInfo.html").render(context=context)
            return contents, cont_type
        elif len(arguments.keys()) == 1:
            cont_type = 'application/json'
            context["dict_info"] = "ERROR"
            contents = json.dumps(context, indent=4, sort_keys=True)
            return contents, cont_type
    id = DICT_GENES[gene]
    connection.request("GET", ENDPOINT + id + PARAMS)
    response = connection.getresponse()
    if response.status == 200:
        response_dict = json.loads(response.read().decode())
        # print(json.dumps(response_dict, indent=4, sort_keys=True))
        info = response_dict["desc"].split(":")
        context["gene"] = gene
        context["dict_info"] = {
            "Name": info[2],
            "ID": id,
            "Start": info[3],
            "End": info[4],
            "Length": (int(info[4]) - int(info[3]) + 1)
        }
        if "json" in arguments.keys():
            if arguments["json"][0] == "1":
                cont_type = 'application/json'
                contents = json.dumps(context, indent=4, sort_keys=True)
                return contents, cont_type
        else:
            cont_type = 'text/html'
            contents = su.read_template_html_file("./HTML/info/geneInfo.html").render(context=context)
            return contents, cont_type
def index(arguments, context, DICT_GENES):
    context["genes"] = DICT_GENES.keys()
    if "json" in arguments.keys():
        if arguments["json"][0] == "1":
            context = {
                "Basic level": [
                    "1) Species list (a limit is required)",
                    "2) Species karyotype (a species is required)",
                    "3) Chromosome length (a species and a chromosome are required)"
                ],
                "Medium level": [
                    "4) Gene sequence (a gene is required)",
                    "5) Gene information (a gene is required)",
                    "6) Gene calculations (a gene is required)",
                ]
            }
            cont_type = 'application/json'
            contents = json.dumps(context, indent=4, sort_keys=True)
            return contents, cont_type
    else:
        cont_type = 'text/html'
        contents = su.read_template_html_file("./HTML/info/index.html").render(context=context)
        return contents, cont_type
def chromosome_length(connection, ENDPOINT, PARAMS, arguments, context):
    try:
        specie = taking_out_space(arguments["species"][0])
    except KeyError:
        if len(arguments.keys()) == 0:
            cont_type = 'text/html'
            context["length"] = "ERROR"
            contents = su.read_template_html_file("./HTML/info/chromosome_length.html").render(context=context)
            return contents, cont_type
        elif len(arguments.keys()) == 1:
            if "chromosome" in arguments.keys():
                cont_type = 'text/html'
                context["length"] = "ERROR 2"
                contents = su.read_template_html_file("./HTML/info/chromosome_length.html").render(context=context)
                return contents, cont_type
            if "json" in arguments.keys():
                cont_type = 'application/json'
                context["length"] = "ERROR"
                contents = json.dumps(context, indent=4, sort_keys=True)
                return contents, cont_type
        elif len(arguments.keys()) == 2:
            cont_type = 'application/json'
            context["length"] = "ERROR 2"
            contents = json.dumps(context, indent=4, sort_keys=True)
            return contents, cont_type
    connection.request("GET", ENDPOINT + specie + PARAMS)
    response = connection.getresponse()
    if response.status == 200:
        response_dict = json.loads(response.read().decode())
        try:
            chromosome = arguments["chromosome"][0]
            # print(json.dumps(response_dict, indent=4, sort_keys=True))
        except KeyError:
            if len(arguments.keys()) == 1:
                if "species" in arguments.keys():
                    cont_type = 'text/html'
                    context["length"] = "ERROR 1"
                    contents = su.read_template_html_file("./HTML/info/chromosome_length.html").render(context=context)
                    return contents, cont_type
                if "json" in arguments.keys():
                    cont_type = 'application/json'
                    context["length"] = "ERROR"
                    contents = json.dumps(context, indent=4, sort_keys=True)
                    return contents, cont_type
            elif len(arguments.keys()) == 2:
                cont_type = 'application/json'
                context["length"] = "ERROR 1"
                contents = json.dumps(context, indent=4, sort_keys=True)
                return contents, cont_type
        for n in range(0, len(response_dict["top_level_region"])):
            if chromosome == response_dict["top_level_region"][n]["name"]:
                length = response_dict["top_level_region"][n]["length"]
        # print(length)
        context["species"] = arguments["species"][0]
        context["chromosome"] = chromosome
        context["length"] = length
        if "json" in arguments.keys():
            if arguments["json"][0] == "1":
                cont_type = 'application/json'
                contents = json.dumps(context, indent=4, sort_keys=True)
                return contents, cont_type
        else:
            cont_type = 'text/html'
            contents = su.read_template_html_file("./HTML/info/chromosome_length.html").render(context=context)
            return contents, cont_type
Exemplo n.º 10
0
    def do_GET(self):
        global contents
        # colorama.init(strip="False")
        """This method is called whenever the client invokes the GET method
        in the HTTP protocol request"""

        connection = http.client.HTTPConnection(SERVER)

        termcolor.cprint(self.requestline, 'green')
        termcolor.cprint(self.path, 'blue')

        o = urlparse(self.path)
        path_name = o.path
        arguments = parse_qs(o.query)
        print("Resource requested: ", path_name)
        print("Parameters: ", arguments)
        # IN this simple server version:
        # We are NOT processing the client's request
        # It is a happy server: It always returns a message saying
        # that everything is ok
        # Message to send back to the client
        context = {}
        try:
            if path_name == "/":
                contents, cont_type = su2.index(arguments, context, DICT_GENES)
            elif path_name.lower() == "/listspecies":
                ENDPOINT = "/info/species"
                contents, cont_type = su2.list_species(connection, ENDPOINT,
                                                       PARAMS, arguments,
                                                       context)
            elif path_name == "/karyotype":
                ENDPOINT = "info/assembly/"
                contents, cont_type = su2.karyotype(connection, ENDPOINT,
                                                    PARAMS, arguments, context)
            elif path_name == "/chromosomeLength":
                ENDPOINT = "info/assembly/"
                contents, cont_type = su2.chromosome_length(
                    connection, ENDPOINT, PARAMS, arguments, context)
            elif path_name == "/geneSeq":
                ENDPOINT = "/sequence/id/"
                contents, cont_type = su2.geneSeq(connection, ENDPOINT, PARAMS,
                                                  arguments, context,
                                                  DICT_GENES)
            elif path_name == "/geneInfo":
                ENDPOINT = "/sequence/id/"
                contents, cont_type = su2.geneInfo(connection, ENDPOINT,
                                                   PARAMS, arguments, context,
                                                   DICT_GENES)
            elif path_name == "/geneCalc":
                ENDPOINT = "/sequence/id/"
                contents, cont_type = su2.geneCalc(connection, ENDPOINT,
                                                   PARAMS, arguments, context,
                                                   DICT_GENES)
            else:
                contents = su.read_template_html_file(HTML +
                                                      "ERROR.html").render()
                cont_type = 'text/html'
        except KeyError:
            cont_type = 'text/html'
            contents = su.read_template_html_file(HTML + "ERROR.html").render()
        except ValueError:
            cont_type = 'text/html'
            contents = su.read_template_html_file(HTML + "ERROR.html").render()
        except TypeError:
            cont_type = 'text/html'
            contents = su.read_template_html_file(HTML + "ERROR.html").render()
        except UnboundLocalError:
            cont_type = 'text/html'
            contents = su.read_template_html_file(HTML + "ERROR.html").render()

        # Generating the response message
        self.send_response(200)  # -- Status line: OK!
        length = len(contents.encode())
        # Define the content-type header:
        self.send_header('Content-Type', cont_type)
        self.send_header('Content-Length', str(length))

        # The header is finished
        self.end_headers()

        # Send the response message
        self.wfile.write(str.encode(contents))

        return
Exemplo n.º 11
0
    def do_GET(self):
        global contents
        termcolor.cprint(self.requestline, 'green')
        termcolor.cprint(self.path, 'blue')

        o = urlparse(self.path)
        path_name = o.path
        arguments = parse_qs(o.query)
        print("Resource requested: ", path_name)
        print("Parameters: ", arguments)
        # IN this simple server version:
        # We are NOT processing the client's request
        # It is a happy server: It always returns a message saying
        # that everything is ok
        context = {}
        # Message to send back to the client
        PARAMETERS = '?content-type=application/json'
        SERVER = "rest.ensembl.org"
        connection = http.client.HTTPConnection(SERVER)
        if path_name == '/':
            contents = Path('./html/index.html').read_text()
        elif path_name == "/listSpecies":
            try:
                ENDPOINT = '/info/species'
                connection.request('GET', ENDPOINT + PARAMETERS)
                response = connection.getresponse()
                final_response = json.loads(response.read().decode())
                species_list = final_response['species']
                names_list = []
                for elem in species_list:
                    s1 = elem['name']
                    lists = [s1]
                    names_list = names_list + lists
                if 'limit' in arguments:
                    limit = int(arguments['limit'][0])
                    final_list = names_list[:limit]
                    if limit <= len(final_list):
                        context['length'] = len(names_list)
                        context['final_list'] = final_list
                        context['limit'] = limit
                        contents = su.read_template_html_file(
                            './html/limit_name_list.html').render(
                                context=context)
                    else:
                        contents = su.read_template_html_file(
                            './html/error.html').render(context=context)
                elif 'limit' not in arguments:
                    context['length'] = len(names_list)
                    context['final_list'] = names_list
                    contents = su.read_template_html_file(
                        './html/full_name_list.html').render(context=context)
            except KeyError:
                contents = su.read_template_html_file(
                    './html/error.html').render(context=context)
        elif path_name == "/karyotype":
            try:
                species_name = arguments['species_name'][0]
                ENDPOINT = '/info/assembly/'
                connection.request('GET', ENDPOINT + species_name + PARAMETERS)
                response = connection.getresponse()
                final_response = json.loads(response.read().decode())
                karyotype = final_response['karyotype']
                context['karyotype'] = karyotype
                contents = su.read_template_html_file(
                    './html/karyotype.html').render(context=context)
            except KeyError:
                contents = su.read_template_html_file(
                    './html/error.html').render(context=context)
        elif path_name == "/chromosomeLength":
            try:
                if 'species_name' not in arguments:
                    contents = su.read_template_html_file(
                        './html basic/ERROR.html').render()
                elif 'chromosome_name' not in arguments:
                    contents = su.read_template_html_file(
                        './html basic/ERROR.html').render()
                else:
                    global chromosome_length
                    species_name = arguments['species_name'][0]
                    chromosome_name = arguments['chromosome_name'][0]
                    ENDPOINT = '/info/assembly/'
                    connection.request('GET',
                                       ENDPOINT + species_name + PARAMETERS)
                    response = connection.getresponse()
                    final_response = json.loads(response.read().decode())
                    list_dict = final_response['top_level_region']
                    for elem in list_dict:
                        if (elem['name']
                                == chromosome_name) and (elem['coord_system']
                                                         == 'chromosome'):
                            chromosome_length = elem['length']
                        else:
                            contents = su.read_template_html_file(
                                './html/error.html').render(context=context)
                    context['chromosome_length'] = chromosome_length
                    contents = su.read_template_html_file(
                        './html/chromosome_length.html').render(
                            context=context)

            except KeyError:
                contents = su.read_template_html_file(
                    './html/error.html').render(context=context)
        elif path_name == "/geneSeq":
            try:
                gene = arguments['gene'][0]
                GENE_ID = genes_dict[gene]

                ENDPOINT = '/sequence/id/'
                connection.request('GET', ENDPOINT + GENE_ID + PARAMETERS)
                response = connection.getresponse()
                final_response = json.loads(response.read().decode())
                sequence = final_response['seq']
                context['sequence'] = sequence
                contents = su.read_template_html_file(
                    './html/Seq.html').render(context=context)
            except KeyError:
                contents = su.read_template_html_file(
                    './html/error.html').render(context=context)
        elif path_name == "/geneInfo":
            try:
                gene = arguments['gene'][0]
                GENE_ID = genes_dict[gene]
                ENDPOINT = '/sequence/id/'
                connection.request('GET', ENDPOINT + GENE_ID + PARAMETERS)
                response = connection.getresponse()
                final_response = json.loads(response.read().decode())
                info_list = final_response['desc'].split(':')
                context['genname'] = gene
                context['start'] = info_list[3]
                context['end'] = info_list[4]
                context['length'] = int(info_list[4]) - int(info_list[3])
                context['id'] = GENE_ID
                context['chromoname'] = info_list[1]
                contents = su.read_template_html_file(
                    './html/Info.html').render(context=context)
            except KeyError:
                contents = su.read_template_html_file(
                    './html/error.html').render(context=context)
        elif path_name == '/geneCalc':
            try:
                gene = arguments['gene'][0]
                GENE_ID = genes_dict[gene]
                ENDPOINT = '/sequence/id/'
                connection.request('GET', ENDPOINT + GENE_ID + PARAMETERS)
                response = connection.getresponse()
                final_response = json.loads(response.read().decode())
                sequence = final_response['seq']
                s = Seq(sequence)
                context['length'] = s.len()
                context['percentageA'] = s.percentage_base('A')
                context['percentageC'] = s.percentage_base('C')
                context['percentageG'] = s.percentage_base('G')
                context['percentageT'] = s.percentage_base('T')
                contents = su.read_template_html_file(
                    './html/Calc.html').render(context=context)
            except KeyError:
                contents = su.read_template_html_file(
                    './html/error.html').render(context=context)
        else:
            pass
        self.send_response(200)  # -- Status line: OK!

        # Define the content-type header:
        self.send_header('Content-Type', 'text/html')
        content_length = len(str.encode(contents))
        self.send_header('Content-Length', content_length)

        # The header is finished
        self.end_headers()

        # Send the response message
        self.wfile.write(contents.encode())
        return
Exemplo n.º 12
0
    def do_GET(self):
        global contents
        colorama.init(strip="False")
        """This method is called whenever the client invokes the GET method
        in the HTTP protocol request"""

        # Print the request line
        termcolor.cprint(self.requestline, 'green')
        termcolor.cprint(self.path, 'blue')

        o = urlparse(self.path)
        path_name = o.path
        arguments = parse_qs(o.query)
        print("Resource requested: ", path_name)
        print("Parameters: ", arguments)
        # IN this simple server version:
        # We are NOT processing the client's request
        # It is a happy server: It always returns a message saying
        # that everything is ok
        # Message to send back to the client
        context = {}
        if path_name == "/":
            context["n_seq"] = len(LIST_SEQ)
            context["list_genes"] = LIST_GENE
            context["operation_list"] = OPERATION_LIST
            contents = su.read_template_html_file(HTML_ASSETS + "index.html").render(context=context)
        elif path_name == "/ping":
            contents = su.read_template_html_file(HTML_ASSETS + "ping.html").render()
        elif path_name == "/get":
            number_seq = arguments["sequence"][0]
            contents = su.get(LIST_SEQ, number_seq)
        elif path_name == "/gene":
            gene = arguments["gene"][0]
            contents = su.gene(gene)
        elif path_name == "/operation":
            sequence = arguments["sequence"][0]
            operation = arguments["calculation"][0]
            if operation == "info":
                contents = su.info(sequence)
            elif operation == "comp":
                contents = su.comp(sequence)
            elif operation == "rev":
                contents = su.rev(sequence)
        else:
            contents = su.read_template_html_file(HTML + "ERROR.html").render()


        # Generating the response message
        self.send_response(200)  # -- Status line: OK!
        length = len(contents.encode())
        # Define the content-type header:
        self.send_header('Content-Type', 'text/html')
        self.send_header('Content-Length', str(length))

        # The header is finished
        self.end_headers()

        # Send the response message
        self.wfile.write(contents.encode())

        return
Exemplo n.º 13
0
    def do_GET(self):

        termcolor.cprint(self.requestline, 'green')
        termcolor.cprint(self.path, "blue")
        o = urlparse(self.path)
        path_name = o.path
        arguments = parse_qs(o.query)
        print("Resoruce requested: ", path_name)
        print("Parameters: ", arguments)
        if 'json' in arguments.keys() and arguments["json"][0] == "1":
            if path_name == "/listSpecies":
                ENDPOINT = "/info/species"
                response = su.api_connection(ENDPOINT, PARAMS, SERVER)
                try:
                    if type(arguments["limit"][0]) == str:
                        contents = json.dumps(au.json_species(
                            response, int(arguments["limit"][0])),
                                              indent=4,
                                              sort_keys=True)
                except KeyError:
                    contents = json.dumps(au.json_species(response),
                                          indent=4,
                                          sort_keys=True)
                except ValueError:
                    contents = json.dumps("Sorry, the data introduced is bad",
                                          indent=4,
                                          sort_keys=True)
            elif path_name == "/Karyotype":
                try:
                    ENDPOINT = "/info/assembly/"
                    specie = arguments["specie"][0]
                    for element in specie:
                        if element == " ":
                            specie = specie.replace(element, "_")
                    ENDPOINT = ENDPOINT + specie
                    response = su.api_connection(ENDPOINT, PARAMS, SERVER)
                    context = {
                        "specie": specie,
                        "karyotype": response["karyotype"]
                    }
                    contents = json.dumps(context, indent=4, sort_keys=True)
                except KeyError:
                    contents = json.dumps("Sorry, the data introduced is bad",
                                          indent=4,
                                          sort_keys=True)
            elif path_name == "/chromosomeLength":
                try:
                    ENDPOINT = "/info/assembly/"
                    specie = arguments["specie"][0]
                    for element in specie:
                        if element == " ":
                            specie = specie.replace(element, "_")
                    print(specie)
                    chromo = arguments["chromo"][0]
                    ENDPOINT = ENDPOINT + specie
                    response = su.api_connection(ENDPOINT, PARAMS, SERVER)
                    contents = json.dumps(au.json_chromosome_length(
                        response, specie, chromo),
                                          indent=4,
                                          sort_keys=True)
                except KeyError:
                    contents = json.dumps("Sorry, the data introduced is bad",
                                          indent=4,
                                          sort_keys=True)
            elif path_name == "/geneSeq":
                ENDPOINT = "/sequence/id/"
                ID = arguments["gene"][0]
                if ID in gene_dict:
                    ENDPOINT = ENDPOINT + gene_dict[ID]
                    response = su.api_connection(ENDPOINT, PARAMS, SERVER)
                    context = {
                        "Sequence": response["seq"],
                        "name": ID,
                        "id": response["id"]
                    }
                    contents = json.dumps(context, indent=4, sort_keys=True)
                else:
                    contents = json.dumps("Sorry, the data introduced is bad",
                                          indent=4,
                                          sort_keys=True)

            elif path_name == "/geneInfo":
                ENDPOINT = "/sequence/id/"
                ID = arguments["gene"][0]
                if ID in gene_dict:
                    ENDPOINT = ENDPOINT + gene_dict[ID]
                    response = su.api_connection(ENDPOINT, PARAMS, SERVER)
                    contents = json.dumps(au.json_calculations(response, ID),
                                          indent=4,
                                          sort_keys=True)
                else:
                    contents = json.dumps("Sorry, the data introduced is bad",
                                          indent=4,
                                          sort_keys=True)
            elif path_name == "/geneCalc":
                ENDPOINT = "/sequence/id/"
                ID = arguments["gene"][0]
                if ID in gene_dict:
                    ENDPOINT = ENDPOINT + gene_dict[ID]
                    response = su.api_connection(ENDPOINT, PARAMS, SERVER)
                    contents = json.dumps(au.json_second_calculations(
                        response, ID),
                                          indent=4,
                                          sort_keys=True)
                else:
                    contents = json.dumps("Sorry, the data introduced is bad",
                                          indent=4,
                                          sort_keys=True)
            else:
                contents = json.dumps("Sorry, the data introduced is bad",
                                      indent=4,
                                      sort_keys=True)

        else:

            if path_name == "/":
                context = {"gene_list": gene_dict}
                contents = su.read_template_html_file(
                    ROOT + "/Basic_level.html").render(context=context)

            elif path_name == "/listSpecies":
                ENDPOINT = "/info/species"
                response = su.api_connection(ENDPOINT, PARAMS, SERVER)
                if "check" in arguments.keys():
                    termcolor.cprint("The checkbox was checked", "red")
                else:
                    termcolor.cprint("The checkbox was unchecked", "red")

                try:
                    if type(arguments["limit"][0]) == str:
                        contents = su.species_list(response,
                                                   int(arguments["limit"][0]))
                except KeyError:
                    contents = su.species_list(response)
                except ValueError:
                    contents = su.read_template_html_file(
                        ROOT + "/ERROR.html").render()

            elif path_name == "/Karyotype":
                try:
                    ENDPOINT = "/info/assembly/"
                    specie = arguments["specie"][0]
                    for element in specie:
                        if element == " ":
                            specie = specie.replace(element, "_")
                    ENDPOINT = ENDPOINT + specie
                    response = su.api_connection(ENDPOINT, PARAMS, SERVER)
                    context = {
                        "specie": specie,
                        "karyotype": response["karyotype"]
                    }
                    contents = su.read_template_html_file(
                        ROOT + "/karyotype.html").render(context=context)
                except KeyError:
                    contents = su.read_template_html_file(
                        ROOT + "/ERROR.html").render()
            elif path_name == "/chromosomeLength":
                try:
                    ENDPOINT = "/info/assembly/"
                    specie = arguments["specie"][0]
                    for element in specie:
                        if element == " ":
                            specie = specie.replace(element, "_")
                    chromo = arguments["chromo"][0]
                    ENDPOINT = ENDPOINT + specie
                    response = su.api_connection(ENDPOINT, PARAMS, SERVER)
                    contents = su.chromosome_length(response, specie, chromo)
                except KeyError:
                    contents = su.read_template_html_file(
                        ROOT + "/ERROR.html").render()

            elif path_name == "/geneSeq":
                ENDPOINT = "/sequence/id/"
                ID = arguments["gene"][0]
                ENDPOINT = ENDPOINT + gene_dict[ID]
                response = su.api_connection(ENDPOINT, PARAMS, SERVER)
                context = {
                    "Sequence": response["seq"],
                    "name": ID,
                    "id": response["id"]
                }
                contents = su.read_template_html_file(ROOT +
                                                      "/GENE.html").render(
                                                          context=context)

            elif path_name == "/geneInfo":
                ENDPOINT = "/sequence/id/"
                ID = arguments["gene"][0]
                ENDPOINT = ENDPOINT + gene_dict[ID]
                response = su.api_connection(ENDPOINT, PARAMS, SERVER)
                contents = su.calculations(response, ID)

            elif path_name == "/geneCalc":
                ENDPOINT = "/sequence/id/"
                ID = arguments["gene"][0]
                ENDPOINT = ENDPOINT + gene_dict[ID]
                response = su.api_connection(ENDPOINT, PARAMS, SERVER)
                contents = su.second_calculations(response, ID)

            else:
                contents = su.read_template_html_file(ROOT +
                                                      "/ERROR.html").render()

        # Generating the response message
        self.send_response(200)  # -- Status line: OK!

        # Define the content-type header:
        self.send_header('Content-Type', 'text/html')
        self.send_header('Content-Length', str(len(contents.encode())))

        # The header is finished
        self.end_headers()

        # Send the response message
        self.wfile.write(contents.encode())

        return