- 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
- Puppet 4 Essentials(Second Edition)
- C語言程序設計(第3版)
- Angular UI Development with PrimeNG
- INSTANT OpenCV Starter
- Java高并發核心編程(卷2):多線程、鎖、JMM、JUC、高并發設計模式
- PHP 從入門到項目實踐(超值版)
- CentOS 7 Server Deployment Cookbook
- Apache Hive Essentials
- 實用防銹油配方與制備200例
- Scratch 3.0少兒編程與邏輯思維訓練
- C語言課程設計
- Spring Boot實戰
- Java EE 8 and Angular
- Maven for Eclipse
- INSTANT JQuery Flot Visual Data Analysis