python操作web3_API--以太坊

web3.py文档:https://web3py.readthedocs.io/en/stable/quickstart.html

安装web3

(base) appledeMac-mini-3:Quantification apple$ pip  install  web3
Collecting web3
  Using cached https://files.pythonhosted.org/packages/cd/e3/46db98888fc36137fe88c09a3066b408108da8e434c7608028981504200b/web3-5.7.0-py3-none-any.whl
Collecting eth-typing<3.0.0,>=2.0.0 (from web3)
  Using cached https://files.pythonhosted.org/packages/bc/c4/c9c78597d0400e5bc1c3cdd031fdfa6629333a31591fcc5fa8519a7ea89c/eth_typing-2.2.1-py3-none-any.whl
Collecting eth-account<0.5.0,>=0.4.0 (from web3)
  Using cached https://files.pythonhosted.org/packages/08/b2/b000adde76e780ba072d75e534ebfe9d44f0d68f429d3757ae9a85e9bd0b/eth_account-0.4.0-py3-none-any.whl
Requirement already satisfied: requests<3.0.0,>=2.16.0 in /Users/apple/.local/lib/python3.7/site-packages (from web3) (2.22.0)
Collecting hexbytes<1.0.0,>=0.1.0 (from web3)

注册登录以太坊并创建一个项目获取项目id

https://infura.io/dashboard/ethereum

设置环境变量

# web3环境变量

export  WEB3_INFURA_PROJECT_ID=获取到的项目ID

使用该web3.auto.infura模块连接到Infura节点。

(base) appledeMac-mini-3:Quantification apple$ python
Python 3.7.3 (default, Mar 27 2019, 16:54:48) 
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from web3.auto.infura import w3
>>> w3.eth.blockNumber
9913260

w3,该实例现在将允许您与以太坊区块链进行交互

获取最新块的信息

