有很多敌人问我学习了Python后,有没有什么好的我的项目能够练手。
其实,做我的项目次要还是依据需要来的。然而对于一个初学者来说,很多简单的我的项目没方法独立实现,因而博主筛选了一个非常适合初学者的我的项目,内容不是很简单,然而十分乏味,我置信对于初学者小白来说是再好不过的我的项目了。
这个我的项目中,咱们将要建设一个比特币价格的揭示服务。
- 你将次要会学习到HTTP的申请,以及如何应用requests包来发送这些申请。
- 同时,你会理解webhooks和如何应用它将Python app与外部设备连贯,例如挪动端手机揭示或者 Telegram 服务。
仅仅不到50行的代码就能实现一个比特币价格揭示服务的性能,并且能够轻松的扩大到其它加密数字货币和服务中。
上面咱们马上来看看。
用Python实现比特币价格揭示
咱们都晓得,比特币是一个变动的货色。你无奈真正的晓得它的去向。因而,为了防止咱们重复的刷新查看最新动静,咱们能够做一个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“。
咱们的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'}
发送一个测试的IFTTT揭示
当初咱们能够转到IFTTT下面来了。应用IFTTT之前,咱们须要创立一个新账户IFTTT,而后装置挪动端app(如果你想在手机上接到告诉) 设置胜利后就开始创立一个新的IFTTT applet用于测试。
创立一个新的测试applet,能够按一下步骤进行:
- 点击大的 “this” 按钮;
- 搜寻 “webhooks” 服务,而后抉择 “Receive a web request”触发;
- 重命名event为test_event;
- 而后抉择大的 “that” 按钮;
- 搜寻 “notifications” 服务,而后抉择 “send a notification from the IFTTT app”
- 扭转短信息为 I just triggered my first IFTTT action!,而后点击 “Create action”;
- 点击 “Finish” 按钮,实现;
要看如何应用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
后面只是测试,当初咱们到了最次要的局部了。再开始代码之前,咱们须要创立两个新的IFTTT applets:一个是比特币价格的紧急通知,另一个是惯例的更新。
比特币价格紧急通知的applet:
- 抉择 “webhooks” 服务,并且抉择 “Receive a web request” 的触发;
- 命名一个事件 event 为 bitcoin_price_emergency;
- 对于响应的动作局部,抉择 “Notifications”服务,而后持续抉择 “send a rich notification from the IFTTT app” 动作;
- 提供一个题目,像 “Bitcoin price emergency!”
- 设置短信息 为 Bitcoin price is at ${{Value1}}. Buy or sell now!(咱们一会儿将返回到{{Value1}}局部)
- 创立动作,而后实现applet的设置;
惯例价格更新的applet:
- 一样的抉择 “webhooks” 服务,并且抉择 “Receive a web request” 的触发;
- 命名一个事件 event 为 bitcoin_price_update;
- 对于响应的动作局部,抉择 “Telegram” 服务,而后持续抉择 “Send message” 动作;
- 设置短信信息文本为:Latest bitcoin prices:
{{Value1}}; - 创立动作,而后实现applet的设置;
将所有连到一起
当初,咱们有了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个),咱们将包装一下,将更新发送进来,而后重置历史,认为后续的更新。
一个须要留神的中央是防止发送信息太频繁,有两个起因:
- Coinmarketcap API 申明他们只有每隔5分钟更新一次,因而更新太频也没有用
- 如果你的app发送太多的申请道 Coinmarketcap API,你的IP可能会被ban
因而,咱们最初退出了 “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标签(像
, , 等等)变换格局。将这个函数复制到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掉。