对于python初学者有哪些项目可以用来练练手( 三 )

接着,我们还要将前面两个Python console部分的代码转换为两个函数,函数将返回最近比特币的价格,然后将它们分别post到IFTTT的webhook上去。将下面的代码加入到main()函数之上。
BITCOIN_API_URL = \u0026#39;https://api.coinmarketcap.com/v1/ticker/bitcoin/\u0026#39;IFTTT_WEBHOOKS_URL = \u0026#39;https://maker.ifttt.com/trigger/{}/with/key/{your-IFTTT-key}\u0026#39;def get_latest_bitcoin_price(): response = requests.get(BITCOIN_API_URL) response_json = response.json() # Convert the price to a floating point numberreturn float(response_json)def post_ifttt_webhook(event, value): # The payload that will be sent to IFTTT service data = https://www.zhihu.com/api/v4/questions/27674460/{/u0026#39;value1/u0026#39;: value} # inserts our desired event ifttt_event_url = IFTTT_WEBHOOKS_URL.format(event) # Sends a HTTP POST request to the webhook URL requests.post(ifttt_event_url, json=data)除了将价格从一个字符串变成浮点数之外,get_latest_bitcoin_price基本没太变。psot_ifttt_webhook需要两个参数:eventvalue
event参数与我们之前命名的触发名字对应。同时,IFTTT的webhooks允许我们通过requests发送额外的数据,数据作为JSON格式。
这就是为什么我们需要value参数:当设置我们的applet的时候,我们在信息文本中有{{Value1}}标签。这个标签会被 JSON payload 中的values1文本替换。requests.post()函数允许我们通过设置json关键字发送额外的JSON数据。
现在我们可以继续到我们app的核心main函数码代码了。它包括一个while True的循环,由于我们想要app永远的运行下去。在循环中,我们调用Coinmarkertcap API来得到最近比特币的价格,并且记录当时的日期和时间。
根据目前的价格,我们将决定我们是否想要发送一个紧急通知。对于我们的常规更新我们将把目前的价格和日期放入到一个bitcoin_history的列表里。一旦列表达到一定的数量(比如说5个),我们将包装一下,将更新发送出去,然后重置历史,以为后续的更新。
一个需要注意的地方是避免发送信息太频繁,有两个原因:
Coinmarketcap API 声明他们只有每隔5分钟更新一次,因此更新太频也没有用如果你的app发送太多的请求道 Coinmarketcap API,你的IP可能会被ban因此,我们最后加入了 "go to sleep" 睡眠,设置至少5分钟才能得到新数据。下面的代码实现了我们的需要的特征:
BITCOIN_PRICE_THRESHOLD = 10000 # Set this to whatever you likedef main(): bitcoin_history = while True: price = get_latest_bitcoin_price() date = datetime.now() bitcoin_history.append({\u0026#39;date\u0026#39;: date, \u0026#39;price\u0026#39;: price}) # Send an emergency notificationif price \u0026lt; BITCOIN_PRICE_THRESHOLD: post_ifttt_webhook(\u0026#39;bitcoin_price_emergency\u0026#39;, price) # Send a Telegram notification # Once we have 5 items in our bitcoin_history send an updateif len(bitcoin_history) == 5: post_ifttt_webhook(\u0026#39;bitcoin_price_update\u0026#39;, format_bitcoin_history(bitcoin_history)) # Reset the history bitcoin_history = # Sleep for 5 minutes # (For testing purposes you can set it to a lower number) time.sleep(5 * 60)


推荐阅读