Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将python脚本转换为面向对象程序_Python_Oop_Procedural - Fatal编程技术网

将python脚本转换为面向对象程序

将python脚本转换为面向对象程序,python,oop,procedural,Python,Oop,Procedural,您好,我是一名半自学的学生,希望提高我的技能,使用不同的API在Python上编写了一些脚本。我想在某个时候使用这个脚本作为我的一个更大项目的一个模块。我的想法是将此脚本转换为一种更面向对象的编程类型。可以从其他文件调用类和函数。我开始创建类和函数,但不认为我做的是正确的,我现在在打印的部分,不知道如何以正确的方式将脚本转换为OOP,如果有任何提示或任何东西可以指导我以正确的方式进行操作,我将不胜感激,第一行是我开始转换为OOP的内容 该脚本运行良好,它基本上提出了一个问题,并根据用户的输入构建

您好,我是一名半自学的学生,希望提高我的技能,使用不同的API在Python上编写了一些脚本。我想在某个时候使用这个脚本作为我的一个更大项目的一个模块。我的想法是将此脚本转换为一种更面向对象的编程类型。可以从其他文件调用类和函数。我开始创建类和函数,但不认为我做的是正确的,我现在在打印的部分,不知道如何以正确的方式将脚本转换为OOP,如果有任何提示或任何东西可以指导我以正确的方式进行操作,我将不胜感激,第一行是我开始转换为OOP的内容

该脚本运行良好,它基本上提出了一个问题,并根据用户的输入构建url向Vulners网站发出请求,然后循环嵌套的词汇表并打印出我感兴趣的键和值,它还将数据本地保存到json文件中,目前还没有真正的用处。任何提示都值得赞赏

class vulnersApi(object):
    def type_of_search(self, software, bulletin, inp):
        self.bulletin = software
        self.collection = bulletin
        self.inp = inp

        while inp != "software" and inp!= "bulletin":
            inp = input("You must choose your type of research(software or bulletin: ")
            if inp != "software" and inp != "bulletin":
                return "You must choose your type of research"

    def search_software(self, myqueryName, sortedHow, numberResults, numberSkipped):
        self.myqueryName = myqueryName
        self.sortedHow = sortedHow
        self.numberResults = numberResults
        self.numberSkipped = numberSkipped

        if self.inp == "software":
            myqueryName = input("What would you like to search? ")
            sortedHow = input("How should we sort the results? (published, cvss.score) ")
            sortedHow = input("How should we sort the results? (published, cvss.score) ")
            numberSkipped = input("How many results do you want to skip? ")
            new_url = "{}?query=affectedSoftware.name%3A{}&sort={}&size={}&skip={}".format(URL, myqueryName, sortedHow, numberResults, numberSkipped)

    def search_bulletin(self, typeSearch, sortedHow, numberResults, numberSkipped):
        self.typeSearch = typeSearch
        self.sortedHow = sortedHow
        self.numberResults = numberResults
        self.numberSkipped = numberSkipped

        if self.inp == "bulletin":
            typeSearch = input("Which db you want the info from? (cve, exploitdb, osvdb, openvas, securityvulns, nessus, metasploit, centos, malwarebytes, symantec, etc...) ")
            sortedHow = input("How should we sort the results? (published, cvss.score) ")
            numberResults = input("How many results? ")
            numberSkipped = input("How many results do you want to skip? ")
            new_url = "{}?query=type%3A{}&sort={}&size={}&skip={}".format(URL, typeSearch, sortedHow, numberResults, numberSkipped)

    def url_request(self):
        response = requests.get(new_url)
        response.raise_for_status()
        json_string = json.dumps(response.text)
        mydata = json.loads(response.text)
剧本如下

# base url
URL=“”

我想在某个时候使用这个脚本作为我的一个更大项目的一个模块。我的想法是将此脚本转换为一种更面向对象的编程类型。可以从其他文件调用类和函数

我首先要注意以下几点:

  • 为了在其他地方重用代码,您不需要将代码面向对象,只需将所有有用的函数放在一个python文件中,然后将其导入其他地方即可
  • 只有重构能够利用OOP优势的代码才有意义(比如具有不同值但共享函数的多个实例)
我尝试过重构您的代码:

import requests
import json

