検索
ホームページバックエンド開発Python チュートリアルPython でストライプ テスト データを作成する

私たちは、Airbyte PGVector コネクタを介して、Stripe から Supabase で実行されている PGVector に e コマース データを移動し、OpenAI クライアント ライブラリを使用して OpenAI 埋め込みを作成することで、AI チャットボットを構築する方法を示す新しい AI データ コースに取り組んでいます。自然言語サポートをアプリに追加します。これは、多くのお客様が実装している非常に一般的な「インテリジェント データ スタック」アプリ パターンです。ソースと宛先は変更される可能性がありますが、パターン (データ ソース > データの移動と埋め込みの作成 > ベクター対応データ ストア > OpenAI を使用した Web アプリ) は変わりません。

Creating Stripe Test Data in Python

私たちは一般の人が実際に体験できるコースを作成しているため、セットアップをできるだけ簡単にしたいと考えました。その大きな部分は、チャットボットが対話するための適切なデータセットが存在するように、Stripe で十分なテスト データを作成することでした。これまでに Stripe を使用したことがある場合は、実験できる優れたサンドボックスがあることをご存知でしょう。唯一の問題は、サンプルデータが事前にロードされていないことです。

CLI フィクスチャ コマンドを介してロードできるサンプル データセットがいくつかあります。しかし、私たちの用途では、これらはニーズに合いませんでした。私たちはより大きなデータ セットが必要でした。また、この教材はオンラインやワークショップで使用されるため、学習者に CLI などの何かをローカル マシンにインストールするよう求めると、非常に複雑な処理が必要になります。ユーザーが実行している OS のバージョン、インストールするための適切な権限があるかどうかなどはわかりません。私はその道を進むのに何度も火傷を負いました。

ありがたいことに、Stripe には素晴らしい API と優れた Python クライアントもあるので、学習者が必要なデータを実行して挿入できるコラボ ノートブックをすぐに作成できます。

!pip install Stripe を使用してストライプ ライブラリをインストールし、Google Collab シークレットを使用してテスト キーを渡した後、顧客と製品にランダムな名前をいくつか設定する必要がありました。目標は、ランダムなコレクションの顧客、異なる価格の製品、および購入を挿入することでした。このようにして、チャットボットに「誰が最も安く購入しましたか? いくら払って、何を購入しましたか?」などの質問をするときに、このようにします。十分なデータがありました。

import stripe
import random
from google.colab import userdata


stripe.api_key = userdata.get('STRIPE_TEST_KEY')


# Sample data for generating random names
first_names = ["Alice", "Bob", "Charlie", "Diana", "Eve", "Frank", "Grace", "Hank", "Ivy", "Jack", "Quinton", "Akriti", "Justin", "Marcos"]
last_names = ["Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Taylor", "Wall", "Chau", "Keswani", "Marx"]
# Sample clothing product names
clothing_names = [
    "T-Shirt", "Jeans", "Jacket", "Sweater", "Hoodie",
    "Shorts", "Dress", "Blouse", "Skirt", "Pants",
    "Shoes", "Sandals", "Sneakers", "Socks", "Hat",
    "Scarf", "Gloves", "Coat", "Belt", "Tie",
    "Tank Top", "Cardigan", "Overalls", "Tracksuit", "Polo Shirt",
    "Cargo Pants", "Capris", "Dungarees", "Boots", "Cufflinks",
    "Raincoat", "Peacoat", "Blazer", "Slippers", "Underwear",
    "Leggings", "Windbreaker", "Tracksuit Bottoms", "Beanie", "Bikini"
]
# List of random colors
colors = [
    "Red", "Blue", "Green", "Yellow", "Black", "White", "Gray",
    "Pink", "Purple", "Orange", "Brown", "Teal", "Navy", "Maroon",
    "Gold", "Silver", "Beige", "Lavender", "Turquoise", "Coral"
]

次に、必要な Stripe の各データ型に関数を追加します。

# Function to create sample customers with random names
def create_customers(count=5):
    customers = []
    for _ in range(count):
        first_name = random.choice(first_names)
        last_name = random.choice(last_names)
        name = f"{first_name} {last_name}"
        email = f"{first_name.lower()}.{last_name.lower()}@example.com"

        customer = stripe.Customer.create(
            name=name,
            email=email,
            description="Sample customer for testing"
        )
        customers.append(customer)
        print(f"Created Customer: {customer['name']} (ID: {customer['id']})")
    return customers

# Function to create sample products with random clothing names and colors
def create_products(count=3):
    products = []
    for _ in range(count):
        color = random.choice(colors)
        product_name = random.choice(clothing_names)
        full_name = f"{color} {product_name}"
        product = stripe.Product.create(
            name=full_name,
            description=f"This is a {color.lower()} {product_name.lower()}"
        )
        products.append(product)
        print(f"Created Product: {product['name']} (ID: {product['id']})")
    return products

# Function to create prices for the products with random unit_amount
def create_prices(products, min_price=500, max_price=5000):
    prices = []
    for product in products:
        unit_amount = random.randint(min_price, max_price)  # Random amount in cents
        price = stripe.Price.create(
            unit_amount=unit_amount,
            currency="usd",
            product=product['id']
        )
        prices.append(price)
        print(f"Created Price: ${unit_amount / 100:.2f} for Product {product['name']} (ID: {price['id']})")
    return prices

