关于javascript:有很多朋友问我学习了Python后有没有什么好的项目可以练手

6次阅读

共计 6117 个字符,预计需要花费 16 分钟才能阅读完成。

有很多敌人问我学习了 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“,更多请参考: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 之前,咱们须要创立一个新账户 IFTTT,而后装置挪动端 app(如果你想在手机上接到告诉)设置胜利后就开始创立一个新的 IFTTT applet 用于测试。

创立一个新的测试 applet,能够按一下步骤进行:

  1. 点击大的 “this” 按钮;
  2. 搜寻 “webhooks” 服务,而后抉择 “Receive a web request” 触发;
  3. 重命名 event 为test_event;
  4. 而后抉择大的 “that” 按钮;
  5. 搜寻 “notifications” 服务,而后抉择 “send a notification from the IFTTT app”
  6. 扭转短信息为 I just triggered my first IFTTT action!,而后点击 “Create action”;
  7. 点击 “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:

  1. 抉择 “webhooks” 服务,并且抉择 “Receive a web request” 的触发;
  2. 命名一个事件 event 为 bitcoin_price_emergency;
  3. 对于响应的动作局部,抉择 “Notifications” 服务,而后持续抉择 “send a rich notification from the IFTTT app” 动作;
  4. 提供一个题目,像 “Bitcoin price emergency!”
  5. 设置短信息 为 Bitcoin price is at ${{Value1}}. Buy or sell now!(咱们一会儿将返回到 {{Value1}} 局部)
  6. 可选的,你能够退出一个 URL link 到 Coinmarketcap Bitcoin page:https://coinmarketcap.com/currencies/bitcoin/;
  7. 创立动作,而后实现 applet 的设置;

惯例价格更新的 applet:

  1. 一样的抉择 “webhooks” 服务,并且抉择 “Receive a web request” 的触发;
  2. 命名一个事件 event 为 bitcoin_price_update;
  3. 对于响应的动作局部,抉择 “Telegram” 服务,而后持续抉择 “Send message” 动作;
  4. 设置短信信息文本为:Latest bitcoin prices:<br>{{Value1}}
  5. 创立动作,而后实现 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须要两个参数: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 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 掉。

正文完
 0