class VulnersResult:
    def __init__(self, json_data):
        self.title = json_data['_source']['title']
        self.type = json_data['_type']
        self.id = json_data['_id']
        self.source_type = json_data['_source']['type']
        self.cvss = json_data['_source']['cvss']
        self.flat_description = json_data['flatDescription']
        self.bulletin_family = json_data['_source']['bulletinFamily']
        self.description = json_data['_source']['description']
        self.vhref = json_data['_source']['vhref']
        self.href = json_data['_source']['href']
        self.source_id = json_data['_source']['id']
        self.lastseen = json_data['_source']['lastseen']
        self.modified = json_data['_source']['modified']
        self.published = json_data['_source']['published']
    def __str__(self):
        lines = ["Title: {}".format(self.title),
                 "Type: {}".format(self.type),
                 "Id: {}".format(self.id),
                 "Type: {}".format(self.source_type),
                 "Cvss: {}".format(self.cvss),
                 "Flat description: {}".format(self.flat_description),
                 "Bulletin family: {}".format(self.bulletin_family),
                 "Description: {}".format(self.description),
                 "Vhref: {}".format(self.vhref),
                 "Href: {}".format(self.href),
                 "Id: {}".format(self.source_id),
                 "Lastseen: {}".format(self.lastseen),
                 "Modified: {}".format(self.modified),
                 "Published: {}".format(self.published)]
        return "\n".join(lines)

class VulnersAPI:
    BASE_URL = "https://vulners.com/api/v3/search/lucene/"
    def __init__(self, research_type, query, sorted_by, results_count, skip_count):
        if research_type == "software":
            self.query_url = "{}?query=affectedSoftware.name%3A{}&sort={}&size={}&skip={}".format(self.BASE_URL, query, sorted_by, results_count, skip_count)
        elif research_type == "bulletin":
            self.query_url = "{}?query=type%3A{}&sort={}&size={}&skip={}".format(self.BASE_URL, query, sorted_by, results_count, skip_count)
        else:
            raise RuntimeError("{} is not a valid research type. research_type must be 'software' or 'bulletin'".format(research_type))
        response = requests.get(self.query_url)
        response.raise_for_status()
        self.raw_data = response.json()
        self.results = [VulnersResult(data) for data in self.raw_data['data']['search']]
    def result_text(self):
        return ("\n"+("-"*30)+"\n").join([str(result) for result in self.results])

if __name__ == "__main__":
    # choose between 2 types of research
    inp = ""
    while inp != "software" and inp != "bulletin" and inp !="collection":
        inp = input("You must chose your type of research(software or bulletin): ")
        if inp != "software" and inp != "bulletin" and inp !="collection":
            print("you must chose your type of research")

    print("-"*30)
    if inp == "software":
        # if "software" was chosen, ask these additional questions
        query = input("What would you like to search? ")
        sorted_by = input("How should we sort the results? (published, cvss.score) ")
        results_count = input("How many results? ")
        skip_count = input("How many results do you want to skip? ")
        api = VulnersAPI("software", query, sorted_by, results_count, skip_count)
    if inp == "bulletin":
        # if "bulletin" was chosen, ask these additional questions
        query = input("Which db you want the info from? (cve, exploitdb, osvdb, openvas, securityvulns, nessus, metasploit, centos, malwarebytes, symantec, etc...) ")
        sorted_by = input("How should we sort the results? (published, cvss.score) ")
        results_count = input("How many results? ")
        skip_count = input("How many results do you want to skip? ")
        api = VulnersAPI("software", query, sorted_by, results_count, skip_count)
    print()

    with open('testfile2.json', 'w') as fd:
        json.dump(api.raw_data, fd)

    print(api.result_text())
第一步是抽象掉任何处理用户输入的代码,使库与各种用例兼容。第二步是思考不同的实体应该拥有自己的类别。我选择了
VulnersResult
VulnersAPI
,因为我认为将它们作为单独的实体是有意义的,而且您可以在以后添加有趣的函数。(类似于
to_table_row()
的内容正在影响
vulnersesult
filter_by_type()
sort_by_lastseen()
对于
VulnersAPI
)。在第三步中,您必须决定每个类应该具有哪些属性。属性应该是在多个函数中使用的变量,或者是类的用户应该有权访问的变量。例如,我没有将
search\u type
query
添加为
VulnersAPI
的属性,因为它们仅用于生成url,但如果有人使用这些值,则应将其存储为属性

为了像当前一样使用python脚本,并向库的用户提供示例代码,我在
之后添加了处理用户输入的原始代码,如果
中的
。当您直接启动脚本时,它会像现在一样要求用户输入,但当您导入脚本时,脚本会忽略最后一部分,只导入
VulnerResult
VulnerAPI
的定义

