【问题标题】:converting a python script into object oriented program将python脚本转换为面向对象的程序
【发布时间】:2018-11-16 21:54:14
【问题描述】:

您好,我是一名半自学的学生,希望提高自己的技能,使用不同的 API 在 Python 上编写了几个脚本。我想在某个时候将此脚本用作我的一个更大项目中的一个模块。我有想法将这个脚本转换为更面向对象的程序类型的编程。可以从其他文件调用的类和函数。我开始创建类和函数,但不认为我的做法是正确的我将不胜感激,第一行是我开始转换为 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 = "https://vulners.com/api/v3/search/lucene/"

# 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 chosed software heres the questions asked to build the full url
if inp == "software":
    myqueryName = input("What would you like to search? ")
    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=affectedSoftware.name%3A{}&sort={}&size={}&skip={}".format(URL, myqueryName, sortedHow, numberResults, numberSkipped)
# if chosed bulletin heres the questions asked to build the full url
if 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)

# making the request and converting the json
resp = requests.get(new_url)
resp.raise_for_status()
json_string=json.dumps(resp.text)
mydata=json.loads(resp.text)
# to see the url
print(resp.url)
print("-"*30)


# loop to go through nested dictionnary returned by the requests
mydata2 = mydata['data']
for mydata3 in mydata2['search']:
#     mydata4 = mydata3['_source']
#     mydata5 = mydata3['highlight']
    for mydata4 in mydata['data']:
        print("Title: {}".format(mydata3['_source']['title']))
        print("Index: {}".format(mydata3['_index']))
        print("Type: {}".format(mydata3['_type']))
        print("Id: {}".format(mydata3['_id']))
        print("Type: {}".format(mydata3['_source']['type']))
        print("Cvss: {}".format(mydata3['_source']['cvss']))
        print("Flat description: {}".format(mydata3['flatDescription']))
        print("Bulletin family: {}".format(mydata3['_source']['bulletinFamily']))
        print("Description: {}".format(mydata3['_source']['description']))
        print("Vhref: {}".format(mydata3['_source']['vhref']))
        print("Href: {}".format(mydata3['_source']['href']))
        print("Id: {}".format(mydata3['_source']['id']))
        print("Lastseen: {}".format(mydata3['_source']['lastseen']))
        print("Modified: {}".format(mydata3['_source']['modified']))
        print("Published: {}".format(mydata3['_source']['published']))
        print("-"*30)
    # saving the data locally inside a json file
        with open('testfile2.json', 'w') as fd:
            print(json.dump(resp.text, fd, indent=2))
            fd.write(resp.text)

【问题讨论】:

  • 注意class vulnersApi(object):的代码没有正确缩进

标签: python oop procedural


【解决方案1】:

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

有几点我想先说明:

  • 你不需要你的代码是面向对象的以便在其他地方重用它,只需将所有有用的函数放在一个 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())

第一步是抽象出处理用户输入的所有代码,以使库与各种用例兼容。第二步是考虑应该属于自己的类别的不同实体。我选择了VulnersResultVulnersAPI,因为我认为将它们作为单独的实体是有意义的,并且您可以稍后添加有趣的功能。 (类似于to_table_row()is_affecting_my_system() 用于VulnersResultfilter_by_type()sort_by_lastseen() 用于VulnersAPI)。在第三步中,您必须决定每个类应该具有哪些属性。属性应该是在多个函数中使用的变量或类的用户应该有权访问的变量。比如我没有添加search_typequery作为VulnersAPI的属性,因为它们只用于生成url,但如果有人使用这些值,它们应该作为属性存储。

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

我希望这个示例以及到达那里的步骤对您有所帮助,并使您能够解决您的大问题:)

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

如果您正在使用最新版本的 python 进行编程,您可以使用f-strings 使字符串格式化更好。

【讨论】:

  • 我没想到会这样,我想我会很头疼,我真的认为一个类和多个功能就足够了,我会更深入地重新阅读所有内容,我是现在在公共汽车上,所以现在是阅读所有这些内容的最佳时机,稍后我将测试代码,感谢您的资源,我肯定会阅读 Python 的样式指南 我认为它对我有很大帮助,我阅读了以前学过Python的禅,但是我觉得是时候背诵它了哈,没想到这么快就有答案了,我迫不及待地想在家里跳一次非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-03
  • 1970-01-01
相关资源
最近更新 更多