使用過Python語言的朋友們可能使用過 forgery_py ,它是一個偽造數(shù)據(jù)的工具。能偽造一些常用的數(shù)據(jù)。在我們開發(fā)過程和效果展示是十分有用。但是沒有Go語言版本的,所以就動手折騰吧。
從源碼入手
在forgery_py的 PyPi 有一段的實例代碼:
>>> import forgery_py
>>> forgery_py.address.street_address()
u'4358 Shopko Junction'
>>> forgery_py.basic.hex_color()
'3F0A59'
>>> forgery_py.currency.description()
u'Slovenia Tolars'
>>> forgery_py.date.date()
datetime.date(2012, 7, 27)
>>> forgery_py.internet.email_address()
u'brian@zazio.mil'
>>> forgery_py.lorem_ipsum.title()
u'Pretium nam rhoncus ultrices!'
>>> forgery_py.name.full_name()
u'Mary Peters'
>>> forgery_py.personal.language()
u'Hungarian'
從以上的方法調(diào)用我們可以看出forgery_py下有一系列的 *.py 文件,里面有各種方法,實現(xiàn)各種功能,我們在來通過分析下Python版本的forgery_py的源碼來看看它的實現(xiàn)原理。
# ForgeryPy 包的一級目錄
├── dictionaries # 偽造內(nèi)容和來源目錄,目錄下存放的都是一些文本文件
├── dictionaries_loader.py # 加載文件腳本
├── forgery # 主目錄,實現(xiàn)各種數(shù)據(jù)偽造功能,目錄下存放的都是python文件
├── __init__.py
我們在來看下forgery目錄下的腳本
$ cat name.py
import random
from ..dictionaries_loader import get_dictionary
__all__ = [
'first_name', 'last_name', 'full_name', 'male_first_name',
'female_first_name', 'company_name', 'job_title', 'job_title_suffix',
'title', 'suffix', 'location', 'industry'
]
def first_name():
"""Random male of female first name."""
_dict = get_dictionary('male_first_names')
_dict += get_dictionary('female_first_names')
return random.choice(_dict).strip()
__all__ 設置能被調(diào)用的方法。
first_name() 方法是forgery_py中一個典型偽造數(shù)據(jù)方法,我們只要來分析它就可以知道forgery_py的工作原理了。
這個方法代碼很少,能容易就看出 _dict = get_dictionary('male_first_names')
和 _dict += get_dictionary('female_first_names')
獲取的數(shù)據(jù)合并,在最后的 return random.choice(_dict).strip(
) 返回隨機的數(shù)據(jù)。它的重點在于 get_dictionary()
,所以我們需要來看它的所在位置 dictionaries_loader.py 文件。
$ cat dictionaries_loader
import random
DICTIONARIES_PATH = abspath(join(dirname(__file__), 'dictionaries'))
dictionaries_cache = {}
def get_dictionary(dict_name):
"""
Load a dictionary file ``dict_name`` (if it's not cached) and return its
contents as an array of strings.
"""
global dictionaries_cache
if dict_name not in dictionaries_cache:
try:
dictionary_file = codecs.open(
join(DICTIONARIES_PATH, dict_name), 'r', 'utf-8'
)
except IOError:
None
else:
dictionaries_cache[dict_name] = dictionary_file.readlines()
dictionary_file.close()
return dictionaries_cache[dict_name]
以上就是 dictionaries_loader.py 文件去掉注釋后的所以要內(nèi)容。它的主要實現(xiàn)就是:定義一個全局的字典參數(shù) dictionaries_cache 作為緩存,然后定義方法 get_dictionary() 獲取源數(shù)據(jù), get_dictionary() 中每次forgery目錄底下方法調(diào)用時先查看緩存,緩存字典中存在數(shù)據(jù)就直接輸出,不存在就讀取 dictionaries 底下的對應文件,并存入緩存。最后是返回數(shù)據(jù)。
總的來說forgery_py的原理就是:一個方法調(diào)用,去讀內(nèi)存中的緩存,存在就直接返回,不存在就到對應的文本文件中讀取并寫入緩存并返回。返回來的數(shù)據(jù)再隨機選取輸出結(jié)果。
使用Go語言實現(xiàn)
在了解了forgery_py的工作原理之后,我們就可以來使用Go語言來實現(xiàn)了。
# forgery的基本目錄
$ cat forgery
├── dictionaries # 數(shù)據(jù)源
│ ├── male_first_names
├── name.go # 具體功能實現(xiàn)
└── loader.go # 加載數(shù)據(jù)
根據(jù)python版本的我們也來創(chuàng)建對應的目錄。
實現(xiàn)數(shù)據(jù)的讀取的緩存:
// forgery/loader.go
package forgery
import (
"os"
"io"
"bufio"
"math/rand"
"time"
"strings"
)
// 全局的緩存map
var dictionaries map[string][]string = make(map[string][]string)
// 在獲取數(shù)據(jù)之后隨機輸出
func random(slice []string) string {
rand.Seed(time.Now().UnixNano())
n := rand.Intn(len(slice))
return strings.TrimSpace(slice[n])
}
// 主要的數(shù)據(jù)加載方法
func loader(name string) (slice []string, err error) {
slice, ok := dictionaries[name]
// 緩存中存在數(shù)據(jù),直接返回
if ok {
return slice, nil
}
// 讀取對應文件
file, err := os.Open("./dictionaries/" + name)
if err != nil {
return slice, err
}
defer file.Close()
rd := bufio.NewReader(file)
for {
line, err := rd.ReadString('\n')
slice = append(slice, line)
if err != nil || io.EOF == err {
break
}
}
dictionaries[name] = slice
return slice, nil
}
// 統(tǒng)一的錯誤處理
func checkErr(err error) (string, error) {
return "", err
}
實現(xiàn)具體的功能:
// forgery/name.go
// Random male of female first name.
func FirstName() (string, error) {
slice, err := loader("male_first_names")
checkErr(err)
slice1, err := loader("female_first_names")
checkErr(err)
slice = append(slice, slice1...)
return random(slice), nil
}
這樣就將python語言版本的forgery_py使用Go來實現(xiàn)了。
最后
上面只是提及了一些工作原理,具體的源代碼可以看 https://github.com/xingyys/fo... ,也十分感謝 https://github.com/tomekwojci... ,具體的思路和里面的數(shù)據(jù)源都是他提供的。本人就是做了一些 翻譯 的的工作。
總結(jié)
以上所述是小編給大家介紹的Go語言版本的forgery,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!