我希望这个例子以及实现这一目标的步骤对您有所帮助,并使您能够解决您的大问题:)

最后,这里是一些我认为每个python程序员都应该阅读的资源


如果您使用最新版本的python编程,您可以使用它来改进字符串格式。

注意
类vulnersApi(object):
的代码没有正确的标识。我没想到会这样,我想我会大吃一惊,我真的认为一个类和多个函数就足够了,我会更深入地阅读所有内容,我现在在车上,所以这是阅读所有这些内容的最佳时机,我稍后将测试代码,感谢您提供的资源,我当然会阅读Python的样式指南,我认为这对我有很大帮助,我以前读过Python的禅宗,但我认为是时候把它背下来了哈,我没想到会这么快得到答复,我迫不及待地想在家里马上回答。谢谢
import requests
import json

class VulnersResult:
    def __init__(self, json_data):
        self.title = json_data['_source']['title']
        self.type = json_data['_type']
        self.id = json_data['_id']
        self.source_type = json_data['_source']['type']
        self.cvss = json_data['_source']['cvss']
        self.flat_description = json_data['flatDescription']
        self.bulletin_family = json_data['_source']['bulletinFamily']
        self.description = json_data['_source']['description']
        self.vhref = json_data['_source']['vhref']
        self.href = json_data['_source']['href']
        self.source_id = json_data['_source']['id']
        self.lastseen = json_data['_source']['lastseen']
        self.modified = json_data['_source']['modified']
        self.published = json_data['_source']['published']
    def __str__(self):
        lines = ["Title: {}".format(self.title),
                 "Type: {}".format(self.type),
                 "Id: {}".format(self.id),
                 "Type: {}".format(self.source_type),
                 "Cvss: {}".format(self.cvss),
                 "Flat description: {}".format(self.flat_description),
                 "Bulletin family: {}".format(self.bulletin_family),
                 "Description: {}".format(self.description),
                 "Vhref: {}".format(self.vhref),
                 "Href: {}".format(self.href),
                 "Id: {}".format(self.source_id),
                 "Lastseen: {}".format(self.lastseen),
                 "Modified: {}".format(self.modified),
                 "Published: {}".format(self.published)]
        return "\n".join(lines)

class VulnersAPI:
    BASE_URL = "https://vulners.com/api/v3/search/lucene/"
    def __init__(self, research_type, query, sorted_by, results_count, skip_count):
        if research_type == "software":
            self.query_url = "{}?query=affectedSoftware.name%3A{}&sort={}&size={}&skip={}".format(self.BASE_URL, query, sorted_by, results_count, skip_count)
        elif research_type == "bulletin":
            self.query_url = "{}?query=type%3A{}&sort={}&size={}&skip={}".format(self.BASE_URL, query, sorted_by, results_count, skip_count)
        else:
            raise RuntimeError("{} is not a valid research type. research_type must be 'software' or 'bulletin'".format(research_type))
        response = requests.get(self.query_url)
        response.raise_for_status()
        self.raw_data = response.json()
        self.results = [VulnersResult(data) for data in self.raw_data['data']['search']]
    def result_text(self):
        return ("\n"+("-"*30)+"\n").join([str(result) for result in self.results])

if __name__ == "__main__":
    # choose between 2 types of research
    inp = ""
    while inp != "software" and inp != "bulletin" and inp !="collection":
        inp = input("You must chose your type of research(software or bulletin): ")
        if inp != "software" and inp != "bulletin" and inp !="collection":
            print("you must chose your type of research")

    print("-"*30)
    if inp == "software":
        # if "software" was chosen, ask these additional questions
        query = input("What would you like to search? ")
        sorted_by = input("How should we sort the results? (published, cvss.score) ")
        results_count = input("How many results? ")
        skip_count = input("How many results do you want to skip? ")
        api = VulnersAPI("software", query, sorted_by, results_count, skip_count)
    if inp == "bulletin":
        # if "bulletin" was chosen, ask these additional questions
        query = input("Which db you want the info from? (cve, exploitdb, osvdb, openvas, securityvulns, nessus, metasploit, centos, malwarebytes, symantec, etc...) ")
        sorted_by = input("How should we sort the results? (published, cvss.score) ")
        results_count = input("How many results? ")
        skip_count = input("How many results do you want to skip? ")
        api = VulnersAPI("software", query, sorted_by, results_count, skip_count)
    print()

    with open('testfile2.json', 'w') as fd:
        json.dump(api.raw_data, fd)

    print(api.result_text())