Best practice project for Python beginners

Time:2020-11-1

Author: Xiaoyu
The official account of WeChat:Python Data Science
Zhihu:Python Data Analyst


Many friends have asked me if there is any good project to practice after learning python.

In fact, the project is mainly based on the needs. But for a beginner, many complex projects can not be completed independently, so the blogger selected a project that is very suitable for beginners. The content is not very complicated, but it is very interesting. I believe it is the best project for beginners Xiaobai.

In this project, we will establish a bitcoin price reminder service.

  • You will mainly learnHTTPAnd how to use itrequestsPackage to send these requests.
  • At the same time, you will understandwebhooksAnd how to use it to connect Python app with external devices, such as mobile phone reminder or telegram service.

Only less than 50 lines of code can complete the function of a bitcoin price reminder service, and can be easily extended to other encrypted digital currencies and services.

Let’s take a look at it right now.

Using Python to realize bitcoin price reminder

We all know that bitcoin is a changing thing. You can’t really know where it’s going. Therefore, in order to avoid us repeatedly refreshing to see the latest news, we can make a python app to work for you.

For this, we will use a popular automation websiteIFTTT。IFTTT(“if this, then that”)It is a tool that can build a bridge between different app devices and web services.

We will create two ifttt applets:

  • One is an urgent reminder when bitcoin prices fall to a certain threshold
  • The other is the update of the regular bitcoin price

Both programs will be triggered by our Python app, which starts fromCoinmakercap API (https://coinmarketcap.com/api/)Get the data.

An ifttt program consists of two partsTrigger partandAction part

In our case, the trigger is a webhook service provided by ifttt. You can think of webhook as“user-defined HTTP callbacksFor more information, please refer to:http://timothyfitz.com/2009/0…

Our Python app will send an HTTP request to the webhook URL, which will trigger the action. Here comes the interesting part. This action can be anything you want. Ifttt provides many actions, such as sending an email, updating a Google Spreadsheet, and even calling you.

Configuration item

If you have Python 3 installed, just install one morerequestsJust a bag.

$ pip install requests==2.18.4  # We only need the requests package

Select an editor, such as pychar, to edit the code.

Get bitcoin price

The code is simple and can be done in the console. ImportrequestsPackage, and then definebitcoin_api_urlVariable, which is the URL of the coinmarketcap API.

Next, userequests.get()Function sends an HTTP get request and saves the response. Since the API returns a JSON response, we can use the.json()Convert it to a python object.

>>> 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'}

What we are interested in above isprice_usd

Send an ifttt reminder for the test

Now we can go to ifttt. Before using ifttt, we need to create a new account(https://ifttt.com/join), then install the mobile app (if you want to be notified on your phone)
After the setup is successful, a new ifttt applet is created for testing.

To create a new test applet, you can follow the steps below:

  1. Click the big “this” button;
  2. Search for “webhooks” service and select “receive a web request” to trigger;
  3. Rename event totest_event;
  4. Then select the big “that” button;
  5. Search for the “notifications” service and select “send a notification from the ifttt app”
  6. Change SMS toI just triggered my first IFTTT action!, and then click “create action”;
  7. Click the “finish” button to finish;

To see how to use ifttt webhooks, click the “documentation” button. The documentation page has the URL of webhooks.

https://maker.ifttt.com/trigger/{event}/with/key/{your-IFTTT-key}

Next, you need to{event}Replace with your own name in step 3.{your-IFTTT-key}It’s the ifttt key that you already have.

Now you can copy the webhook URL and open another console. Also importrequestsThen send a post request.

>>> 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]>

After running, you can see:

Best practice project for Python beginners

Create ifttt applets

The front is just a test, now we have reached the main part. Before we start the code again, we need to create two new ifttt applets: one is an urgent notification of bitcoin prices, and the other is a regular update.

Bitcoin price emergency notification applet:

  1. Select the “webhooks” service and select the trigger of “receive a web request”;
  2. Name an event event asbitcoin_price_emergency;
  3. For the action part of the response, select the “notifications” service, and then continue to select the “send a rich notification from the ifttt app” action;
  4. Provide a title like “bitcoin price emergency!”
  5. Set SMS toBitcoin price is at ${{Value1}}. Buy or sell now!We will return to{{Value1}}Part)
  6. Alternatively, you can add a URL link to the coinmarketcap bitcoin page:https://coinmarketcap.com/currencies/bitcoin/;
  7. Create actions, and then complete the applet settings;

Regular price update applet:

  1. Similarly, select the “webhooks” service and select the trigger of “receive a web request”;
  2. Name an event event asbitcoin_price_update;
  3. For the action part of the response, select the “telegram” service, and then continue to select the “send message” action;
  4. Set SMS text to:Latest bitcoin prices:<br>{{Value1}}
  5. Create actions, and then complete the applet settings;

Connect it all together

Now that we have ifttt, here’s the code. You’ll start by creating a standard Python command-line app skeleton like the one below. Code it and save it asbitcoin_notifications.py:

import requests
import time
from datetime import datetime

def main():
    pass

if __name__ == '__main__':
    main()

Next, we need to convert the code of the previous two Python console parts into two functions, which will return the latest bitcoin price, and then post them to the webhook of ifttt respectively. Add the following code to the main() function.

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)

In addition to changing the price from a string to a floating-point number,get_latest_bitcoin_priceIt hasn’t changed much.psot_ifttt_webhookTwo parameters are required:eventandvalue

eventThe parameter corresponds to the trigger name we named earlier. At the same time, ifttt’s webhooks allow us to send additional data through requests as JSON format.

That’s why we need tovalueParameter: when setting our applet, we have{{Value1}}label. This tag will be used in JSON payloadvalues1Text replacement.requests.post()Function allows us to set thejsonKeyword to send additional JSON data.

Now we can go on to the main function code of our app. It includes awhile TrueBecause we want the app to run forever. In the loop, we call the coinmarkercap API to get the latest bitcoin price and record the date and time at that time.

Based on the current price, we will decide whether we want to send an urgent notice. For our regular update, we will put the current price and date into abitcoin_historyIn the list. Once the list reaches a certain number (say, five), we’ll wrap it up, send the updates out, and reset the history for subsequent updates.

There are two reasons to avoid sending messages too frequently

  • The coinmarketcap API states that they are only updated every five minutes, so it’s useless to update too often
  • If your app sends too many requests to the coinmarketcap API, your IP may be ban

Therefore, we finally added “go to sleep” sleep and set it for at least 5 minutes to get new data. The following code implements the features we need:

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)

We’re almost there. But one is missingformat_bitcoin_historyFunction. It willbitcoin_historyAs a parameter, then use the basic HTML tags (like<br>, <b>, <i>And so on). Copy this function onto 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)

Finally, the result displayed on the mobile phone is as follows:

Best practice project for Python beginners

Then, our function is completed. As soon as the price of bitcoin is updated, the mobile terminal of the mobile phone will be prompted. Of course, if you are bored, you can also turn it off in the app.

reference resources:https://realpython.com/python…

WeChat official accountPython Data Science, get120GArtificial intelligence learning materials.

Best practice project for Python beginners

Best practice project for Python beginners