在做 Web 开发时,经常需要构造一些测试数据,每次都手动构造数据都是非常麻烦的操作,并且效率很低。在 Python 界有一个叫 Faker 的库就是用来解决这个问题的。
Faker 简单使用
可以使用 pip 来安装 Faker:
1
pip install Faker
Faker 库使用起来非常简单,示例代码如下:
1 2 3 4 5 6 7 8
>>> from faker import Faker >>> fake = Faker() >>> fake.name() 'Emily Jones DDS' >>> fake.address() '4204 Wallace Highway Suite 512\nJohnsonborough, ME 69851' >>> fake.text() 'Mean through magazine black. Where exist deal parent.\nDifference though during too same.\nWhy result character seem car course. Seven east meeting scientist.'
>>> fake.providers [<faker.providers.user_agent.Provider object at 0x109f19d90>, <faker.providers.ssn.zh_CN.Provider object at 0x109f19b10>, <faker.providers.python.Provider object at 0x109e97c50>, <faker.providers.profile.Provider object at 0x109e97b90>, <faker.providers.phone_number.zh_CN.Provider object at 0x109e97b10>, <faker.providers.person.zh_CN.Provider object at 0x109f19b90>, <faker.providers.misc.en_US.Provider object at 0x109f007d0>, <faker.providers.lorem.zh_CN.Provider object at 0x109f006d0>, <faker.providers.job.zh_CN.Provider object at 0x109f00590>, <faker.providers.isbn.Provider object at 0x109f00750>, <faker.providers.internet.zh_CN.Provider object at 0x109f004d0>, <faker.providers.geo.en_US.Provider object at 0x109e97590>, <faker.providers.file.Provider object at 0x109e977d0>, <faker.providers.date_time.en_US.Provider object at 0x109e97690>, <faker.providers.currency.Provider object at 0x109e97490>, <faker.providers.credit_card.en_US.Provider object at 0x109e97c10>, <faker.providers.company.zh_CN.Provider object at 0x109e97350>, <faker.providers.color.en_US.Provider object at 0x109e97cd0>, <faker.providers.barcode.Provider object at 0x109e97bd0>, <faker.providers.bank.en_GB.Provider object at 0x109e7dc50>, <faker.providers.automotive.en_US.Provider object at 0x109e81c90>, <faker.providers.address.zh_CN.Provider object at 0x109e97c90>]
>>> fake.chrome(version_from=13, version_to=63, build_from=800, build_to=899) 'Mozilla/5.0 (Linux; Android 2.2.2) AppleWebKit/535.0 (KHTML, like Gecko) Chrome/36.0.846.0 Safari/535.0' >>> fake.firefox() 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_1_1 like Mac OS X) AppleWebKit/531.2 (KHTML, like Gecko) FxiOS/17.0a5677.0 Mobile/97O054 Safari/531.2' >>> fake.safari() 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_12_6 rv:2.0; am-ET) AppleWebKit/532.30.3 (KHTML, like Gecko) Version/5.0.2 Safari/532.30.3' >>> fake.internet_explorer() 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 5.01; Trident/4.0)' >>> fake.user_agent() 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/3.1)'