In the early stage of project development, for the convenience of testing, we always create a lot of fake data into the system to try to simulate the real environment.
Like creating a bunch of users, creating a piece of text, or a phone number, or a street address, or an IP address, and so on.
It used to be a lot of typing, making up random strings, and of course no one knew anyone.
Now you don’t have to do that.
You can do everything you need with faker.
Install faker first
pip install Faker
Copy the code
Create the Faker object
from faker import Faker
fake = Faker()
Copy the code
Fake a name
>>> fake.name()
'Joshua Reed'
Copy the code
Fake an address
>>> fake.address()
'554 Hoffman Locks Suite 216\nElizabethstad, RI 23081'
Copy the code
Fake is a browser UA
>>> fake.chrome()
'the Mozilla / 5.0 (X11; Linux i686) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/35.0.870.0 Safari/532.0'
Copy the code
Fake a date
>>> fake.date()
'1984-08-17'
>>> fake.date_object()
datetime.date(1980.9.27)
Copy the code
But it can fake anything you need. If you don’t know what fake can be, check out dir(fake).
It can fake nearly 300 items, and if there’s more you can’t meet, you can submit a PR to Github or extend it yourself
All the fake items, such as names and streets, are in English. Does he support Chinese?
Can the
Just specify the language when creating the Faker object
>>> fake = Faker("zh_CN")
>>> fake.name()
'ZhuangYang'
>>> fake.address()
'285123, Block I, New Beijing Street, Shenbei, Taipei county, Zhejiang Province'
>>> fake.phone_number()
'13223924289'
Copy the code
You’ll find that fake data is actually true. In addition to Chinese, it also supports Japanese, Korean, German and hundreds of other languages
Of course, it also supports command-line mode
-h View help documents
faker [-h] [--version] [-o output]
[-l {bg_BG,cs_CZ,...,zh_CN,zh_TW}]
[-r REPEAT] [-s SEP]
[-i {package.containing.custom_provider otherpkg.containing.custom_provider}]
[fake] [fake argument [fake argument ...]]
C:\Users\lzjun\workspace\>faker name
Samantha Washington
Copy the code
Can I create my own fake data? Let’s say I want to randomly generate a user-agent based on Android devices
from faker import Faker
fake = Faker()
from faker.providers import BaseProvider
# Create a custom provider
class MyProvider(BaseProvider):
def android_ua(self):
return 'xxxxxx'
# Add a provider
fake.add_provider(MyProvider)
>>>fake.android_ua()
>>>'xxxxxx'
Copy the code
Is it too simple? In addition, Faker is a very good source code library to study.
This article is published on the public account: Zen of Python, welcome to follow