Python: Basic use of module--faker for randomly generated test data

Source: Internet
Author: User
Tags generator locale

The content of this article:

    1. Introduction of Faker
    2. Use of Faker
    3. Small example: Generate random data table information

Starting Date: 2018-06-15

Faker Introduction:

    • Faker is a third-party module of Python and is an open source project on GitHub.
    • Used primarily to create some random data for testing purposes.

Official Document: Https://faker.readthedocs.io/en/master/index.html

Use of Faker:

1. Installing the module
PIP3 Install Faker

"The use of Faker can also identify success, but the new version has been updated to Faker"

2. Import the module
 from Import Faker

"The main use is the factory class, and import Faker, will import factory"

3. Steps to use:

    • 3.1 Initialization:
      Fake=faker ()
      • Faker () calls the Create method of the factory, common parameter options:
        • Used to generate localized data: Locale "is en_us by default, so the generated data is American English"
          • ZH-CN representative uses the Chinese version
          • For more country versions, you can refer to Https://faker.readthedocs.io/en/master/index.html#localization
        • Providers is a "provider" that contains a number of generators that generate random data, such as a generator that produces random names, and a generator that contains random addresses. If we want to define the rules for the randomly generated data, then we need to customize the providers. How to generate a providers, you can refer to Https://faker.readthedocs.io/en/master/index.html#how-to-create-a-provider
    • 3.2. Call Method:
      • Using the Faker object call method, the return value of the calling method is random data.
      • Different data needs to call different methods, see below for common methods.

 fromFakerImportFaker#fake=faker () #默认生成美国英文数据Fake=faker (locale='ZH_CN')#Address classPrint("Address class". Center (20,"-"))Print(Fake.address ())#Hainan Province Cheng City Fengdou Shenzhen Road p block 425541Print(Fake.street_address ())#block X, Shenzhen StreetPrint(Fake.street_name ())#Changsha RoadPrint(Fake.city_name (), fake.city ())#Lanzhou Guiyang (difference "City")Print(Fake.province ())#Shaanxi Province#Company class:Print("Company Class". Center (20,"-"))Print(Fake.company ())#Hui Send International Company Information Co., Ltd.Print(Fake.company_suffix ())#Network Co., Ltd.Print(Fake.company_prefix ())#xin Bo Tengfei#Personal Information CategoryPrint("Personal Information Category". Center (20,"-"))Print(Fake.name ())#DonghaoPrint(Fake.simple_profile ())#{' username ': ' Leihan ', ' name ': ' Wu Shuai ', ' sex ': ' F ', ' address ': ' Block C, Huaian Shuangluan House, Jilin Province 210434 ', ' Mail ': ' [email protected] ', ' birth Date ': ' 1988-11-12 '}Print(Fake.user_name (), Fake.password (Special_chars=false))#Ajiang zi2qbhy02p#Article ClassPrint("Article Class". Center (20,"-"))Print(Fake.word ())#CurrentPrint(Fake.words (3))#[' Welcome ', ' support ', ' pictures ']Print(Fake.sentence (3))#essence about some.Print(Fake.paragraph ())#everyone in the telephone space to work with the picture requirements. Shanghai has developed into a user as well as a person. Must be a journalist relationship registration. User Time investment release.

Common methods:

Https://faker.readthedocs.io/en/master/locales/zh_CN.html as the main use of Chinese data, so provide a common method example is Chinese. If you want to know anything else, you can click on other languages in the official network and refer to the sample results, but the methods are basically the same.

Address Information class:
    • Fake.address (): Full address, such as Hainan Province Cheng City Fengdou Shenzhen road block P 425541
    • Fake.street_address (): Street + address, for example, Xingcheng Road, Block a
    • Fake.street_name (): Street name, such as Yidou Street
    • Fake.city_name (): City name, such as Lanzhou
    • Fake.city (): Cities, such as Lanzhou City
    • Fake.province (): province name, such as Shaanxi
    • Fake.postcode (): Zip code
    • Fake.country (): Country

