官术网_书友最值得收藏!

Practical usage of OAuth

In this part of the chapter, we will see how to connect to the main social media using OAuth and how to get and parse the data. There are many libraries in Python 3 implementing the OAuth protocol. For the purposes of this book, we will show how to use a library called requests.

The requests library implements the whole range of authentication protocols and allows you to execute HTTP requests such as GET or POST.

Firstly, you have to import the library in your code:

import requests 

If you are using the OAuth protocol, you import the related library:

from requests_oauthlib import OAuth1 

Then, you have to create your authenticated connection using access tokens and application keys that you will find in the developer console:

auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET', 'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET') 

Then, you can make GET requests:

r = requests.get('https://api.sampleurl.org/get',auth=auth) 

Pass these parameters:

payload = {'key1': 'value1', 'key2': 'value2'} 
r = requests.get('http://sampleurl.org/get', params=payload) 

POST requests:

r = requests.post('http://sampleurl.org/post', data = {'key':'value'}) 

Also, a whole range of additional requests:

r = requests.put('http://sampleurl.org/put', data = {'key':'value'}) 
r = requests.delete('http://sampleurl.org/delete') 
r = requests.head('http://sampleurl.org/get') 
r = requests.options('http://sampleurl.org/get') 

In order to parse the outputs, you can use different methods such as:

  • r.text() This gets a string with request outputs
  • r.json(): This gets JSON with request outputs
  • r.econding(): This checks the encoding of the output
主站蜘蛛池模板: 信丰县| 南昌市| 平安县| 安国市| 梁山县| 余干县| 临颍县| 桓仁| 大荔县| 汉阴县| 桃园县| 舟山市| 呼伦贝尔市| 兴业县| 南通市| 阳泉市| 额尔古纳市| 盐山县| 翼城县| 塔河县| 定西市| 札达县| 钟祥市| 台南县| 汾西县| 神农架林区| 石泉县| 六枝特区| 井陉县| 永靖县| 措美县| 隆子县| 陇川县| 荆门市| 偏关县| 晋城| 那坡县| 平乡县| 会同县| 大同县| 南平市|