This tutorial guides Python developers through the basics of Web3.py—a blockchain (Ethereum) library. We'll execute most steps directly in the Python interpreter.
Note: For safety, we'll perform transfers via a test network. The same techniques apply to the Ethereum mainnet.
Key Steps Overview
- Installation
- Establishing Connection
- Initialization
- Account Creation
- ENS Accounts
- Executing Transfers
1. Installation
Install Web3.py via pip:
pip3 install web3Verify your Python version if multiple installations exist:
pip3 -V # Ensure Python 3.x👉 Need help setting up Python environments?
2. Establishing Connection
To interact with the blockchain, you'll need:
- A self-hosted node or
- A service like Infura (free tier available).
Steps:
- Sign up for Infura and obtain an API endpoint (e.g.,
https://rinkeby.infura.io/v3/YOUR_API_KEY). - Use this endpoint to connect via Python.
3. Initialization
Launch Python and import required libraries:
from web3 import Web3, HTTPProvider
import jsonInitialize the connection:
w3 = Web3(Web3.HTTPProvider("https://rinkeby.infura.io/v3/YOUR_API_KEY"))Add middleware for Rinkeby compatibility:
from web3.middleware import geth_poa_middleware
w3.middleware_onion.inject(geth_poa_middleware, layer=0)Verify connectivity:
w3.isConnected() # Should return True4. Account Creation
Generate an Ethereum account:
my_account = w3.eth.account.create('Your_Entropy_String')
print(f"Address: {my_account._address}")
print(f"Private Key: {my_account._private_key.hex()}")Warning: Never expose private keys publicly in real scenarios. Use secure managers like MetaMask.
5. ENS Accounts
Ethereum Name Service (ENS) simplifies addresses (e.g., coogan.eth). While unusable on testnets, it’s valuable for mainnet transactions.
6. Executing Transfers
A. Smart Contract Setup
Interact with Dai stablecoin on Rinkeby:
Load ABI:
abi = '[{"constant":true,"inputs":[],"name":"name",...}]' # Full ABI copied earlier abi = json.loads(abi)Contract Address:
address = '0xc3dbf84Abb494ce5199D5d4D815b10EC29529ff8'Instantiate Contract:
dai = w3.eth.contract(address=address, abi=abi)
B. Building Transactions
Transfer 10 Dai:
transaction = dai.functions.transfer(
'RECIPIENT_ADDRESS', # Replace with target address
0x10 # 16 Dai in hex
).buildTransaction({
'chainId': 4, # Rinkeby
'gas': 70000,
'nonce': w3.eth.getTransactionCount(my_account._address)
})C. Signing and Sending
signed_txn = w3.eth.account.signTransaction(transaction, my_account._private_key)
txn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
print(f"Transaction Hash: {txn_hash.hex()}")Track your transaction on Etherscan Rinkeby.
👉 Explore advanced Web3.py techniques
FAQ Section
Q1: Why use a testnet instead of mainnet?
A1: Testnets allow risk-free experimentation without real financial losses.
Q2: How do I get testnet Dai?
A2: Use Rinkeby faucets like Chainlink Faucet.
Q3: What’s the gas fee for testnet transactions?
A3: Testnet gas costs nothing since it uses fake ETH.
Q4: Can I use ENS on Rinkeby?
A4: No, ENS domains are mainnet-only.
Q5: How secure is account generation via Web3.py?
A5: Secure for testing, but use hardware wallets like Ledger for mainnet.
Conclusion
Web3.py empowers developers to build Python-based blockchain applications seamlessly. Start with testnets, master the basics, and gradually transition to mainnet deployments.