### Efficiently Create Mimesis Data Providers with Generic (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/quickstart.rst This example demonstrates the efficient way to create Mimesis data providers using the Generic class. Instead of importing and instantiating each provider individually, Generic provides access to all providers through a single object, reducing boilerplate code. It shows accessing person and datetime data. ```python from mimesis import Generic from mimesis.locales import Locale generic = Generic(locale=Locale.EN) generic.person.username() # Output: 'sherley3354' generic.datetime.date() # Output: '14-05-2007' ``` -------------------------------- ### Importing Individual Mimesis Providers (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/quickstart.rst This snippet illustrates importing individual Mimesis providers, such as Person, when only specific data types are needed. It shows creating separate Person instances for different locales (English and Swedish) to demonstrate localized data generation. ```python from mimesis import Person from mimesis.locales import Locale p_en = Person(Locale.EN) p_sv = Person(Locale.SV) ``` -------------------------------- ### Install Mimesis using pip Source: https://github.com/lk-geimfari/mimesis/blob/master/README.md This command installs the Mimesis library using pip, the Python package installer. Ensure you have pip installed and configured correctly. ```bash ~ pip install mimesis ``` -------------------------------- ### Generate Person Data with Mimesis (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/quickstart.rst This snippet shows how to import the Person provider, set the locale to English, and generate random full names for both female and male genders. It utilizes the Locale enum for specifying the language and the Gender enum for specifying the gender. ```python from mimesis import Person from mimesis.locales import Locale from mimesis.enums import Gender person = Person(Locale.EN) person.full_name(gender=Gender.FEMALE) # Output: 'Antonetta Garrison' person.full_name(gender=Gender.MALE) # Output: 'Jordon Hall' ``` -------------------------------- ### Instantiate Providers with Specific Locales Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/locales.rst This example shows how to create instances of Mimesis providers (like Address) and specify a locale (e.g., German or Russian) during instantiation. This ensures that the generated data is appropriate for the chosen locale. ```python from mimesis import Address from mimesis.locales import Locale de = Address(locale=Locale.DE) ru = Address(locale=Locale.RU) de.region() # Output: 'Brandenburg' ru.federal_subject() # Output: 'Алтайский край' de.address() # Output: 'Mainzer Landstraße 912' ru.address() # Output: 'ул. Пехотная 125' ``` -------------------------------- ### Install Mimesis with factory extra Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/factory_plugin.rst This command installs Mimesis along with the 'factory' extra, which includes factory_boy. This is an alternative way to ensure factory_boy is available when using Mimesis for data generation. ```bash poetry add --group dev mimesis[factory] ``` -------------------------------- ### JSON Data Format for Custom Providers Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/providers.rst This JSON example shows the expected format for data files used by custom providers. It demonstrates a simple key-value structure where the value is a list of strings. ```json { "key": [ "value1", "value2", "value3" ] } ``` -------------------------------- ### Overriding Locale for Mimesis Provider (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/quickstart.rst This example demonstrates how to temporarily override the locale for a Mimesis provider using a context manager. The `override_locale` method allows changing the locale for a specific block of code, ensuring that subsequent operations within that block use the new locale. ```python from mimesis import Person person = Person(Locale.EN) with person.override_locale(Locale.SV): pass ``` -------------------------------- ### Install factory_boy with Poetry Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/factory_plugin.rst This command installs the factory_boy package as a development dependency using Poetry. It's a common way to manage testing-related packages in a Python project. ```bash poetry add --group dev factory_boy ``` -------------------------------- ### Utilize Generic Provider for Mimesis Data Generation in Python Source: https://context7.com/lk-geimfari/mimesis/llms.txt This example shows how to use the Generic provider in Mimesis, which aggregates all other providers into a single object. This allows for consistent locale and seed usage across different data types like person names, addresses, dates, URLs, and more. ```python from mimesis import Generic from mimesis.locales import Locale g = Generic(Locale.EN) # Access all providers through one object print(g.person.full_name()) # 'John Smith' print(g.address.city()) # 'New York' print(g.datetime.date()) # datetime.date(2023, 5, 15) print(g.internet.url()) # 'https://example.com/' print(g.cryptographic.uuid()) # 'a3d2f5e8-...' print(g.code.imei()) # '353918052107063' print(g.food.fruit()) # 'Apple' print(g.finance.price()) # 99.99 # Locale-independent providers work too print(g.code.isbn()) # '978-3-16-148410-0' print(g.hardware.cpu()) # 'Intel Core i7' print(g.transport.car()) # 'BMW' ``` -------------------------------- ### Override Locale with Generic Provider Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/locales.rst This example demonstrates how to use the `override_locale` context manager with the `Generic` provider in Mimesis. It shows how to generate text data in different locales by temporarily switching the locale for specific text generation methods. ```python from mimesis import Generic from mimesis.locales import Locale generic = Generic(locale=Locale.EN) generic.text.word() # Output: 'anyone' with generic.text.override_locale(Locale.FR): generic.text.word() # Output: 'mieux' generic.text.word() # Output: 'responsibilities' ``` -------------------------------- ### Generate Personal Data with Mimesis Person Provider Source: https://github.com/lk-geimfari/mimesis/blob/master/README.md This Python code demonstrates how to use the Person provider from the Mimesis library to generate fake personal information. It shows examples of generating a full name, an email address (with and without uniqueness), and a formatted telephone number. ```python from mimesis import Person from mimesis.locales import Locale person = Person(Locale.EN) person.full_name() # Output: 'Brande Sears' person.email(domains=['example.com']) # Output: 'roccelline1878@example.com' person.email(domains=['mimesis.name'], unique=True) # Output: 'f272a05d39ec46fdac5be4ac7be45f3f@mimesis.name' person.telephone(mask='1-4##-8##-5##3') # Output: '1-436-896-5213' ``` -------------------------------- ### Using the Custom Data Provider in Python Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/providers.rst This Python code snippet demonstrates how to instantiate and use the custom data provider. It shows creating an instance with a specific locale and calling a custom method to retrieve data. ```python >>> from mimesis.locales import Locale >>> cdp = CustomDataProvider(Locale.EN) >>> cdp.my_method() 'value3' ``` -------------------------------- ### Create Custom Mimesis Providers (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/providers.rst Demonstrates how to create custom data providers by subclassing mimesis.providers.base.BaseProvider. This allows for extending Mimesis with specific data needs. Custom providers can be added to a Generic instance. ```python from mimesis import Generic from mimesis.locales import Locale from mimesis.providers.base import BaseProvider class SomeProvider(BaseProvider): class Meta: name = "some_provider" @staticmethod def hello() -> str: return "Hello!" class Another(BaseProvider): def __init__(self, seed, message: str) -> None: super().__init__(seed=seed) self.message = message def bye(self) -> str: return self.message generic = Generic(locale=Locale.DEFAULT) generic.add_provider(SomeProvider) # or generic += SomeProvider generic.add_provider(Another, message="Bye!") generic.some_provider.hello() # Output: 'Hello!' generic.another.bye() # Output: 'Bye!' ``` ```python generic.add_providers(SomeProvider, Another) generic.some_provider.hello() # Output: 'Hello!' generic.another.bye() # Output: 'Bye!' ``` ```python class InvalidProvider: @staticmethod def hello() -> str: return 'Hello!' generic.add_provider(InvalidProvider) ... ... TypeError: The provider must be a subclass of mimesis.providers.BaseProvider. ``` -------------------------------- ### Hashing Data with SHA256 and Blake2s Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Demonstrates how to hash generated data using SHA256 and Blake2s algorithms with the Mimesis library. This is useful for generating secure identifiers or checksums. ```python >>> from mimesis import keys >>> field("password", key=keys.hash_with('sha256')) '8742c08c354ea086510c5a6abf7f6ed8b938ad00b35c740c3f02d01b75f11d06' >>> field("email", key=keys.hash_with('blake2s')) '86167b4b002d323526088b837edc34223a404055b7ab8b6205957ab42325f752' ``` -------------------------------- ### Instantiate Locale-Independent Provider (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/providers.rst Shows how to instantiate a locale-independent provider, like Code, which does not require a locale. Attempting to specify a locale for such providers will result in a TypeError. ```python from mimesis import Code code = Code() code.imei() # Output: '353918052107063' ``` ```python from mimesis import Code from mimesis.locales import Locale code = Code(locale=Locale.EN) # TypeError: BaseProvider.__init__() got an unexpected keyword argument 'locale' ``` -------------------------------- ### Instantiate Locale-Dependent Provider (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/providers.rst Demonstrates how to instantiate a locale-dependent provider, such as Person, and generate data. If no locale is specified, the default locale (Locale.EN) is used. ```python from mimesis import Person from mimesis.locales import Locale person = Person(locale=Locale.EN) person.name() # Output: 'John' ``` -------------------------------- ### Chaining Key Functions with 'pipe' Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Explains the `pipe` key function for sequentially applying multiple key functions. The output of one function becomes the input for the next, enabling complex data transformations. ```python >>> from mimesis import keys >>> field("full_name", key=keys.pipe( ... str.lower, ... # ... more functions can be added here ... )) ``` -------------------------------- ### Chaining Key Functions with pipe in Mimesis Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Demonstrates how to chain multiple key functions using mimesis.keys.pipe for complex data transformations. This allows for sequential application of functions like slugify, prefix, hash_with, and string manipulations. ```python from mimesis import Field from mimesis.locales import Locale from mimesis import keys field = Field(Locale.EN, seed=42) # Create a slugified, prefixed username field("username", key=keys.pipe( keys.slugify, keys.prefix('user-') )) # Create a hashed, prefixed username field("email", key=keys.pipe( lambda s: s.split('@')[0], keys.hash_with('md5'), keys.prefix('usr_'), lambda x: x[:16] )) # Complex transformation chain: lowercase, remove whitespace, base64 encode field("sentence", key=keys.pipe( str.lower, keys.remove_whitespace, keys.base64_encode )) ``` -------------------------------- ### Use Generic Provider for Data Generation (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/providers.rst Illustrates the usage of the Generic provider, which consolidates access to all other Mimesis providers for a specified locale. It automatically handles locale-dependent and independent providers. ```python from mimesis import Generic from mimesis.locales import Locale g = Generic(locale=Locale.ES) g.datetime.month() # Output: 'Agosto' g.code.imei() # Output: '353918052107063' g.food.fruit() # Output: 'Limón' ``` -------------------------------- ### Use Generic Provider with Seed for Multiple Data Types (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/random_and_seed.rst Illustrates how to use the Generic provider with a seed to ensure consistent random data generation across different Mimesis providers (e.g., Person, Datetime, Text). This simplifies managing seeds for multiple data types. ```python from mimesis import Generic, Locale generic = Generic(Locale.EN, seed='Wow. Much seed. Much random.') generic.person.name() # Output: 'Donn' generic.datetime.date() # Output: '2021-09-04' generic.text.word() # Output: 'platform' ``` -------------------------------- ### Create Custom Data Provider with Random Attribute (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/random_and_seed.rst Demonstrates how to create a custom data provider by subclassing BaseProvider and utilizing the 'random' attribute for generating random numbers. This is useful when extending Mimesis with your own data generation logic. ```python from mimesis import BaseProvider class MyProvider(BaseProvider): class Meta: name = 'my_provider' def my_method(self): return self.random.randint(0, 100) my_provider = MyProvider() my_provider.my_method() # Output: 42 ``` -------------------------------- ### Apply Key Functions to Mimesis Fields and Fieldsets (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Demonstrates how to use the 'key' parameter in Mimesis Field and Fieldset to apply transformation functions to generated values. This allows for post-generation data manipulation. ```python from mimesis import Field, Fieldset, Locale field = Field(Locale.EN) print(field("name", key=str.upper)) fieldset = Fieldset(i=3) print(fieldset("name", key=str.upper)) ``` -------------------------------- ### Complex Relational Data Generation with Mimesis Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Illustrates generating complex relational data involving three schemas: users, projects, and API keys. It showcases using ctx.pick_from for cross-schema referencing and field.get_random_instance().choice for selecting from a list. ```python from mimesis.schema import Field, Schema, SchemaBuilder from mimesis.enums import TimestampFormat from mimesis.locales import Locale SEED = 0xFF field = Field(Locale.EN, seed=SEED) builder = SchemaBuilder(seed=SEED) # Define users builder.define( "users", Schema(lambda: { "id": field("increment", accumulator="user"), "username": field("username"), "email": field("email"), "created_at": field("timestamp", fmt=TimestampFormat.POSIX), }) ) # Define projects (owned by users) builder.define( "projects", Schema(lambda: { "id": field("increment", accumulator="project"), "name": field("text.word"), "version": field("version"), }) .map(lambda item, ctx: { **item, "owner_id": ctx.pick_from("users", "id"), # Assign random user as owner "status": field.get_random_instance().choice( ["active", "archived", "draft"] ), }) ) # Define API keys (belong to projects, created by users) builder.define( "api_keys", Schema(lambda: { "id": field("uuid"), "key": field("token_hex"), "created_at": field("timestamp", fmt=TimestampFormat.POSIX), }) .map(lambda item, ctx: item | {"project_id": ctx.pick_from("projects", "id")}) ) # Generate all data with proper relationships data = builder.create( users=3, projects=5, api_keys=10 ) # This will generate: # - 3 users # - 5 projects (each with a valid ``owner_id`` referencing a user) # - 10 API keys (each with a valid ``project_id`` referencing projects) ``` -------------------------------- ### Accessing Random Instance for Seeded Operations in Mimesis Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Shows how to access the Mimesis random instance within a key function to ensure consistent seeding across operations. This is useful for complex transformations that rely on random choices or other random methods. ```python from mimesis import Field from mimesis.locales import Locale field = Field(Locale.EN, seed=42) foobarify = lambda val, rand: rand.choice(["foo", "bar"]) + val field("email", key=foobarify) ``` -------------------------------- ### Set Global Seed for All Data Providers (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/random_and_seed.rst Explains how to set a global seed for the `mimesis.random` module, which will then be applied to all data providers automatically without needing to pass the seed explicitly to each one. This is convenient for ensuring consistent randomness across an entire application. ```python from mimesis import random random.global_seed = 0xFF from mimesis import Person, Locale person = Person(Locale.EN) person.full_name() # Output: 'Karl Munoz' ``` -------------------------------- ### Base64 Encoding Strings Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Shows how to encode strings into Base64 format using Mimesis. This is commonly used for data transmission and storage. ```python >>> from mimesis import keys >>> field("sentence", key=keys.base64_encode) 'SSBkb24ndCBldmVuIGNhcmUu' ``` -------------------------------- ### Weighted Choice for Probabilistic Data Generation (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/random_and_seed.rst Demonstrates how to use the `weighted_choice` method from the random attribute to generate data with specific probabilities. This is useful for scenarios where certain outcomes should be more likely than others, such as generating names with a bias towards a specific gender. ```python from mimesis import Person, Locale, Gender person = Person(Locale.EN) for _ in range(10): full_name = person.full_name( gender=person.random.weighted_choice( choices={ Gender.MALE: 0.2, Gender.FEMALE: 0.8, } ), ) print(full_name) ``` -------------------------------- ### Integrate Mimesis with Factory Boy for Test Fixtures Source: https://context7.com/lk-geimfari/mimesis/llms.txt Explains how to use the Mimesis factory_boy plugin to generate test data fixtures. It shows defining a model and a factory that utilizes Mimesis fields for attribute generation. ```python # Install: pip install mimesis[factory] import factory from mimesis.plugins.factory import FactoryField # Define your model class User: def __init__(self, username, email, name, age): self.username = username self.email = email self.name = name self.age = age # Create factory with Mimesis fields class UserFactory(factory.Factory): class Meta: model = User username = FactoryField('username', mask='l_d') name = FactoryField('name', gender='female') age = FactoryField('integer_number', start=18, end=65) email = factory.LazyAttribute( lambda obj: f'{obj.username}@example.com' ) # Generate test data user = UserFactory() users = UserFactory.create_batch(10) ``` -------------------------------- ### Generate IP Addresses and MAC Addresses with Mimesis Source: https://context7.com/lk-geimfari/mimesis/llms.txt Generates various types of IP addresses (IPv4, IPv6, CIDR) and MAC addresses. Includes options for IPv4 with ports and public DNS resolution. Essential for simulating network configurations. ```python from mimesis import Internet internet = Internet() # Generate IP Addresses print(internet.ip_v4()) # '192.168.1.1' print(internet.ip_v6()) # '2001:db8::8a2e:370:7334' print(internet.ip_v4_with_port()) # '192.168.1.1:8080' print(internet.ip_v4_cidr()) # '192.168.1.0/24' print(internet.ip_v6_cidr()) # '2001:db8::/32' print(internet.public_dns()) # '8.8.8.8' # Generate MAC Address print(internet.mac_address()) # '00:16:3e:25:e7:f1' ``` -------------------------------- ### Seed Data Provider with Integer or String (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/random_and_seed.rst Shows how to initialize a data provider (e.g., Person) with a specific seed value, ensuring that the generated data is reproducible. Supports integer, string, bytes, and bytearray seeds. ```python from mimesis import Person, Locale person = Person(locale=Locale.TR, seed=0xFF) person.full_name() # Output: 'Gizem Tekand' ``` ```python from mimesis import Person, Locale person = Person(Locale.EN, seed='Wow.') person.name() # Output: 'Fausto' person.reseed('Wow.') person.name() # Output: 'Fausto' ``` -------------------------------- ### Create Pandas DataFrames with Mimesis Fieldset in Python Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Illustrates how to use Mimesis's Fieldset to generate data for creating Pandas DataFrames. This allows for the creation of test data that mirrors real-world structures, facilitating testing and analysis. ```python import pandas as pd from mimesis import Fieldset from mimesis.locales import Locale fs = Fieldset(locale=Locale.EN, i=5) df = pd.DataFrame.from_dict({ "ID": fs("increment"), "Name": fs("person.full_name"), "Email": fs("email"), "Phone": fs("telephone", mask="+1 (###) #5#-7#9#"), }) print(df) ``` -------------------------------- ### Define and Generate Relational Data Schemas with Mimesis Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Demonstrates defining multiple related schemas (users, projects) using SchemaBuilder and generating data with cross-schema references. Ensures schemas are defined in the correct order for valid references. ```python from mimesis.schema import Field, Schema, SchemaBuilder builder = SchemaBuilder() field = Field() # Define the users schema builder.define( "users", Schema(lambda: { "id": field("increment", accumulator="user"), "username": field("username"), "email": field("email"), }) ) # Define the posts schema with a reference to users builder.define( "projects", Schema(lambda: { "id": field("increment", accumulator="project"), "title": field("sentence"), }) .map(lambda item, ctx: { **item, "user_id": ctx.pick_from("users", "id"), # Reference to user }) ) # Create data data = builder.create(users=5, projects=20) # Access generated data print(data["users"]) # List of 5 users print(data["projects"]) # List of 20 projects with valid user_id references ``` -------------------------------- ### Generate Personal Data with Mimesis Person Provider (Python) Source: https://context7.com/lk-geimfari/mimesis/llms.txt This snippet demonstrates how to use the Person provider from the Mimesis library to generate various types of personal data, including names, contact information, usernames, and birthdates. It supports locale-specific generation and options for gender, masks, and uniqueness. ```python from mimesis import Person from mimesis.locales import Locale from mimesis.enums import Gender # Create person provider with locale person = Person(Locale.EN) # Generate names person.name() # 'John' person.name(gender=Gender.FEMALE) # 'Sarah' person.full_name() # 'John Smith' person.full_name(reverse=True) # 'Smith John' person.surname() # 'Williams' # Generate contact information person.email() # 'foretime10@live.com' person.email(domains=['company.com']) # 'user1892@company.com' person.email(unique=True) # 'f272a05d39ec46fd@gmail.com' person.phone_number() # '+1-(963)-409-11-22' person.phone_number(mask='###-###-####') # '555-123-4567' person.phone_number(e164=True) # '+14155552671' # Generate usernames with masks (C=Capitalized, U=UPPERCASE, l=lowercase, d=digits) person.username() # 'plasmic_1907' person.username(mask='C_C_d') # 'Cotte_Article_1923' person.username(mask='U.l.d') # 'ELKINS.wolverine.2013' # Other personal data person.password(length=16) # 'k6dv2odff9#4h...' person.password(length=8, hashed=True) # SHA256 hash person.gender() # 'Male' person.occupation() # 'Programmer' person.university() # 'MIT' person.birthdate(min_year=1980, max_year=2000) # datetime.date(1995, 3, 15) person.blood_type() # 'A+' person.height() # '1.85' person.weight() # 72 ``` -------------------------------- ### Generate Lists and Single Values with Field and Fieldset in Python Source: https://context7.com/lk-geimfari/mimesis/llms.txt This code demonstrates the use of Mimesis' Field and Fieldset classes for generating single values and lists of values, respectively. It supports both explicit provider method calls and implicit naming, and allows for transformations using keys. ```python from mimesis import Field, Fieldset from mimesis.locales import Locale from mimesis.enums import Gender # Single value generation field = Field(Locale.EN, seed=42) print(field('name')) # 'John' print(field('person.name')) # 'John' (explicit) print(field('full_name', gender=Gender.FEMALE)) # 'Sarah Williams' print(field('email', domains=['test.com'])) # 'user1234@test.com' print(field('uuid')) # 'a3d2f5e8-...' # Generate lists of values fieldset = Fieldset(Locale.EN, seed=42) print(fieldset('name', i=5)) # ['John', 'Sarah', 'Mike', 'Emma', 'David'] print(fieldset('email', i=3)) # ['user1@gmail.com', 'user2@live.com', ...] print(fieldset('integer_number', i=10)) # [42, 17, 89, ...] # Key functions for transformation print(field('name', key=str.upper)) # 'JOHN' print(fieldset('name', i=3, key=str.lower)) # ['john', 'sarah', 'mike'] ``` -------------------------------- ### Hash Strings with hashlib Algorithms (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Applies the mimesis.keys.hash_with function to hash a string using algorithms from Python's hashlib module (e.g., sha256, md5). Useful for generating secure hashes or checksums. ```python from mimesis import Field, Locale from mimesis import keys field = Field(Locale.EN) # Example using sha256, replace with desired algorithm print(field("password", key=keys.hash_with('sha256'))) ``` -------------------------------- ### Generate URLs, Hostnames, and Paths with Mimesis Source: https://context7.com/lk-geimfari/mimesis/llms.txt Generates various internet-related strings like URLs, hostnames, slugs, and paths. Supports customization for schemes, TLD types, and subdomains. Useful for creating mock network data. ```python from mimesis import Internet from mimesis.enums import URLScheme, TLDType internet = Internet() # Generate URLs print(internet.url()) # 'https://example.com/' print(internet.url(scheme=URLScheme.HTTP)) # 'http://example.org/' print(internet.uri(query_params_count=3)) # 'https://host.net/2024/01/15/article?a=b&c=d' # Generate Hostnames print(internet.hostname()) # 'example.com' print(internet.hostname(tld_type=TLDType.GTLD)) # 'example.org' print(internet.hostname(subdomains=['api', 'www'])) # 'api.example.com' # Generate Paths and Slugs print(internet.slug()) # 'random-words-here' print(internet.path()) # 'random/path/segments' ``` -------------------------------- ### Generate HTTP Headers with Mimesis Source: https://context7.com/lk-geimfari/mimesis/llms.txt Generates dictionaries containing mock HTTP request and response headers. Includes common headers like User-Agent, Authorization, Cookie, Content-Type, and Set-Cookie. Useful for testing API clients and servers. ```python from mimesis import Internet internet = Internet() # Generate HTTP Headers (returns dict) print(internet.http_request_headers()) # {'User-Agent': '...', 'Authorization': 'Bearer ...', 'Cookie': '...', ...} print(internet.http_response_headers()) # {'Content-Type': '...', 'Set-Cookie': '...', 'X-Request-ID': '...', ...} ``` -------------------------------- ### Create Polars DataFrames with Mimesis Fieldset in Python Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Demonstrates the use of Mimesis's Fieldset for generating data to construct Polars DataFrames. This integration enables the creation of structured test data suitable for Polars-based data analysis workflows. ```python import polars as pl from mimesis import Fieldset from mimesis.locales import Locale fs = Fieldset(locale=Locale.EN, i=5) df = pl.DataFrame({ "ID": fs("increment"), "Name": fs("person.full_name"), "Email": fs("email"), "Phone": fs("telephone", mask="+1 (###) #5#-7#9#"), }) print(df) ``` -------------------------------- ### Seeding for Reproducible Data Generation in Mimesis Source: https://context7.com/lk-geimfari/mimesis/llms.txt Details how to use seeds in Mimesis for generating reproducible fake data. Seeding can be applied at the provider, field, or schema level to ensure consistent results. ```python from mimesis import Person, Field, Schema from mimesis.locales import Locale # Provider-level seeding person = Person(Locale.EN, seed=42) person.full_name() # Always returns same value with seed=42 # Field-level seeding field = Field(Locale.EN, seed=42) field('full_name') # Reproducible # Reseed during runtime field.reseed(123) field('email') # New reproducible sequence # Schema seeding schema = Schema( schema=lambda: {"name": field("full_name")}, iterations=10, seed=42 ) ``` -------------------------------- ### Import Schema Dependencies (Python) Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Imports necessary classes and enums from the mimesis library to begin defining schemas for structured data generation. ```python from mimesis import Field, Fieldset, Schema from mimesis.enums import Gender, TimestampFormat ``` -------------------------------- ### Define Custom Data Directory Structure Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/providers.rst This text block illustrates the required directory structure for custom data providers. It shows how to organize locale-specific JSON files within a main data directory. ```text custom_datadir/ ├── de │ └── file_name.json ├── en │ └── file_name.json └── ru └── file_name.json ``` -------------------------------- ### Conditional Data Generation with 'maybe' Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Explains the `maybe` key function for generating realistic data that may include null or placeholder values. It accepts a value and a probability to determine if the value should be generated or if a default (like None or 'N/A') should be used. ```python >>> from mimesis import Fieldset, Locale >>> from mimesis.keys import maybe >>> fieldset = Fieldset(Locale.EN, i=5) >>> fieldset("email", key=maybe(None, probability=0.6)) [None, None, None, 'bobby1882@gmail.com', None] >>> fieldset = Fieldset("en", i=5) >>> fieldset("email", key=maybe('N/A', probability=0.6)) ['N/A', 'N/A', 'static1955@outlook.com', 'publish1929@live.com', 'command2060@yahoo.com'] ``` -------------------------------- ### Bulk Create Datetimes with Mimesis Source: https://context7.com/lk-geimfari/mimesis/llms.txt Generates a list of datetime objects within a specified date range and interval. Useful for creating time-series data or populating schedules. ```python from mimesis import Datetime from mimesis.locales import Locale from datetime import datetime dt = Datetime(Locale.EN) # Bulk create datetimes print(dt.bulk_create_datetimes( date_start=datetime(2023, 1, 1), date_end=datetime(2023, 1, 10), days=1 )) # List of 10 datetime objects ``` -------------------------------- ### Define and Use Field Aliases in Mimesis Source: https://context7.com/lk-geimfari/mimesis/llms.txt Shows how to create custom aliases for field names using the Mimesis Field provider. This allows mapping generic field names to domain-specific terminology. Aliases can be updated, used, popped, or cleared. ```python from mimesis import Field, Locale field = Field(Locale.EN) # Define aliases field.aliases.update({ 'customer_name': 'full_name', 'customer_email': 'email', 'order_id': 'uuid', 'price_usd': 'price', }) # Use aliases field('customer_name') # 'John Smith' field('customer_email') # 'user@example.com' field('order_id') # 'a3d2f5e8-...' # Remove aliases field.aliases.pop('customer_name') field.aliases.clear() ``` -------------------------------- ### Generate Pandas DataFrame with Mimesis Source: https://context7.com/lk-geimfari/mimesis/llms.txt Illustrates how to integrate Mimesis Fieldset with Pandas to generate a DataFrame populated with fake data. This is useful for creating test datasets or sample data for analysis. ```python import pandas as pd from mimesis import Fieldset from mimesis.locales import Locale fs = Fieldset(locale=Locale.EN, i=1000) df = pd.DataFrame({ "id": fs("increment"), "name": fs("full_name"), "email": fs("email"), "phone": fs("telephone", mask="+1 (###) ###-####"), "city": fs("city"), "country": fs("country"), "signup_date": fs("date"), "is_active": fs("boolean"), }) print(df.head()) ``` -------------------------------- ### Generate DSNs and Query Strings with Mimesis Source: https://context7.com/lk-geimfari/mimesis/llms.txt Generates Data Source Names (DSNs) for databases like PostgreSQL and Redis, and creates query strings or parameter dictionaries. Useful for simulating database connections and API requests. ```python from mimesis import Internet from mimesis.enums import DSNType internet = Internet() # Generate DSNs print(internet.dsn(dsn_type=DSNType.POSTGRES)) # 'postgres://host.com:5432' print(internet.dsn(dsn_type=DSNType.REDIS)) # 'redis://host.com:6379' # Generate Query Parameters print(internet.query_string(length=3)) # 'key1=value1&key2=value2&key3=value3' print(internet.query_parameters(length=2)) # {'param1': 'value1', 'param2': 'value2'} ``` -------------------------------- ### Generate Internet Data with Mimesis Internet Provider (Python) Source: https://context7.com/lk-geimfari/mimesis/llms.txt This snippet shows how to use the Internet provider from the Mimesis library to generate network-related data. It covers generating URLs, IP addresses, email domains, HTTP headers, and DSN strings, utilizing various enums for specific data types. ```python from mimesis import Internet from mimesis.enums import TLDType, URLScheme, PortRange, DSNType, MimeType internet = Internet() # Example usage (actual output will vary): # internet.ip_v4() # e.g., '192.168.1.1' # internet.ip_v6() # e.g., '2001:0db8:85a3:0000:0000:8a2e:0370:7334' # internet.url() # e.g., 'http://example.com' # internet.top_level_domain() # e.g., '.com' # internet.email() # e.g., 'user@example.com' # internet.http_header() # internet.dsn() # internet.mime_type() ``` -------------------------------- ### Data Transformation with Mimesis Key Functions (Python) Source: https://context7.com/lk-geimfari/mimesis/llms.txt Applies various transformations to generated data using Mimesis key functions. These functions include string manipulations, wrapping, affixes, encoding, hashing, conditional logic, redaction, joining, and romanization. They can be piped together for complex transformations. ```python from mimesis import Field, Fieldset, Locale from mimesis import keys field = Field(Locale.EN) fieldset = Fieldset(Locale.EN, i=5) # String transformations field('full_name', key=str.upper) # 'JOHN SMITH' field('full_name', key=str.lower) # 'john smith' field('full_name', key=keys.snake_case) # 'john_smith' field('full_name', key=keys.camel_case) # 'johnSmith' field('full_name', key=keys.kebab_case) # 'john-smith' field('full_name', key=keys.slugify) # 'john-smith' # Wrapping and affixes field('username', key=keys.wrap('<', '>')) # '' field('word', key=keys.prefix('user_')) # 'user_dynamics' field('word', key=keys.suffix('.io')) # 'dynamics.io' # String manipulation field('word', key=keys.reverse) # 'scimanyd' field('sentence', key=keys.truncate(20)) # 'Hello world thi...' field('full_name', key=keys.remove_whitespace) # 'JohnSmith' # Encoding and hashing field('password', key=keys.hash_with('sha256')) # 'd3e7130d657733468b10c1fd207c4d62b7180cda...' field('word', key=keys.base64_encode) # 'ZHluYW1pY3M=' field('word', key=keys.urlsafe_base64_encode) # 'ZHluYW1pY3M=' # Maybe - randomly return None or alternate value fieldset('email', key=keys.maybe(None, probability=0.3)) # ['user@gmail.com', None, 'test@live.com', None, 'demo@yahoo.com'] fieldset('email', key=keys.maybe('N/A', probability=0.5)) # ['N/A', 'user@gmail.com', 'N/A', 'test@live.com', 'N/A'] # Conditional transformation field('word', key=keys.apply_if( lambda x: len(x) > 5, str.upper, str.lower )) # 'DYNAMICS' or 'hi' # Redaction field('password', key=keys.redact('[CLASSIFIED]')) # '[CLASSIFIED]' # Join list items field('words', quantity=3, key=keys.join(' | ')) # 'word1 | word2 | word3' # Pipe multiple transformations field('full_name', key=keys.pipe( str.lower, keys.slugify, keys.prefix('user-') )) # 'user-john-smith' # Romanization (Cyrillic to Latin) field_ru = Field(Locale.RU) field_ru('name', key=keys.romanize(Locale.RU)) # 'Ivan' instead of 'Иван' ``` -------------------------------- ### Define and Generate Data with Mimesis Schema Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst This Python code demonstrates how to define a data schema using Mimesis Field and Fieldset, wrap it in a callable for dynamic evaluation, and then create a Schema instance to generate multiple records. It includes fields for incrementing IDs, UUIDs, text, versions, timestamps, nested owner information, and arrays of tokens. ```python from mimesis import Field, Fieldset, Schema from mimesis.enums import Gender, TimestampFormat from mimesis.locales import Locale field = Field(Locale.EN, seed=0xff) fieldset = Fieldset(Locale.EN, seed=0xff) schema_definition = lambda: { "pk": field("increment"), "uid": field("uuid"), "name": field("text.word"), "version": field("version"), "timestamp": field("timestamp", fmt=TimestampFormat.POSIX), "owner": { "email": field("person.email", domains=["mimesis.name"]), "creator": field("full_name", gender=Gender.FEMALE), }, "apiKeys": fieldset("token_hex", key=lambda s: s[:16], i=3), } schema = Schema(schema=schema_definition, iterations=3) schema.create() ``` -------------------------------- ### Export Generated Data to CSV, JSON, and Pickle in Python Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Shows how to export data generated by Mimesis schemas into CSV, JSON, and pickle formats. This involves defining a schema with a Field instance and then calling the respective `to_csv`, `to_json`, or `to_pickle` methods on the schema object. ```python from mimesis.enums import TimestampFormat from mimesis.locales import Locale from mimesis.keys import maybe from mimesis.schema import Field, Schema field = Field(locale=Locale.EN) schema = Schema( schema=lambda: { "pk": field("increment"), "name": field("text.word", key=maybe("N/A", probability=0.2)), "version": field("version"), "timestamp": field("timestamp", TimestampFormat.RFC_3339), }, iterations=1000 ) schema.to_csv(file_path='data.csv') schema.to_json(file_path='data.json') schema.to_pickle(file_path='data.obj') ``` -------------------------------- ### URL-Safe Base64 Encoding Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Illustrates URL-safe Base64 encoding, which replaces characters with special URL meanings (+, /) with safer alternatives (-, _). Useful for generating tokens or identifiers intended for URLs. ```python >>> from mimesis import keys >>> field("token_hex", key=keys.urlsafe_base64_encode) 'SXQgaXMgYWxzbyBhIGdhcmJhZ2UtY29sbGVjdGVkIHJ1bnRpbWUgc3lzdGVtLg==' ``` -------------------------------- ### Joining Sequence Elements into a String Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Demonstrates the `join` key function, which concatenates elements of a list or tuple into a single string using a specified separator. It automatically converts elements to strings. ```python >>> from mimesis import keys >>> fieldset("words", key=keys.join(' | ')) ['personals | errors', 'eyes | monday', 'kim | mn'] ``` -------------------------------- ### Generate Stock Image URLs with Mimesis Source: https://context7.com/lk-geimfari/mimesis/llms.txt Generates URLs for stock images, typically from services like Unsplash. Allows specifying dimensions and keywords to tailor the image search. Useful for populating UIs with placeholder images. ```python from mimesis import Internet internet = Internet() # Generate Stock Image URLs print(internet.stock_image_url(width=800, height=600, keywords=['nature'])) # 'https://source.unsplash.com/800x600?nature' ``` -------------------------------- ### Generate Dates and Times with Mimesis Source: https://context7.com/lk-geimfari/mimesis/llms.txt Generates various date and time components, including full dates, times, datetimes, timestamps in different formats (POSIX, RFC, ISO), durations, and calendar data like year, month, day, and week. Supports locale-specific formatting. ```python from mimesis import Datetime from mimesis.locales import Locale from mimesis.enums import TimestampFormat, DurationUnit dt = Datetime(Locale.EN) # Generate Dates print(dt.date()) # datetime.date(2023, 5, 15) print(dt.date(start=2020, end=2024)) # Date between 2020-2024 print(dt.formatted_date()) # '15-05-2023' (locale format) print(dt.formatted_date(fmt='%Y/%m/%d')) # '2023/05/15' # Generate Times print(dt.time()) # datetime.time(14, 30, 45) print(dt.formatted_time()) # '14:30:45' print(dt.formatted_time(fmt='%H:%M')) # '14:30' # Generate Datetime print(dt.datetime()) # datetime.datetime(2023, 5, 15, 14, 30) # Timestamps print(dt.timestamp(fmt=TimestampFormat.POSIX)) # 1684159845 print(dt.timestamp(fmt=TimestampFormat.RFC_3339)) # '2023-05-15T14:30:45Z' print(dt.timestamp(fmt=TimestampFormat.ISO_8601)) # '2023-05-15T14:30:45+00:00' # Duration print(dt.duration(unit=DurationUnit.HOURS)) # '5 hours' print(dt.duration(unit=DurationUnit.DAYS)) # '3 days' ``` -------------------------------- ### Registering Custom Field Handlers with Decorators in Mimesis Source: https://github.com/lk-geimfari/mimesis/blob/master/docs/schema.rst Demonstrates registering custom field handlers using the @field.handle decorator. This provides a concise way to register functions as field handlers directly. ```python from mimesis import Field from mimesis.random import Random field = Field() @field.handle("my_field") def my_field(random: Random, a=None, b=None) -> str: return random.choice([a, b]) field("my_field", a="a", b="b") ```