Using Faker to generate events
Faker¶
A quick introduction to Faker.
Installation¶
In [1]:
%%sh
pip install Faker
Initialization¶
In [2]:
from faker import Faker
faker = Faker()
Implementation¶
Create a random integer:
In [3]:
faker.random_int(min=1, max=8, step=1)
Out[3]:
Run it a second time and it might give another integer:
In [4]:
faker.random_int(min=1, max=8, step=1)
Out[4]:
Or we can define a list with some elements and create random element with Faker:
In [5]:
characters = ["Mario", "Luigi", "Peach", "Toad"]
faker.random_element(characters)
Out[5]:
In [6]:
faker.random_element(characters)
Out[6]:
Additionally, we can create a date between a start and end date, i.e. the last month:
In [7]:
import datetime
from dateutil.relativedelta import relativedelta
date_end = datetime.datetime.now()
date_start = date_end + relativedelta(months=-1)
In [8]:
faker.date_between_dates(date_start=date_start, date_end=date_end)
Out[8]:
In [9]:
faker.date_between_dates(date_start=date_start, date_end=date_end)
Out[9]:
Event generator¶
Let's put this together to make an event generator that can be used to create fake data for any other project.
In [10]:
import json
CHARACTERS = ["Mario", "Luigi", "Peach", "Toad"]
DATE_END = datetime.datetime.now()
DATE_START = DATE_END + relativedelta(months=-1)
MAX_LIVES = 100
MIN_LIVES = 1
NUM_EVENTS = 2
def _generate_events():
""" Generate the metric data """
for _ in range(NUM_EVENTS):
yield {
"character": faker.random_element(CHARACTERS),
"lives": faker.random_int(min=MIN_LIVES, max=MAX_LIVES, step=1),
"time": str(faker.date_between_dates(DATE_START, DATE_END)),
}
print(json.dumps(list(_generate_events()), indent=2))
C'est tout! Please use this wiseley.