# Function to create random purchases for each customer
def create_purchases(customers, prices, max_purchases_per_customer=5):
    purchases = []
    for customer in customers:
        num_purchases = random.randint(1, max_purchases_per_customer)  # Random number of purchases per customer
        for _ in range(num_purchases):
            price = random.choice(prices)  # Randomly select a product's price
            purchase = stripe.PaymentIntent.create(
                amount=price['unit_amount'],  # Amount in cents
                currency=price['currency'],
                customer=customer['id'],
                payment_method_types=["card"],  # Simulate card payment
                description=f"Purchase of {price['product']} by {customer['name']}"
            )
            purchases.append(purchase)
            print(f"Created Purchase for Customer {customer['name']} (Amount: ${price['unit_amount'] / 100:.2f})")
    return purchases

あとはスクリプトを実行して、必要なデータ量を指定するだけです。

# Main function to create sample data
def main():
    print("Creating sample customers with random names...")
    customers = create_customers(count=20)

    print("\nCreating sample products with random clothing names and colors...")
    products = create_products(count=30)

    print("\nCreating prices for products with random amounts...")
    prices = create_prices(products, min_price=500, max_price=5000)

    print("\nCreating random purchases for each customer...")
    purchases = create_purchases(customers, prices, max_purchases_per_customer=10)

    print("\nSample data creation complete!")
    print(f"Created {len(customers)} customers, {len(products)} products, and {len(purchases)} purchases.")

if __name__ == "__main__":
    main()

Stripe Sandbox にデータをロードすると、コネクタ ビルダーを使用して API エンドポイントを各データ タイプのストリームにマッピングし、同期ジョブをセットアップすることで、データを Airbyte に接続するのに数分しかかかりませんでした。

Creating Stripe Test Data in Python

問題は解決しました! Collab Python スクリプトを使用すると、学習者がテスト データを Stripe に挿入するのが非常に簡単になります。同様のテストを行っている他の人にとって役立つことを願っています。

以上がPython でストライプ テスト データを作成するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
どのデータ型をPythonアレイに保存できますか?どのデータ型をPythonアレイに保存できますか?Apr 27, 2025 am 12:11 AM

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

Pythonアレイに間違ったデータ型の値を保存しようとするとどうなりますか?Pythonアレイに間違ったデータ型の値を保存しようとするとどうなりますか?Apr 27, 2025 am 12:10 AM

heouttemptemptostoreavure ofthewrongdatatypeinapythonarray、yure counteractypeerror.thisduetothearraymodule'sstricttypeeencultionyを使用します

Python Standard Libraryの一部はどれですか:リストまたは配列はどれですか?Python Standard Libraryの一部はどれですか:リストまたは配列はどれですか?Apr 27, 2025 am 12:03 AM

PythonListSarePartOfThestAndardarenot.liestareBuilting-in、versatile、forStoringCollectionsのpythonlistarepart。

スクリプトが間違ったPythonバージョンで実行されるかどうかを確認する必要がありますか?スクリプトが間違ったPythonバージョンで実行されるかどうかを確認する必要がありますか?Apr 27, 2025 am 12:01 AM

theScriptisrunningwithwrongthonversionduetorectRectDefaultEntertersettings.tofixthis:1)CheckthedededefaultHaulthonsionsingpython - versionorpython3-- version.2)usevirtualenvironmentsbycreatingonewiththon3.9-mvenvmyenv、andverixe

Pythonアレイで実行できる一般的な操作は何ですか?Pythonアレイで実行できる一般的な操作は何ですか?Apr 26, 2025 am 12:22 AM

PythonArraysSupportVariousoperations:1)SlicingExtractsSubsets、2)Appending/ExtendingAdddesements、3)inSertingSelementSatspecificpositions、4)remvingingDeletesements、5)sorting/verversingsorder、and6)listenionsionsionsionsionscreatenewlistsebasedexistin

一般的に使用されているnumpy配列はどのようなアプリケーションにありますか?一般的に使用されているnumpy配列はどのようなアプリケーションにありますか?Apr 26, 2025 am 12:13 AM

numpyarraysAressertialentionsionceivationsefirication-efficientnumericalcomputations andDatamanipulation.theyarecrucialindatascience、mashineelearning、物理学、エンジニアリング、および促進可能性への適用性、scaledatiencyを効率的に、forexample、infinancialanalyyy

Pythonのリスト上の配列を使用するのはいつですか?Pythonのリスト上の配列を使用するのはいつですか?Apr 26, 2025 am 12:12 AM

UseanArray.ArrayOverAlistinPythonは、Performance-criticalCode.1)homogeneousdata:araysavememorywithpedelements.2)Performance-criticalcode:Araysofterbetterbetterfornumerumerumericaleperations.3)interf

すべてのリスト操作は配列でサポートされていますか?なぜまたはなぜですか?すべてのリスト操作は配列でサポートされていますか?なぜまたはなぜですか?Apr 26, 2025 am 12:05 AM

いいえ、notallistoperationSaresuptedbyarrays、andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorintorintorinsertizizing、whosimpactsporformance.2)リスト

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

PhpStorm Mac バージョン

PhpStorm Mac バージョン

最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

mPDF

mPDF

mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません