After learning Python, what projects can you practice?

Posted by Eric_Ryk on Fri, 10 Dec 2021 08:12:18 +0100

Many friends asked me if there were any good projects to practice after learning Python.

In fact, projects are mainly based on needs. But for a beginner, many complex projects cannot be completed independently, so the blogger chose a project that is very suitable for beginners. The content is not very complex, 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 learn about HTTP requests and how to use the requests package to send these requests.
  • At the same time, you will learn about webhooks and how to use it to connect Python app to external devices, such as mobile phone reminder or telegraph 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.

Now let's have a look.

Bitcoin price reminder with Python

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 and viewing the latest developments, we can make a Python app to work for you.

For this purpose, we will use a very popular automated website IFTTT. IFTTT("if this, then that") is a tool that can build a bridge between different app devices and web services.

We will create two IFTTT applets:

  • One is an emergency reminder when the bitcoin price drops to a certain threshold
  • The other is the update of the conventional bitcoin price

Both programs will be triggered by our Python app, which obtains data from the Coinmakercap API point.

An IFTTT program consists of two parts: trigger part and action part.

In our case, the trigger is a webhook service provided by IFTTT. You can think of webhook as "user defined HTTP callbacks".

Our Python app will issue an HTTP request to the webhook URL, and then the webhook URL 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 installed Python 3, just install another requests package.

$ 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 very simple and can be implemented in the console. Import the requests package and define bitcoin_api_url variable, which is the URL of Coinmarketcap API.

Next, use requests The get () function sends an HTTP GET request and saves the response. Since the API returns a JSON response, we can json() converts 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'} 

Send a test IFTTT reminder

Now we can go to IFTTT. Before using IFTTT, we need to create a new account IFTTT, and then install the mobile app (if you want to be notified on the mobile phone). After setting successfully, we will start to create a new IFTTT applet for testing.

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

  1. Click the big "this" button;
  2. Search the "webhooks" service and select "Receive a web request" to trigger;
  3. Rename event to test_event;
  4. Then select the large "that" button;
  5. Search for the "notifications" service and select "send a notification from the IFTTT app"
  6. Change the SMS to I just triggered my first IFTTT action!, Then click "Create action";
  7. Click "Finish" 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 replace {event} with your own name in step 3. {your IFTTT key} is an existing IFTTT key.

Now you can copy the webhook URL and open another console. Similarly, import requests and 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:

Create IFTTT Applets

It's just a test. Now we've reached the main part. Before starting the code again, we need to create two new IFTTT applets: one is the emergency notification of bitcoin price, and the other is the regular update.

applet for bitcoin price emergency notification:

  1. Select the "webhooks" service and select the trigger of "Receive a web request";
  2. Name an event bitcoin_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 the SMS to bitcoin price is at ${{Value1}} Buy or sell now! (we'll return to the {{Value1}} section later)
  6. Create an action, and then complete the setting of the applet;

applet for general price update:

  1. Similarly, select the "webhooks" service and select the trigger of "Receive a web request";
  2. Name an event bitcoin_price_update;
  3. For the action part of the response, select the "telegraph" service, and then continue to select the "Send message" action;
  4. Set the text of SMS message as: Latest bitcoin prices:
    {{Value1}};
  5. Create an action, and then complete the setting of the applet;

Connect all together

Now that we have IFTTT, here is the code. You'll start by creating a standard Python command line app skeleton like the following. Code and save it as bitcoin_notifications.py:

import requests
import time
from datetime import datetime

def main():
    pass

if __name__ == '__main__':
    main()

Next, we will also convert the codes of the first two Python console parts into two functions, which will return the price of the latest bitcoin, and then post them to IFTTT's webhook 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_price hasn't changed much. psot_ifttt_webhook requires two parameters: event and value.

The event 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.

This is why we need the value parameter: when setting our applet, we have a {{Value1}} tag in the information text. This tag will be replaced by the values1 text in the JSON payload. requests. The post () function allows us to send additional JSON data by setting the JSON keyword.

Now we can continue to the core main function code of our app. It includes a while True loop, because we want the app to run forever. In the loop, we call the coinmarkercap API to get the price of the latest bitcoin 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 updates, we will put the current price and date into a bitcoin_ In the history list. Once the list reaches a certain number (say 5), we will wrap it, send the update, and then reset the history for subsequent updates.

One thing to note is to avoid sending messages too often for two reasons:

  • The Coinmarketcap API states that they only update every 5 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 almost succeeded. But a format is missing_ bitcoin_history function. It will bitcoin_history as a parameter, and then use the basic HTML tags allowed by telegraph (like
, etc.) transform the format. 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:

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 off in the app.

Topics: PHP Python