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

  • Python Social Media Analytics
  • Siddhartha Chatterjee Michal Krystyanczuk
  • 224字
  • 2021-07-15 17:24:56

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
主站蜘蛛池模板: 文昌市| 潢川县| 余江县| 周口市| 特克斯县| 壤塘县| 常山县| 云梦县| 库伦旗| 宝丰县| 哈密市| 北票市| 南阳市| 琼海市| 贵德县| 互助| 沛县| 石台县| 东兰县| 马关县| 湾仔区| 辽阳县| 乌拉特中旗| 色达县| 拉萨市| 澜沧| 那曲县| 靖宇县| 六盘水市| 麟游县| 开阳县| 荆州市| 金坛市| 柯坪县| 石渠县| 南投市| 宣汉县| 房产| 霍城县| 沾化县| 吕梁市|