程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[basic tutorial for beginners of Python] the best hand training program for beginners of Python

編輯:Python

Preface

Actually , 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 complicated , But it's very interesting , I believe it is the best project for beginners Xiaobai .

In this project , We're going to set up a bitcoin price reminder service .

  • You will mainly learn HTTP Request , And how to use it requests Package to send these requests .
  • meanwhile , You will understand webhooks And how to use it will Python app Connect to external devices , For example, mobile phone reminder or Telegram service .

Less than 50 Line of code can complete the function of a bitcoin price reminder service , And it can be easily extended to other encrypted digital currencies and services .

Now let's take a look at .

use Python Realize bitcoin price reminder

We all know , Bitcoin is a changing thing . You can't really know where it's going . therefore , In order to avoid repeated refresh and check the latest developments , We can make a Python app To work for you .

So , We will use a popular automated website IFTTT.IFTTT**("if this, then that")** Is one that can be in different app Equipment and web Tools to build bridges between 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 used by us Python app Trigger ,Python app from Coinmakercap API Click here get data .

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

In our case , The trigger is a IFTTT Provided webhook service . You can take webhook Imagine as "user-defined HTTP callbacks", Please refer to :WEBHOOK

our Python app Will send a HTTP Ask to webhook URL, then webhook URL Trigger action . Here comes the interesting part , This action can be anything you want .IFTTT Provides many actions like sending a email, Update one Google Spreadsheet , I can even call you .

Configuration items

If you install it python3, Then just install another requests A bag will do .

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

Choose an editor , such as Pycharm Edit the code .

Get bitcoin price

The code is simple , Can be in console In the middle of . Import requests package , Then define bitcoin_api_url Variable , This variable is Coinmarketcap API Of URL.

next , Use requests.get() Function to send a HTTP GET request , Then save the response response. because API Return to one JSON Respond to , We can go through .json() Convert it to 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 is price_usd.

Send a test IFTTT remind

Now we can go to IFTTT Here comes . Use IFTTT Before , We need to create a new account IFTTT, Then install the mobile terminal app( If you want to be notified on your mobile phone ) After setting successfully, start to create a new IFTTT applet Used for testing .

Create a new test applet, You can follow the steps below :

  1. Click on the big "this" Button ;
  2. Search for "webhooks" service , And then choose "Receive a web request" Trigger ;
  3. rename event by test_event;
  4. Then choose the big "that" Button ;
  5. Search for "notifications" service , And then choose "send a notification from the IFTTT app"
  6. Change SMS to I just triggered my first IFTTT action!, And then click "Create action";
  7. Click on "Finish" Button , complete ;

It depends on how to use IFTTT webhooks, Please click on "Documentation" Button documentation Page has webhooks Of URL.

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

next , You need to {event} Replace with you in step 3 Name yourself in .{your-IFTTT-key} It's already there IFTTT key.

Now you can copy webhook URL, Then turn on the other console. Also import requests And then send 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 :

establish IFTTT Applets

It's just a test , Now we have reached the main part . Before starting the code again , We need to create two new IFTTT applets: One is the urgent notice of bitcoin price , The other is a regular update .

Bitcoin price emergency notification applet:

  1. choice "webhooks" service , And choose "Receive a web request" Trigger ;
  2. Name an event event by bitcoin_price_emergency;
  3. For the action part of the response , choice "Notifications" service , Then continue to choose "send a rich notification from the IFTTT app" action ;
  4. Provide a title , image "Bitcoin price emergency!"
  5. Set SMS by Bitcoin price is at ${{Value1}}. Buy or sell now!( We will return to {{Value1}} part )
  6. Optional , You can join a URL link To Coinmarketcap Bitcoin page:https://coinmarketcap.com/currencies/bitcoin/;
  7. Create action , Then finish applet Set up ;

Regular price update applet:

  1. The same choice "webhooks" service , And choose "Receive a web request" Trigger ;
  2. Name an event event by bitcoin_price_update;
  3. For the action part of the response , choice "Telegram" service , Then continue to choose "Send message" action ;
  4. Set the text of SMS message to :Latest bitcoin prices:<br>{{Value1}};
  5. Create action , Then finish applet Set up ;

Connect all together

Now? , We have it. IFTTT, Here's the code . You will create a standard like the following Python Command line app Start with the skeleton . Code up , And save it as bitcoin_notifications.py:

import requests
import time
from datetime import datetime
def main():
pass
if __name__ == '__main__':
main()

next , We'll also take the first two Python console Part of the code is converted to two functions , The function will return the price of the nearest bitcoin , Then separate them post To IFTTT Of webhook Up . 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 It hasn't changed much .psot_ifttt_webhook Two parameters are required :event and value.

event The parameter corresponds to the trigger name we named earlier . meanwhile ,IFTTT Of webhooks Allow us to pass requests Send additional data , Data as JSON Format .

That's why we need value Parameters : When setting our applet When , We have... In the message text {{Value1}} label . This label will be JSON payload Medium values1 Text substitution .requests.post() The function allows us to set json Keyword to send additional JSON data .

Now we can continue until we app At the heart of main Function code . It includes a while True The cycle of , Because we want to app Run forever . In circulation , We call Coinmarkertcap API To get the latest bitcoin price , And record the date and time at that time .

According to 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_history In the list of . Once the list reaches a certain number ( for instance 5 individual ), We'll pack , Send updates , Then reset the history , For subsequent updates .

One thing to note is to avoid sending messages too often , There are two reasons :

  • Coinmarketcap API Declare that they only have 5 Minute update , So it's no use updating too often
  • If your app Send too many requests Coinmarketcap API, Yours IP May be ban

therefore , We finally joined "go to sleep" sleep , Set 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 one is still missing format_bitcoin_history function . It will bitcoin_history As a parameter , Then use to be Telegram Allowed basic HTML label ( image <br>, <b>, <i> wait ) Transform format . Copy this function to main() above .

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)

The final result displayed on the mobile phone is :

then , Our function is finished , As soon as the price of bitcoin is updated , There is a prompt on the mobile terminal of the mobile phone . Of course , If you're bored, you can also app Inside off fall .

Today's article is shared here , Thank you for reading


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved