做者:xiaoyupython
微信公众号:Python数据科学web
知乎:Python数据分析师json
有不少朋友问我学习了Python后,有没有什么好的项目能够练手。api
其实,作项目主要仍是根据需求来的。可是对于一个初学者来讲,不少复杂的项目没办法独立完成,所以博主挑选了一个很是适合初学者的项目,内容不是很复杂,可是很是有趣,我相信对于初学者小白来讲是再好不过的项目了。bash
这个项目中,咱们将要创建一个比特币价格的提醒服务。微信
你将主要会学习到HTTP
的请求,以及如何使用requests
包来发送这些请求。app
同时,你会了解webhooks
和如何使用它将Python app与外部设备链接,例如移动端手机提醒或者 Telegram 服务。编辑器
仅仅不到50行的代码就能完成一个比特币价格提醒服务的功能,而且能够轻松的扩展到其它加密数字货币和服务中。函数
下面咱们立刻来看看。工具
咱们都知道,比特币是一个变更的东西。你没法真正的知道它的去向。所以,为了不咱们反复的刷新查看最新动态,咱们能够作一个Python app来为你工做。
为此,咱们将会使用一个很流行的自动化网站IFTTT
。IFTTT**("if this, then that")**是一个能够在不一样app设备与web服务之间创建链接桥梁的工具。
咱们将会建立两个IFTTT applets:
两个程序都将被咱们的Python app触发,Python app从Coinmakercap API
点这里 获取数据。
一个IFTTT程序有两个部分组成:触发部分和动做部分。
在咱们的状况下,触发是一个IFTTT提供的webhook服务。你能够将webhook想象为"user-defined HTTP callbacks",更多请参考:WEBHOOK
咱们的Python app将会发出一个HTTP请求到webhook URL,而后webhook URL触发动做。有意思的部分来了,这个动做能够是你想要的任何东西。IFTTT提供了众多的动做像发送一个email,更新一个Google电子数据表,甚至能够给你打电话。
若是你安装了python3,那么只要再安装一个requests
包就能够了。
$ pip install requests==2.18.4 # We only need the requests package
复制代码
选一个编辑器,好比Pycharm进行代码编辑。
代码很简单,能够在console中进行。导入requests
包,而后定义bitcoin_api_url
变量,这个变量是Coinmarketcap API的URL。
接着,使用requests.get()
函数发送一个 HTTP GET请求,而后保存响应response。因为API返回一个JSON响应,咱们能够经过.json()
将它转换为python对象。
>>> import requests
>>> bitcoin_api_url = 'https://api.coinmarketcap.com/v1/ticker/bitcoin/'
>>> response = requests.get(bitcoin_api_url)
>>> response_json = response.json()
>>> type(response_json) # The API returns a list
<class 'list'>
>>> # Bitcoin data is the first element of the list
>>> response_json[0]
{'id': 'bitcoin', 'name': 'Bitcoin', 'symbol': 'BTC', 'rank': '1',
'price_usd': '10226.7', 'price_btc': '1.0', '24h_volume_usd': '7585280000.0',
'market_cap_usd': '172661078165', 'available_supply': '16883362.0',
'total_supply': '16883362.0', 'max_supply': '21000000.0',
'percent_change_1h': '0.67', 'percent_change_24h': '0.78',
'percent_change_7d': '-4.79', 'last_updated': '1519465767'}
复制代码
上面咱们感兴趣的是price_usd
。
如今咱们能够转到IFTTT上面来了。使用IFTTT以前,咱们须要建立一个新帐户IFTTT,而后安装移动端app(若是你想在手机上接到通知) 设置成功后就开始建立一个新的IFTTT applet用于测试。
建立一个新的测试applet,能够按一下步骤进行:
test_event
;I just triggered my first IFTTT action!
,而后点击 "Create action";要看如何使用IFTTT webhooks,请点击 "Documentation" 按钮documentation页有webhooks的URL。
https://maker.ifttt.com/trigger/{event}/with/key/{your-IFTTT-key}
复制代码
接着,你须要将{event}
替换为你在步骤3中本身起的名字。{your-IFTTT-key}
是已经有了的IFTTT key。
如今你能够复制webhook URL,而后开启另外一个console。一样导入requests
而后发送post请求。
>>> import requests
>>> # Make sure that your key is in the URL
>>> ifttt_webhook_url = 'https://maker.ifttt.com/trigger/test_event/with/key/{your-IFTTT-key}'
>>> requests.post(ifttt_webhook_url)
<Response [200]>
复制代码
运行完以后,你能够看到:
前面只是测试,如今咱们到了最主要的部分了。再开始代码以前,咱们须要建立两个新的IFTTT applets:一个是比特币价格的紧急通知,另外一个是常规的更新。
比特币价格紧急通知的applet:
bitcoin_price_emergency
;Bitcoin price is at ${{Value1}}. Buy or sell now!
(咱们一下子将返回到{{Value1}}
部分)https://coinmarketcap.com/currencies/bitcoin/
;常规价格更新的applet:
bitcoin_price_update
;Latest bitcoin prices:<br>{{Value1}}
;如今,咱们有了IFTTT,下面就是代码了。你将经过建立像下面同样标准的Python命令行app骨架来开始。 代码码上去,而后保存为 bitcoin_notifications.py
:
import requests
import time
from datetime import datetime
def main():
pass
if __name__ == '__main__':
main()
复制代码
接着,咱们还要将前面两个Python console部分的代码转换为两个函数,函数将返回最近比特币的价格,而后将它们分别post到IFTTT的webhook上去。将下面的代码加入到main()函数之上。
BITCOIN_API_URL = 'https://api.coinmarketcap.com/v1/ticker/bitcoin/'
IFTTT_WEBHOOKS_URL = 'https://maker.ifttt.com/trigger/{}/with/key/{your-IFTTT-key}'
def get_latest_bitcoin_price():
response = requests.get(BITCOIN_API_URL)
response_json = response.json()
# Convert the price to a floating point number
return float(response_json[0]['price_usd'])
def post_ifttt_webhook(event, value):
# The payload that will be sent to IFTTT service
data = {'value1': 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
须要两个参数:event
和value
。
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个),咱们将包装一下,将更新发送出去,而后重置历史,觉得后续的更新。
一个须要注意的地方是避免发送信息太频繁,有两个缘由:
所以,咱们最后加入了 "go to sleep" 睡眠,设置至少5分钟才能获得新数据。下面的代码实现了咱们的须要的特征:
BITCOIN_PRICE_THRESHOLD = 10000 # Set this to whatever you like
def main():
bitcoin_history = []
while True:
price = get_latest_bitcoin_price()
date = datetime.now()
bitcoin_history.append({'date': date, 'price': price})
# Send an emergency notification
if price < BITCOIN_PRICE_THRESHOLD:
post_ifttt_webhook('bitcoin_price_emergency', price)
# Send a Telegram notification
# Once we have 5 items in our bitcoin_history send an update
if len(bitcoin_history) == 5:
post_ifttt_webhook('bitcoin_price_update',
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)
复制代码
咱们几乎快成功了。可是还缺一个format_bitcoin_history
函数。它将bitcoin_history
做为参数,而后使用被Telegram容许的基本HTML标签(像<br>
, <b>
, <i>
等等)变换格式。将这个函数复制到main()之上。
def format_bitcoin_history(bitcoin_history):
rows = []
for bitcoin_price in bitcoin_history:
# Formats the date into a string: '24.02.2018 15:09'
date = bitcoin_price['date'].strftime('%d.%m.%Y %H:%M')
price = bitcoin_price['price']
# <b> (bold) tag creates bolded text
# 24.02.2018 15:09: $<b>10123.4</b>
row = '{}: $<b>{}</b>'.format(date, price)
rows.append(row)
# Use a <br> (break) tag to create a new line
# Join the rows delimited by <br> tag: row1<br>row2<br>row3
return '<br>'.join(rows)
复制代码
最后在手机上显示的结果是这样的:
而后,咱们的功能就完成了,只要比特币的价格一更新,手机移动端就有提示。固然,若是你嫌烦也能够在app里面off掉。
参考:https://realpython.com/python-bitcoin-ifttt/
关注微信公众号Python数据科学,获取 120G
人工智能 学习资料。