Company Information Category:
    • Fake.company (): company name, such as Hui Pi International Company Information Co., Ltd.
    • Fake.company_suffix (): Company name suffix (company nature), such as Network Co., Ltd.
    • Fake.company_prefix (): Company name prefix, such as Xin Bo Tengfei
Date class:
    • Fake.date (pattern= "%y-%m-%d", End_datetime=none)
    • Fake.year (): Random year
    • Fake.day_of_week (): Random number of weeks
    • Fake.time (pattern= "%h:%m:%s", End_datetime=none): Random Time
Network class:
    • Fake.company_email (): Enterprise mailbox
    • Fake.email (): Mailbox
Personal Information Category:
    • Fake.name (): Name

    • Fake.user_name (*args, **kwargs): username, just a random combination of English names, typically 6-bit
    • Fake.phone_number (): Phone number
    • Fake.simple_profile (Sex=none): Brief personal information, including user name, name, gender, address, email, date of birth. For example {' username ': ' Chao ', ' name ': ' Hu Shulan ', ' sex ': ' M ', ' address ': ' Shawan Ningde Road in Ningxia Hui Autonomous Region ' t block 873713 ', ' Mail ': ' [email protected] ', ' Birt Hdate ': ' 1998-06-12 '}
    • Fake.profile (Fields=none, Sex=none): Detailed slightly personal information, more than a brief personal information about the company name, blood type, work, location, domain name and so on.
    • Fake.password (): Password
      • Parameter options: Length: Password size, Special_chars: Whether special characters can be used, digits: whether it contains a number, Upper_case: Whether it contains uppercase letters, Lower_case: Whether it contains a lowercase letter.
      • Default: length=10, Special_chars=true, Digits=true, Upper_case=true, lower_case=true
    • Fake.job (): Work

Article class:
    • Fake.word (Ext_word_list=none): Random words
      • Ext_word_list can be a list, then words are taken from the list
    • Fake.words (Nb=3, Ext_word_list=none): random multiple words
      • NB is the number of words for words to return how many
    • Fake.sentence (nb_words=6, Variable_nb_words=true, Ext_word_list=none): Random phrase (will include phrase end marker dot)
    • Fake.paragraph (nb_sentences=3, Variable_nb_sentences=true, Ext_word_list=none): Random Paragraph
    • Fake.paragraphs (Nb=3, Ext_word_list=none): multiple random paragraphs

Data type class:
    • Fake.pystr (Min_chars=none, max_chars=20): Random string of custom lengths
    • Fake.pyint (): Random integer
PS:
想了解Faker的更多用法,可以参考官方文档:https://faker.readthedocs.io/en/master/index.html
Small example: Generate random data table information

Note: For example, it is easy to use "imperative" for database operation, instead of using ORM model.

Implementation process:
    1. Connecting Databases with Pymysql
    2. Create a table
    3. Format the data to be inserted using fake
    4. Executing an INSERT statement with Pymysql

Code:
ImportPymysql fromFakerImportFakerconn=pymysql.connect (host="localhost", port=3306,user="Root", password="123456", db="it", charset="UTF8") Cursor=conn.cursor ()#This gives the table structure, and if you use a table that already exists, you can not create the table. Sql="""CREATE TABLE user (id int PRIMARY KEY auto_increment,username varchar, password varchar, address varchar (35)) /c6>"""cursor.execute (SQL) fake=faker ("ZH-CN") forIinchRange (20): SQL="""INSERT INTO User (username,password,address) VALUES ('%s ', '%s ', '%s ')"""        % (Fake.user_name (), Fake.password (special_chars=False), fake.address ()) cursor.execute (SQL) Conn.commit () Cursor.close () conn.close ()

Results:

Python: Basic use of module--faker for randomly generated test data

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.