>>> w3.eth.getBlock('latest')
AttributeDict({'difficulty': 2261993248924870, 'extraData': HexBytes('0x505059452d65746865726d696e652d6575312d35'), 'gasLimit': 9966590, 'gasUsed': 9954427, 'hash': HexBytes('0x64a043f893abcd0a8e424c64b4104660033eba1f018371ca4d3bec72bf23cc46'), 'logsBloom': HexBytes('0x08c24c5800c2201e0000a221708670036280c5012ca8409c18340ff1536800a4800c07e13210ac07060081740f5a0bc963820400099425c1282ac87120a10e2c18008d84b02080010405e66d808f6424e4132f86c1464200024302049cc430d14802a8160a2061c0d200507001a1482a8841f2011c0c1e22300405b424a6402025802b4c14642806b321a6ab8b020407200108436aa280828008088020313964a6c41062000281049c080ad64a8811918d042845c04e00a0086a8488988008d10620244693880d28840210115ee041420b04f00184080801f80000a217402306e85139035090188407600630c18122380c81185385b105e6ed2d120f389058c0'), 'miner': '0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8', 'mixHash': HexBytes('0xbe86772ffde4f025efae9dc14063d3a906f2f1ac675c8ce8e6a35725218e1d8a'), 'nonce': HexBytes('0xb18c36a40281d83a'), 'number': 9913288, 'parentHash': HexBytes('0xaa772d2645331b7d7e44286f398de7e0d3225afadd2fd54684e9d46ef71ac576'), 'receiptsRoot': HexBytes('0x7f0fa855dd4c7a9576d4ece8847dd87e82a77c25c9b733084e6f44f1940dbe4b'), 'sha3Uncles': HexBytes('0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'), 'size': 34719, 'stateRoot': HexBytes('0xbfc8504b7f8ad32e0763c18efced31c0ce9976944ea1f80322108f020621a1a2'), 'timestamp': 1587438028

将要执行的许多典型操作都在w3.ethAPI中web3对象通常通过连接到JSON-RPC服务器来提供与以太坊区块链进行交互的API

1.web3连接到区块链的方式

from web3 import Web3,HTTPProvider,IPCProvider,WebsocketProvider
"""
HTTPProvider:用于连接基于http和https的JSON-RPC服务器:通过完整的URI找到服务器
w3=Web3(HTTPProvider('http://loaclhost:8545'))
Web3.IPCProvider 用于连接到基于ipc套接字的JSON-RPC服务器:通过文件系统路径找到IPC套接字
w3 = Web3(IPCProvider(参数))
Web3.WebsocketProvider 用于连接到基于ws和wss websocket的JSON-RPC服务器:通过完整的URI找到服务器
w3 = Web3(WebsocketProvider('ws://127.0.0.1:8546'))
"""

w3=Web3(HTTPProvider('http://loaclhost:8545'))
print(w3)   # <web3.main.Web3 object at 0x105d42510

2.类型转化

# Web3.toHex(primary = None,hexstr = None,text = None )
# 接受各种输入并以其十六进制表示形式返回。它遵循JSON-RPC规范

# def to_hex(
#     primitive: Primitives = None, hexstr: HexStr = None, text: str = None
# ) -> HexStr:

print(Web3.toHex(10))  # 0xa

print(Web3.toHex(hexstr='0x00'))  # 0x00

print(Web3.toHex(text='asimov'))  # 0x6173696d6f76


# Web3.toText(primary = None,hexstr = None,text = None )
# 接受各种输入并返回其等效字符串。文本被解码为UTF-8。

print(Web3.toText('0x1254'))  #T
print(Web3.toText('0x6173696d6f76')) # asimov
print(Web3.toText(b'asim\x6f\x76'))  # asimov
print(Web3.toText('6173696d6f76')) # asimov

# Web3.toBytes(primary = None,hexstr = None,text = None )
# 接受各种输入并返回等效的字节数。文本被编码为UTF-8。

print(Web3.toBytes(0))    # b'\x00'
print(Web3.toBytes(b'sasas')) # b'sasas'
print(Web3.toBytes(hexstr='000F')) # b'\x00\x0f'
print(Web3.toBytes(hexstr='0x000F')) # b'\x00\x0f'
print(Web3.toBytes(text='asimov'))  # b'asimov'


# Web3.toInt(primary = None,hexstr = None,text = None )
# 接受各种输入并返回其等效的整数
print(Web3.toInt(0))   # 0
print(Web3.toInt(0x00f))  # 15
print(Web3.toInt(b'\x00\x0F')) # 15
print(Web3.toInt(hexstr='0x00F')) # 15
# ValueError: invalid literal for int() with base 10: 'sa'
# text: interpret as string of digits, like '12' => 12
print(Web3.toInt(text='10'))  # 10


# Web3.toJSON(obj)  obj: Dict[Any, Any]
# 接受各种输入并返回等效的JSON。
print(Web3.toJSON({'asimov':'da'}))  # {"asimov": "da"}

3. 货币换算

# to_wei(number: Union[int, float, str, decimal.Decimal], unit: str) -> int
# Takes a number of a unit and converts it to wei
# 转换为wei 的参数指定的面额返回值
print(Web3.toWei(1,'ether')) # 1000000000000000000

# from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]
# Takes a number of wei and converts it to any other ether unit
# 返回以wei转换为给定货币的值
print(Web3.fromWei(1000000000000000000,'ether'))  # 1

4.地址验证

# is_address(value: Any) -> bool
# 如果值是可识别的地址格式之一,则返回True
# 允许有0x前缀和无前缀的参数值。
# 如果地址包含大小写混合的字符,则此功能还会根据EIP55(区分大小写)检查地址校验和是否有效
print(Web3.isAddress('056cc3f68ed1c4f52bec72688f51789cb2000bac95'))  # False
print(Web3.isAddress('0xd3CdA913deB6f67967B99D67aCDFa1712C293601')) # True
print(Web3.isAddress('0xd3cdA913deB6f67967B99D67aCDFa1712C293601')) # False
print(Web3.isAddress('d3CdA913deB6f67967B99D67aCDFa1712C293601'))  # False

# is_checksum_address(value: Any) -> bool
# EIP55验证:区分地址的大小写
print(Web3.isChecksumAddress('0xd3CdA913deB6f67967B99D67aCDFa1712C293601'))  # True
print(Web3.isChecksumAddress('0xd3cdA913deB6f67967B99D67aCDFa1712C293601'))  # False

# to_checksum_address(value: AnyStr) -> ChecksumAddress
# EIP55校验地址,并返回EIP55给定的地址
print(Web3.toChecksumAddress('0xd3cdA913deB6f67967B99D67aCDFa1712C293601'))  # 0xd3CdA913deB6f67967B99D67aCDFa1712C293601
print(Web3.toChecksumAddress('d3cdA913deB6f67967B99D67aCDFa1712C293601'))    # 0xd3CdA913deB6f67967B99D67aCDFa1712C293601
print(Web3.toChecksumAddress('056cc3f68ed1c4f52bec72688f51789cb2000bac'))    # 0x056Cc3f68Ed1c4f52BeC72688F51789cb2000Bac
print(Web3.isAddress('0x056Cc3f68Ed1c4f52BeC72688F51789cb2000Bac'))  # True
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值