示例#1
0
def client_dic():
    js = client()
    dic = {}
    return {j['title']+j['body']:j['image'] for j in js if 'title' in j and 'body' in j and 'image' in j}
示例#2
0
    print(f"Response received!: {r1.status} {r1.reason}\n")
    data1 = r1.read().decode("utf-8")
    data = json.loads(data1)
    print(data)


valid = True
while valid:
    menu()
    json_param = input("Choose a json parameter(must be 1 for it to work): ")
    options = int(input("Choose an option: "))

    if options == 1:
        limit = input("Type the number of species you want to be shown: ")
        url = "/listSpecies?limit=" + limit
        client(url, json_param)

    elif options == 2:
        specie = input("Choose any specie: ")
        url = "/karyotype?specie=" + specie
        client(url, json_param)

    elif options == 3:
        specie = input("Choose specie: ")
        chromosome = input("Choose chromosome: ")
        url = f"/chromosomeLength?specie={specie}&chromo={chromosome}"
        client(url, json_param)
    elif options == 4:
        gene = input("Choose a human gene: ")
        url = "/geneSeq?gene=" + gene
        client(url, json_param)
示例#3
0
def main():
	if len(sys.argv) > 1:
		port = int(sys.argv[1])
		server(("", port))
	else:
		client()
示例#4
0
    response - JSON formated server response
    return   - actual string response from server
    '''
    response_py = json.loads(response)
    return response_py['response']


def client():
    # set up connectin with server
    connection = http.client.HTTPConnection(dest)
    while (1):
        user_input = None
        try:
            user_input = input('user: '******''.join(['askmeanything/?q=', url_encoded_input])
        # send a request to server
        connection.request('get', request_path)
        # read the response
        response = connection.getresponse()
        print(getBotResponse(response.read().decode()))
    print("Conversation ended")


if __name__ == "__main__":
    client()
示例#5
0
    def do_GET(self):
        """This method is called whenever the client invokes the GET method
        in the HTTP protocol request"""

        # Printing in the server some useful information
        print("GET received")
        print("Request line:" + self.requestline)
        print(" Cmd: " + self.command)
        print(" Path: " + self.path)

        # Separating and selecting the information of the path
        calling_response = self.path.split("?")[0]
        # Separating and selecting the information of the path
        p = (self.path.replace("=", ",")).replace("&", ",")
        ins = p.split(
            ","
        )  # Making a list of instructions dividing the string in the = and & symbols
        # Assigning to the variable page different html pages names in function of the request
        l_text = []
        if self.path == "/":
            page = "main-page.html"

        elif calling_response == "/listSpecies":  # Using the resource /Seq
            result0 = client(ENDPOINT0)
            p = (self.path.replace("=", ",")).replace("&", ",")
            ins = p.split(
                ","
            )  # Making a list of instructions dividing the string in the = and & symbols
            print(ins)

            print(len(ins))
            # idea de mejora
            if len(ins) == 2:
                limit = int(ins[1])
            else:
                limit = len(result0["species"])
            for index in range(limit):
                l_text.append(result0["species"][index]["name"])

            page = "response.html"

        elif calling_response == "/karyotype":  # Using the resource /karyotype

            ENDPOINT1 = "/info/assembly/" + ins[
                1] + "?content-type=application/json"
            result1 = client(ENDPOINT1)
            for chrom in result1[
                    "karyotype"]:  # Transformation into a string with intros "<br>"
                l_text.append(chrom)
            page = "response.html"

        else:
            page = "error.html"

        # -- printing the request line
        termcolor.cprint(self.requestline, 'green')

        f = open(page, 'r')
        contents = f.read()  # reading the contents of the selected page

        # If the html response page is requested change the word text by the text of the user
        if page == "response.html":
            text = ""
            for string in l_text:
                text += string + "<br>"
            contents = contents.replace("text", text)

        # Generating and sending the response message according to the request
        self.send_response(200)
        self.send_header('Content-Type', 'text/html')
        self.send_header('Content-Length', len(str.encode(contents)))
        self.end_headers()

        # -- sending the body of the response message
        self.wfile.write(str.encode(contents))
        r1 = connect.getresponse()

        # Print the status line
        print(f"Response received!: {r1.status} {r1.reason}\n")

        # Read the response's body
        data1 = r1.read().decode("utf-8")
        # Print the received data
        data = json.loads(data1)
        return data


try:
    ARGUMENTS = "?limit=10&json=1"
    PATH_NAME = "/listSpecies"
    data = client(ARGUMENTS, PATH_NAME)
    list_names = " "
    for name in data["species_list"]:
        list_names = list_names + name + ", "
    print("The total number of species in the ensemble is: ", data["length"])
    print("The limit you have selected is: ", data["input_number"])
    print("The names of the species are", list_names)

except ConnectionRefusedError:
        print("ERROR! Cannot connect to the Server")
        exit()

try:
    ARGUMENTS = "?specie=human&json=1"
    PATH_NAME = "/karyotype"
    data = client(ARGUMENTS, PATH_NAME)
 def gene_seq(self):
     ENDPOINT4 = "/sequence/id/" + self.id() + "?content-type=application/json"
     result4 = client(ENDPOINT4)
     return result4["seq"]
    def do_GET(self):
        """This method is called whenever the client invokes the GET method
        in the HTTP protocol request"""

        # Printing in the server some useful information
        print("GET received")
        print("Request line:" + self.requestline)
        print(" Cmd: " + self.command)
        print(" Path: " + self.path)

        # Separating and selecting the information of the path
        res = self.path.split("?")[0]
        p = (self.path.replace("=", ",")).replace("&", ",")
        ins = p.split(",")  # Making a list of instructions dividing the string in the = and & symbols

        # Some important parameters
        text = ""  # Empty string that will save the response information
        sp = Seq(ins[-1])  # Object used in the genes calculations
        page = "response.html"  # The page will be response except if the endpoint is "/" or it does not exist

        try:
            if self.path == "/":  # Using the resource / to obtain the main page with all the options
                page = "main-page.html"

            elif res == "/listSpecies":  # Using the resource /listSpecies

                result0 = client(ENDPOINT0)
                # The variable limit has been created to avoid the error "referenced before assignment"
                limit = ""
                # The second parameter is the limit
                if len(ins) == 2:
                    limit = int(ins[1])
                # Using elif instead of else to avoid sending the list of species with 3 or more parameters
                elif len(ins) == 1:
                    limit = len(result0["species"])  # If there is no limit the loop will be over all the species
                for index in range(limit):
                    text += result0["species"][index]["name"] + "<br>"

            elif res == "/karyotype":  # Using the resource /karyotype

                ENDPOINT1 = "/info/assembly/"+ins[-1]+"?content-type=application/json"
                result1 = client(ENDPOINT1)
                for chrom in result1["karyotype"]:  # Transformation into a string with intros "<br>"
                    text += chrom+"<br>"

            elif res == "/chromosomeLength":  # Using the resource /chromosomeLength

                specie = ins[1]
                ch = ins[-1]
                ENDPOINT2 = "/info/assembly/"+specie+"/"+ch+"?content-type=application/json"
                result2 = client(ENDPOINT2)
                text += str(result2["length"])  # Obtaining the value that corresponds to the length keyword

            elif res == "/geneSeq":  # Using the resource /geneSeq

                text += sp.gene_seq()  # calling the method gene_seq to obtain the sequence of the sp object

            elif res == "/geneInfo":

                id_number = sp.id()  # calling the method id to obtain the identity number of the sp object
                ENDPOINT5 = "/overlap/id/" + id_number + "?feature=gene;content-type=application/json"
                result4 = client(ENDPOINT5)  # Dictionary that contains several lists of information for different genes

                a = ""  # This variable avoids the error "referenced before assignment"
                for i in range(len(result4)):  # loop to search which gene is the one that coincides with our requisites
                    if result4[i]["id"] == id_number:  # the correct information is in the list in which is our id gene
                        a = i
                # Searching the values in the selected list
                text += "Start: " + str(result4[a]["start"]) + "<br>"
                text += "End: " + str(result4[a]["end"]) + "<br>"
                text += "Length: " + str(result4[a]["end"] - result4[a]["start"] + 1) + "<br>"  # sum also 1st position
                text += "ID: " + str(result4[a]["id"]) + "<br>"
                text += "Chromosome: " + str(result4[a]["seq_region_name"]) + "<br>"

            elif res == "/geneCalc":  # Using the resource /geneCalc

                text += sp.results()  # calling the results method

            elif res == "/geneList":  # Using the resource /geneList

                start = ins[3]
                end = ins[-1]
                ch = ins[1]
                ENDPOINT6 = "/overlap/region/human/"+ch+":"+start+"-"+end+"?content-type=application/json;feature=gene"
                result5 = client(ENDPOINT6)
                # Searching the name of each gene in the dictionary
                for index in range(len(result5)):
                    text += result5[index]["external_name"] + "<br>"

                # Preventing some common errors
                if start == end:
                    text += "<b>"+"Sorry, you have introduced the same number for the start than for the end."+"</b>"
                    text += "<b>"+"<br><br>"+"So obviously, as there is no region, there is no gene contained."+"</b>"
                if text == "":
                    text += "<b>"+"There is no gene in the selected region"+"</b>"

            else:
                page = "error.html"  # If it is not one of the previous resources

            # improvement in the server to avoid taking as correct an extra valid parameter. Ex: gene=FRAT1&gene=BRAF
            if res in ["/karyotype", "/chromosomeLength", "/geneSeq", "/geneInfo", "/geneCalc", "/geneList"]:

                # checking the length of the instructions and generating a KeyError if they are not correct
                if len(ins) > 2 and res != "/chromosomeLength" and res != "/geneList":
                    text += client(ENDPOINT0)["e"]
                elif (len(ins) > 4 and res == "/chromosomeLength") or (len(ins) > 6 and res == "/geneList"):
                    text += client(ENDPOINT0)["e"]

        # Dealing with the main errors
        except ValueError:
            text = "<b>"+"Incorrect value in the parameter 'limit'"+"<br>"+"Please introduce an integer number"+"</b>"
        except TypeError:
            text = "<b>"+"Sorry, the endpoint '/listSpecies' does not admit three or more parameters"+"</b>"
        except KeyError:
            text = "<b>"+"Incorrect parameters"+"<br>"+"Please review their spelling and the amount required"+"</b>"
        except Exception:  # Emergency exception that has not been detected yet
            text = "<b>"+"Sorry, an error has been produced"+"<br>"+"Please review the performed actions"+"</b>"

        # -- printing the request line
        termcolor.cprint(self.requestline, 'green')

        # -- Opening the selected page
        f = open(page, 'r')
        contents = f.read()  # reading the contents of the selected page

        # If the html response page is requested change the word text by the text of the user
        if page == "response.html":
            contents = contents.replace("text", text)

        # Generating and sending the response message according to the request
        self.send_response(200)
        self.send_header('Content-Type', 'text/html')
        self.send_header('Content-Length', len(str.encode(contents)))
        self.end_headers()

        # -- sending the body of the response message
        self.wfile.write(str.encode(contents))
示例#9
0
 def tunggu(x):
     sys.stdout.write(
         "\r                                        \r")
     for remaining in range(x, 0, -1):
         sys.stdout.write("\\r")
         sys.stdout.write(
             "{}[{}|{}]{} {:2d} {}seconds remaining".format(
                 abu2, yellow2, abu2, res, remaining,
                 hijau))
         sys.stdout.flush()
         sleep(0.125)
         sys.stdout.write("\\r")
         sys.stdout.write(
             "{}[{}/{}]{} {:2d} {}seconds remaining".format(
                 abu2, yellow2, abu2, res, remaining,
                 hijau))
         sys.stdout.flush()
         sleep(0.125)
         sys.stdout.write("\\r")
         sys.stdout.write(
             "{}[{}-{}]{} {:2d}{} seconds remaining".format(
                 abu2, yellow2, abu2, res, remaining,
                 hijau))
         sys.stdout.flush()
         sleep(0.125)
         sys.stdout.write("\\r")
         sys.stdout.write(
             "{}[{}\\{}]{} {:2d}{} seconds remaining".
             format(abu2, yellow2, abu2, res, remaining,
                    hijau))
         sys.stdout.flush()
         sleep(0.125)
         sys.stdout.write("\\r")
         sys.stdout.write(
             "{}[{}|{}]{} {:2d}{} seconds remaining".format(
                 abu2, yellow2, abu2, res, remaining,
                 hijau))
         sys.stdout.flush()
         sleep(0.125)
         sys.stdout.write("\\r")
         sys.stdout.write(
             "{}[{}/{}]{} {:2d} {}seconds remaining".format(
                 abu2, yellow2, abu2, res, remaining,
                 hijau))
         sys.stdout.flush()
         sleep(0.125)
         sys.stdout.write("\\r")
         sys.stdout.write(
             "{}[{}-{}]{} {:2d} {}seconds remaining".format(
                 abu2, yellow2, abu2, res, remaining,
                 hijau))
         sys.stdout.flush()
         sleep(0.125)
         sys.stdout.write("\\r")
         sys.stdout.write(
             "{}[{}\\{}]{} {:2d}{} seconds remaining".
             format(abu2, yellow2, abu2, res, remaining,
                    hijau))
         sys.stdout.flush()
         sleep(0.125)
         sys.stdout.write(
             "\\r                                           \\r"
         )
         sys.stdout.write(
             f"\\r{abu2}[{yellow2}!{abu2}] {yellow}Getting Reward"
         )
         ua = {
             "User-Agent":
             "Mozilla/5.0 (Linux; Android 5.1; A1603 Build/LMY47I; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.121 Mobile Safari/537.36"
         }
         c = requests.session()
         if len(sys.argv) < 2:
             print(banner)
             print(
                 yellow2 +
                 "\\n\\n\\nUsage : python main.py +62xxxxxxxxxx"
             )
             sys.exit(1)
             login(sys.argv[1])
             channel_entity = client.get_entity(
                 "@ClickBeeBot")
             channel_username = "******"
             while True:
                 sys.stdout.write(
                     "\\r                                             \\r"
                 )
                 sys.stdout.write(
                     f"\\r{abu2}[{yellow2}!{abu2}]{yellow} Mencoba Mengambil URL"
                 )
                 client.send_message(
                     entity=channel_entity,
                     message="\xf0\x9f\x9a\xb2 Visit Links")
                 sleep(3)
                 posts = client(
                     GetHistoryRequest(peer=channel_entity,
                                       limit=1,
                                       offset_date=None,
                                       offset_id=0,
                                       max_id=0,
                                       min_id=0,
                                       add_offset=0,
                                       hash=0))
                 if posts.messages[0].message.find(
                         "Aw snap! You can\'t visit any websites for now."
                 ) != -1:
                     sys.stdout.write(
                         "\\r                                                 \\r"
                     )
                     print(
                         f"\\n{abu2}[{red2}x{abu2}] {red}Iklan Sudah Habis Coba Lagi Besok"
                     )
                     break
                 else:
                     url = posts.messages[
                         0].reply_markup.rows[0].buttons[
                             0].url
                     sys.stdout.write(
                         "\r                                              \r"
                     )
                     sys.stdout.write(
                         f"\r{abu2}[{yellow2}!{abu2}]{yellow} Memulai Mengunjungi Situs...!"
                     )
                     r = c.get(url, headers=ua)
                     soup = BeautifulSoup(
                         r.text, "html.parser")
                     if soup.find('form',
                                  method="GET") is not None:
                         sys.stdout.write(
                             "\r                                              \r"
                         )
                         sys.stdout.write(
                             f"\r{abu2}[{yellow2}!{abu2}]{yellow} Timer Detected....!"
                         )
                         waktu = soup.find('i', id="timer")
                         tunggu(int(waktu.text))
                         link = soup.find(
                             'form', method="GET").find(
                                 'input').get('value')
                         r = c.get(
                             'https://clickbeeads.com/link.php?u='
                             + link)
                         sleep(3)
                         posts = client(
                             GetHistoryRequest(
                                 peer=channel_entity,
                                 limit=1,
                                 offset_date=None,
                                 offset_id=0,
                                 max_id=0,
                                 min_id=0,
                                 add_offset=0,
                                 hash=0))
                         sys.stdout.write(
                             "\\r                                        \\r"
                         )
                         sys.stdout.write(
                             "\\r" +
                             f"\\r{abu2}[{hijau2}+{abu2}]{hijau} "
                             + posts.messages[0].message.
                             replace(
                                 "\xe2\x9c\x85 Task Completed!\\n",
                                 "") + "\\n")
 def id(self):
     ENDPOINT3 = "/lookup/symbol/homo_sapiens/" + self.strbases + "?content-type=application/json"
     result3 = client(ENDPOINT3)
     return result3["id"]
示例#11
0
    def __init__(self):
        super().__init__()

    def __call__(self, path="/"):
        #in host parameter we have to specify the host name
        #we can not but "" for localhost
        #the name of the service must be defined
        rest = http.client.HTTPConnection("localhost", 8080)
        #make request with method get
        rest.request("GET", path)
        response = rest.getresponse()
        #display respnse info
        #print(response.status, response.reason)
        #print(response.getheaders())
        #get the charset
        content_header = response.getheader("Content-Type")
        pattren = re.compile(r".*charset=(.*$)")
        match = pattren.match(content_header)
        charset = match.group(1) if match else "UTF-8"

        row = response.read().decode(charset)
        if response.status == "200":
            print(json.loads(row))
        else:
            print(row)


if __name__ == "__main__":
    client = Roulette_client()
    client("/am")
    def do_GET(self):
        """This method is called whenever the client invokes the GET method
        in the HTTP protocol request"""

        # Printing in the server some useful information
        print("GET received")
        print("Request line:" + self.requestline)
        print(" Cmd: " + self.command)
        print(" Path: " + self.path)

        # Separating and selecting the information of the path
        res = self.path.split("?")[0]
        p = (self.path.replace("=", ",")).replace("&", ",")
        ins = p.split(",")  # Making a list of instructions dividing the string in the = and & symbols
        print(" Ins: ", ins)

        # Some important parameters
        text = []  # Empty list that will save the response information
        j_dict = {}  # Dictionary that will save the response information when json_opt == "json1"
        page = "response.html"  # Our page will be response except if the endpoint is "/" or it does not exist
        keyword_j_dict = ""  # Keyword of j_dict to which we will assign specific values of text list
        y = []  # parameter only used in case we want to print a unique string contained in a list
        code = 200  # if everything is OK!

        # Classification of the information requested in function of the resource
        try:
            if self.path == "/":  # Using the resource / to obtain the main page with all the options
                page = "main-page.html"

            elif res == "/listSpecies":  # Using the resource /listSpecies

                result0 = client(ENDPOINT0)
                # The variable limit has been created to avoid the error "referenced before assignment"
                limit = ""
                if "json=1" in self.path:
                    j = 4  # j is the length of instructions with limit parameter
                    k = 2  # k is the length of instructions without limit parameter
                else:
                    j = 2
                    k = 1

                if len(ins) == j:
                    limit = int(ins[1])
                # Using elif instead of else to avoid sending the list of species with excess of parameters
                elif len(ins) == k:
                    limit = len(result0["species"])  # If there is no limit, the loop will iterate over all the species
                for index in range(limit):
                    text.append(result0["species"][index]["name"])

                keyword_j_dict += "species"  # Our keyword "species" will be assigned with all species values

            elif res == "/karyotype":  # Using the resource /karyotype

                ENDPOINT1 = "/info/assembly/"+ins[1]+"?content-type=application/json"
                result1 = client(ENDPOINT1)
                text = result1["karyotype"]  # text will be our list of chromosomes

                keyword_j_dict = "karyotype"  # choosing the word karyotype as a keyword

            elif res == "/chromosomeLength":  # Using the resource /chromosomeLength

                specie = ins[1]
                ch = ins[3]
                ENDPOINT2 = "/info/assembly/"+specie+"/"+ch+"?content-type=application/json"
                result2 = client(ENDPOINT2)
                text.append(str(result2["length"]))  # Selecting the value that corresponds to the length keyword
                keyword_j_dict = "length"  # Name of the keyword of j_dict for this case
                y.append(0)  # this will be used to indicate that we want the string contained in the list

            elif res == "/geneSeq":  # Using the resource /geneSeq

                sp = Seq(ins[1])  # Object of the species name
                text.append(sp.gene_seq())  # calling the method gene_seq to obtain the sequence of the sp object
                keyword_j_dict = "seq"  # Name of the keyword of j_dict for this case
                y.append(0)  # this will be used to indicate that we want the string contained in the list

            elif res == "/geneInfo":

                sp = Seq(ins[1])  # Object of the species name
                id_number = sp.id()  # calling the method id to obtain the identity number of the sp object
                ENDPOINT5 = "/overlap/id/" + id_number + "?feature=gene;content-type=application/json"
                result4 = client(ENDPOINT5)  # Dictionary that contains several lists of information for different genes

                a = ""  # This variable avoids the error "referenced before assignment"
                for i in range(len(result4)):  # loop to search which gene is the one that coincides with our requisites
                    if result4[i]["id"] == id_number:  # the correct information is in the list in which is our id gene
                        a = i

                # Searching the values in the selected list
                text.append("Start: " + str(result4[a]["start"]))
                text.append("End: " + str(result4[a]["end"]))
                text.append("Length: " + str(result4[a]["end"] - result4[a]["start"] + 1))  # sum also first position
                text.append("ID: " + str(result4[a]["id"]))
                text.append("Chromosome: " + str(result4[a]["seq_region_name"]))

                keyword_j_dict = a  # Using the index number of the list element that corresponds to our gene

            elif res == "/geneCalc":  # Using the resource /geneCalc

                sp = Seq(ins[1])  # Object of the species name
                text.append(sp.results())  # calling the results method
                if "json=1" in self.path:
                    text = text[0].replace("<br><br>", "<br>").rstrip("<br>").split("<br>")  # deleting intros if json=1
                keyword_j_dict = "Calculus about the gene sequence"  # Choosing this phrase as our j_dict keyword

            elif res == "/geneList":  # Using the resource /geneList

                start = ins[3]
                end = ins[5]
                ch = ins[1]
                ENDPOINT6 = "/overlap/region/human/"+ch+":"+start+"-"+end+"?content-type=application/json;feature=gene"
                result5 = client(ENDPOINT6)
                # Searching the name of each gene in the dictionary
                for index in range(len(result5)):
                    text.append(result5[index]["external_name"])

                if len(text) == 0:
                    text.append("<b>"+"There is no gene in the selected region"+"</b>")
                keyword_j_dict = "External name of the genes"

            else:
                page = "error.html"  # If it is not one of the previous resources
                keyword_j_dict = "ERROR: this is a non valid endpoint"
                code = 404  # the request is not Ok!

            # improvement in the server to avoid taking as correct an extra valid parameter. Ex: gene=FRAT1&gene=BRAF
            if res in ["/karyotype", "/chromosomeLength", "/geneSeq", "/geneInfo", "/geneCalc", "/geneList"]:
                i = 2  # we have three different instructions lengths i, j, k that will change with json = 1 parameter
                j = 4
                k = 6
                if "json=1" in self.path:
                    i += 2
                    j += 2
                    k += 2

                # checking the length of the instructions and generating a KeyError if they are not correct
                if len(ins) > i and res != "/chromosomeLength" and res != "/geneList":
                    text.append(client(ENDPOINT0)["e"])
                elif (len(ins) > j and res == "/chromosomeLength") or (len(ins) > k and res == "/geneList"):
                    text.append(client(ENDPOINT0)["e"])

        # Dealing with the main errors
        except ValueError:
            text = ["<b>"+"Incorrect value in the parameter 'limit'"+"<br>"+"Please introduce an integer number"+"</b>"]
            code = 404  # the request is not Ok!
        except TypeError:
            text = ["<b>"+"Sorry, '/listSpecies' only admits the parameter limit alone or with one json"+"</b>"]
            code = 404  # the request is not Ok!
        except KeyError:
            text = ["<b>"+"Incorrect parameters"+"<br>"+"Please review their spelling and the amount required"+"</b>"]
            code = 404  # the request is not Ok!

        # -- printing the request line
        termcolor.cprint(self.requestline, 'green')

        # Generating and sending the response message according to the request

        # -- Modification according to the request
        if "json=1" in self.path:
            h = 'application/json'  # headers content type will vary if we choose the json option
            # Fulfilling the j_dict with the assigned keywords and values
            if y == [0]:
                j_dict[keyword_j_dict] = text[0]  # if we have a list with a unique string and we just want the string
            else:
                j_dict[keyword_j_dict] = text
            contents = json.dumps(j_dict)  # Our contents will be the j_dict in a json object format
        else:
            h = 'text/html'  # If we don't choose json, the answers must be in html format
            # Opening the selected page
            f = open(page, 'r')
            contents = f.read()  # reading the contents of the selected page (main-page, error, response)

            # If the html response page is requested change the word text by the information requested
            if page == "response.html":
                information = ""  # changing our list text into a string
                for string in text:
                    information += string + "<br>"
                contents = contents.replace("text", information)

        # -- Sending the response message
        self.send_response(code)
        self.send_header('Content-Type', h)
        self.send_header('Content-Length', len(str.encode(contents)))
        self.end_headers()
        self.wfile.write(str.encode(contents))
示例#13
0
    def execute_case(cls, case_id):
        VALUES = {}  # 用户全局变量
        steps = Step.objects.filter(case=case_id).order_by("order")
        for step in steps:
            print "开始执行测试步骤:", step.name
            template = step.template
            url = template.url
            method = template.method
            t_data_str = template.data
            s_headers_str = step.headers
            s_data_str = step.data
            check_str = step.check
            headers = None
            data = None
            if s_headers_str:
                headers = {}
                for h in s_headers_str.split('&'):
                    key = h.split('=')[0]
                    value = h.split('=')[1]
                    if value.startswith('{{'):
                        value = VALUES.get(value[2:-2], None)
                    headers[key] = value

            if s_data_str and t_data_str:
                t_data = t_data_str.split('&')
                data = {}
                for d in s_data_str.split('&'):
                    key = d.split('=')[0]
                    value = d.split('=')[1]
                    if value.startswith('{{'):
                        value = VALUES.get(value[2:-2], None)
                    data[key] = value
                    if key == 'password':
                        r_str = ''.join(
                            random.sample(string.ascii_letters + string.digits,
                                          3))
                        data[key] = base64.encodestring(r_str + value)
                # 如果步骤中没有指定必填项,赋于模板中维护的默认值
                for p in t_data:
                    if p.split('=')[0] != 'sign' and p.split(
                            '=')[0] not in data.keys():
                        data[p.split('=')[0]] = p.split('=')[1]
            # 发送请求
            client = http.client(url=url,
                                 method=method,
                                 headers=headers,
                                 data=data)
            if 'sign' in t_data_str.split('&'):
                client.add_sign()
            client.send()
            # 添加检查点
            if check_str:
                check_list = json.loads(check_str).get("checks", None)
                for check in check_list:
                    try:
                        method_name = check.keys()[0]
                        paras = check[method_name]
                        CHECK_FUNC = "client.{method_name}(paras)"
                        if method_name == 'transfer':
                            VALUES[paras.get('name', None)] = client.transfer(
                                paras.get('path', None))
                        else:
                            eval(
                                CHECK_FUNC.format(method_name=method_name,
                                                  paras=paras))
                    except Exception, e:
                        assert False, '检查点函数%s执行异常:%s' % (method_name,
                                                          str(e.message))
示例#14
0
文件: run.py 项目: stavaea/hit
        check_str = case.checks
        headers = {}
        if headers_str:
            list = headers_str.split('&')
            for l in list:
                headers[l.split('=')[0]] = l.split('=')[1]
        if body_str:
            if headers.get('content-type', None) == 'application/x-www-form-urlencoded' \
                or headers.get('content-type', None) == 'multipart/form-data':
                data = {}
                list = body_str.split('&')
                for l in list:
                    data[l.split('=')[0]] = l.split('=')[1]
            else:
                data = body_str
        client = http.client(url=url, method=method, headers=headers, data=data)
        if check_str:
            list = check_str.split('&')
            for l in list:
                if l.split('=')[0] == "response_code":
                    client.check_status_code(l.split('=')[1])
                elif l.split('=')[0] == "response_time":
                    pass

if __name__ == '__main__':
    task_id = sys.argv[1]
    task_time = sys.argv[2]
    suite = unittest.defaultTestLoader.discover('./index/', pattern='run.py')
    time_str = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    fp = open('./static/report/' + time_str + '.html', 'wb')
    HTMLTestRunnerCN.HTMLTestRunner(stream=fp, title='接口自动化测试报告').run(suite)
    print(f"Response received!: {r1.status} {r1.reason}\n")
    data1 = r1.read().decode("utf-8")
    data = json.loads(data1)
    termcolor.cprint(f"CONTENT: {data}", "yellow")


options = True
while options:
    print("Client proving API rest")
    menu()
    option = int(input("Choose an option from menu: "))
    json_number = input("Enter a number for json: ")
    if option == 1:
        limit_parameter = input("Select the number of species: ")
        req = "/listSpecies?limit=" + limit_parameter
        client(req, json_number)
    elif option == 2:
        parameter = input("choose specie: ")
        req = "/karyotype?specie=" + parameter
        client(req, json_number)
    elif option == 3:
        specie_parameter = input("Choose specie: ")
        chromo_parameter = input("Choose chromosome: ")
        req = f"/chromosomeLength?specie={specie_parameter}&chromo={chromo_parameter}"
        client(req, json_number)

    elif option == 4:
        gene_parameter = input("Choose a human gene: ")
        req = "/geneSeq?gene=" + gene_parameter
        client(req, json_number)