做者:xiaoyu
微信公衆號:Python數據科學
知乎:python數據分析師python
有不少朋友問我學習了Python後,有沒有什麼好的項目能夠練手。web
其實,作項目主要仍是根據需求來的。可是對於一個初學者來講,不少複雜的項目沒辦法獨立完成,所以博主挑選了一個很是適合初學者的項目,內容不是很複雜,可是很是有趣,我相信對於初學者小白來講是再好不過的項目了。json
這個項目中,咱們將要創建一個比特幣價格的提醒服務。api
HTTP
的請求,以及如何使用requests
包來發送這些請求。webhooks
和如何使用它將Python app與外部設備鏈接,例如移動端手機提醒或者 Telegram 服務。僅僅不到50行的代碼就能完成一個比特幣價格提醒服務的功能,而且能夠輕鬆的擴展到其它加密數字貨幣和服務中。微信
下面咱們立刻來看看。app
咱們都知道,比特幣是一個變更的東西。你沒法真正的知道它的去向。所以,爲了不咱們反覆的刷新查看最新動態,咱們能夠作一個Python app來爲你工做。編輯器
爲此,咱們將會使用一個很流行的自動化網站IFTTT
。IFTTT("if this, then that")是一個能夠在不一樣app設備與web服務之間創建鏈接橋樑的工具。函數
咱們將會建立兩個IFTTT applets:工具
兩個程序都將被咱們的Python app觸發,Python app從Coinmakercap API
(https://coinmarketcap.com/api/) 獲取數據。post
一個IFTTT程序有兩個部分組成:觸發部分和動做部分。
在咱們的狀況下,觸發是一個IFTTT提供的webhook服務。你能夠將webhook想象爲"user-defined HTTP callbacks",更多請參考:http://timothyfitz.com/2009/0...
咱們的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以前,咱們須要建立一個新帳戶(https://ifttt.com/join),而後安裝移動端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...
關注微信公衆號Python數據科學,獲取 120G
人工智能 學習資料。