溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Go語言版本的forgery有什么用

發(fā)布時間:2021-06-24 09:46:23 來源:億速云 閱讀:167 作者:小新 欄目:編程語言

這篇文章主要介紹了Go語言版本的forgery有什么用,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

使用過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__ 設(shè)置能被調(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 底下的對應(yīng)文件,并存入緩存。最后是返回數(shù)據(jù)。

總的來說forgery_py的原理就是:一個方法調(diào)用,去讀內(nèi)存中的緩存,存在就直接返回,不存在就到對應(yīng)的文本文件中讀取并寫入緩存并返回。返回來的數(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)建對應(yī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
  }
  // 讀取對應(yīng)文件
  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)了。

感謝你能夠認真閱讀完這篇文章,希望小編分享的“Go語言版本的forgery有什么用”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI