搜尋
首頁後端開發Python教學在 Python 中建立 Stripe 測試數據

我們一直在致力於一門新的AI 數據課程,向您展示如何透過將電子商務數據從Stripe 移動到在Supabase 上運行的PGVector 來構建AI 聊天機器人,透過Airbyte PGVector 連接器創建OpenAI 嵌入,使用OpenAI 用戶端程式庫將自然語言支援新增至應用程式。這是我們的許多客戶正在實施的一種非常常見的「智慧資料堆疊」應用程式模式。來源和目的地可能會發生變化,但模式(資料來源 > 行動資料並建立嵌入 > 支援向量的資料儲存 > 使用 OpenAI 的 Web 應用程式)保持不變。

Creating Stripe Test Data in Python

由於我們正在開發旨在讓人們上手的課程,因此我們希望讓設定盡可能簡單。其中很大一部分是在 Stripe 中創建足夠的測試數據,這樣就有一個合理的數據集供聊天機器人與之互動。如果您以前使用過 Stripe,您就會知道他們有一個很棒的沙盒,您可以在其中進行試驗。唯一的問題是它沒有預先載入範例資料。

您可以透過 CLI 裝置指令載入一些範例資料集。但是,對於我們的使用來說,這些都不符合需求。我們想要一個更大的數據集,並且由於這些材料將在線上和研討會中使用,因此要求學習者在他們的本地電腦上安裝一些東西,例如CLI,會讓你面臨一大堆複雜的處理。您永遠不知道用戶正在運行什麼作業系統版本,他們是否擁有正確的安裝權限等等。我已經被燒傷太多次了,無法走這條路。

值得慶幸的是,Stripe 還擁有出色的 API 和出色的 Python 客戶端,這意味著我們可以快速創建協作筆記本,供學習者運行和插入我們想要的資料。

透過 !pip install stripe 安裝 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 後,透過使用 Connector Builder 將 API 端點對應到每種資料類型的串流並設定同步作業,將其連接到 Airbyte 只需幾分鐘。

Creating Stripe Test Data in Python

問題解決了!我們的 Collab Python 腳本對於學習者來說非常容易將測試資料插入 Stripe 中。希望對其他進行類似測試的人有所幫助。

以上是在 Python 中建立 Stripe 測試數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
可以在Python數組中存儲哪些數據類型?可以在Python數組中存儲哪些數據類型?Apr 27, 2025 am 12:11 AM

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

如果您嘗試將錯誤的數據類型的值存儲在Python數組中,該怎麼辦?如果您嘗試將錯誤的數據類型的值存儲在Python數組中,該怎麼辦?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Python標準庫的哪一部分是:列表或數組?Python標準庫的哪一部分是:列表或數組?Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

您應該檢查腳本是否使用錯誤的Python版本執行?您應該檢查腳本是否使用錯誤的Python版本執行?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

在Python陣列上可以執行哪些常見操作?在Python陣列上可以執行哪些常見操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些類型的應用程序中,Numpy數組常用?在哪些類型的應用程序中,Numpy數組常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什麼時候選擇在Python中的列表上使用數組?您什麼時候選擇在Python中的列表上使用數組?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中