Brownie v1.17.2 - Python development framework for Ethereum
TokenProject is the active project.
Attached to local RPC client listening at '127.0.0.1:8545'...
Running 'scripts/deploy.py::main'...
Transaction sent: 0x28fe8322442356b1ea88fe80925973a53dcae1a651dfa01558607bedc4b4f00c
Gas price: 0.0 gwei Gas limit: 6721975 Nonce: 0
KongLongNFT.constructor confirmed Block: 1 Gas used: 1421519 (21.15%)
KongLongNFT deployed at: 0x684f51E9A4Ec41DDaC067A9E03eECad3274F4FDd
Contract deployed to 0x684f51E9A4Ec41DDaC067A9E03eECad3274F4FDd
$ brownie console
Brownie v1.17.2 - Python development framework for Ethereum
TokenProject is the active project.
/Users/jim/.local/pipx/venvs/eth-brownie/lib/python3.9/site-packages/brownie/network/main.py:44: BrownieEnvironmentWarning: Development network has a block height of 2
warnings.warn(
Attached to local RPC client listening at '127.0.0.1:8545'...
Brownie environment is ready.
>>>
$ brownie compile
Brownie v1.17.2 - Python development framework for Ethereum
Project has been compiled. Build artifacts saved at /xxxxxxxx/build/contracts
如果有問題的話,會在 console 列出來有問題的行數
CompilerError: solc returned the following errors:
ParserError: Expected '(' but got identifier
--> contracts/KongLongNFT.sol:33:14:
|
33 | function getCurrentTokenId() public view returns (uint256) {
| ^^^^^^^^^^^^^^^^^
Brownie v1.17.2 - Python development framework for Ethereum
Attached to local RPC client listening at '127.0.0.1:8545'...
Brownie environment is ready.
>>> network.is_connected()
True
回 True 表示連線成功!可以進行 RPC 操作。
其中 brownie 貼心的是,如果他發現 local 沒有啟動 ganche-cli,他還會自動幫你啟動!
Brownie v1.17.2 - Python development framework for Ethereum
Launching 'ganache-cli --accounts 10 --hardfork istanbul --gasLimit 12000000 --mnemonic brownie --port 8545'...
Brownie environment is ready.
>>>
def find_pkgs(pkg_keyword):
result = subprocess.check_output([PKG_UTIL, PKGS]).decode()
return [r for r in result.split('\n') if pkg_keyword.lower() in r.lower()]
得到 pkg 完整名稱,再用 find_location() 找出他們所在位置,包裝這個指令:
$ pkgutil --pkg-info <完整套件名稱>
此函數會把 volume 和 location 拼接在一起回傳完整的路徑。
如果有多個套件,可用 for loop 多次呼叫函數批次抓回來,不用像以往人工多次輸入查詢。
def find_location(pkg_name):
volume = ''
location = ''
result = subprocess.check_output([PKG_UTIL, PKG_INFO, pkg_name]).decode()
for line in result.split('\n'):
if VOLUME in line:
volume = line.replace(VOLUME, '')
elif LOCATION in line:
location = line.replace(LOCATION, '')
return f'{volume}{location}'
與同事討論後,他說他之前也遇過類似的問題,那時的原因是他在 test 裡把一些 access db 的 code 寫在某些地方,導致 db 還沒建立就去 access db 而發生類似的錯誤。
仔細檢查這次的修改,發現在某些 class 的 __init__ 裡面增加了 default 設定
class AdvanceInvoiceUpdateHandler():
def __init__(self, user, voucher_service=VoucherService()): # set default value
self.user = user
self.voucher_service = voucher_service
而在 VoucherService 的 __init__ 裡面我們有 access db
class VoucherService():
def __init__(self):
company = Company.get_current_company() # access db
class VoucherService():
def __init__(self):
print(‘I am the ghost.’’)
...
再跑一次測試,果然看到 「I am the ghost.」出現在錯誤訊息之前
做以下修改解決錯誤,把 default VoucherService 往內放即可
class AdvanceInvoiceCreateHandler():
def __init__(self, user, voucher_service=None):
self.user = user
self.voucher_service = voucher_service or VoucherService()
這讓我好奇 python 中 function default arguments 的規則,於是上網研究了下,得到以下結論
python 的函數是物件
python 的 def 是「可執行陳述式」
default arguments 的值會在「跑 def 陳述」時被建立
mutable object 做 default value 的時候,不能寫在 arguments 旁邊,要到 function 裡面去處理
SELECT * FROM test_score ORDER BY date desc, id LIMIT 1;
多了一個對 id sort 的描述。這在有些情況結果就會和我們預期的不同。
原理
詳細查看兩家的 doc,在 SQLAlchemy 對 first() 函數這麼說:
Return the first result of this Query or None if the result doesn’t contain any row.
first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present).
意思是說,他的 first 函數是在 SQL 中增加 LIMIT 1 。
那回頭來看 GORM 呢?
Get the first record ordered by primary key
就這麼簡單一句話XD。如果使用 GORM 的 First,他預設會對 pk 做 order 再取 LIMIT 1。
def _filter_records(self, cgms: List[Cgm], start_datetime: datetime, end_datetime: datetime) -> List[dict]:
records = []
# 過濾
for cgm in cgms:
# filter records which is in this time range
filtered_records = filter(
lambda r:
arrow.get(r['datetime']).datetime >= start_datetime and
arrow.get(r['datetime']).datetime <= end_datetime,
cgm.records
)
records += list(filtered_records)
# 去除重複
deduplicated_records = []
datetime_set = set()
for record in records:
if record['datetime'] not in datetime_set:
datetime_set.add(record['datetime'])
deduplicated_records.append(record)
# 回傳排序好的陣列
return sorted(deduplicated_records, key=lambda r: arrow.get(r['datetime']).datetime)
records = []
datetime_map = {}
# 因為 datetime 轉換很花時間,所以先轉一次緩存起來
for cgm in cgms:
for record in cgm.records:
datetime_map[record['datetime']] = arrow.get(record[‘datetime’]).datetime
for cgm in cgms:
# filter records which is in this time range
filtered_records = filter(
lambda r:
datetime_map.get(r['datetime']) >= start_datetime and
datetime_map.get(r['datetime']) <= end_datetime,
cgm.records
)
records += list(filtered_records)
# 因為 datetime 轉換很花時間,所以先轉一次緩存起來
for cgm in cgms:
for record in cgm.records:
datetime_map[record['datetime']] = datetime.strptime(record['datetime'], '%Y-%m-%dT%H:%M:%S%z')
def _filter_records(self, cgms: List[Cgm], start_datetime: datetime, end_datetime: datetime) -> List[dict]:
records = []
datetime_map = {}
# 因為 datetime 轉換很花時間,所以先轉一次緩存起來
# 且這邊用原生函數轉換,會比 arrow 快很多
for cgm in cgms:
for record in cgm.records:
datetime_map[record['datetime']] = datetime.strptime(record['datetime'], '%Y-%m-%dT%H:%M:%S%z')
for cgm in cgms:
# filter records which is in this time range
filtered_records = filter(
lambda r:
datetime_map.get(r['datetime']) >= start_datetime and
datetime_map.get(r['datetime']) <= end_datetime,
cgm.records
)
records += list(filtered_records)
deduplicated_records = []
datetime_set = set()
for record in records:
if record['datetime'] not in datetime_set:
datetime_set.add(record['datetime'])
deduplicated_records.append(record)
deduplicated_records = deduplicated_records.sort(deduplicated_records, key=lambda r: datetime_map.get(r['datetime']))
return deduplicated_records