Second half of the first day of studying Python Try hitting the Twitter API with Bottle

Case Study

Python3.4 Bottle IntelliJ Do something on twitter

Synopsis up to the last time

python3.4, Intellij environment construction Study basic usage of bottle Easy to use jinja2 template modularization

Post to Twitter timeline

Use Requests-OAuthlib

From the result, it failed

There are a lot of Twitter libraries, but the Web API only sends JSON. Only Auth is done in the library, and the rest is to make an HTTP request directly Unlike the Twitter library, it can also be used for other Auth such as Facebook and Google+

So I decided to use Requests-OAuthlib

As usual,

import requests_oauthlib

And import it with IntelliJ Not found and cannot be resolved!

I tried various things, but eventually gave up using it with IntelliJ To install with pip and start it from the command line

First, register the Twitter API and consumer_key, consumer_secret, access_token, access_token_secret Please get and set

python


import os
import bottle
import jinja2
import requests_oauthlib
from requests_oauthlib import OAuth1Session

from bottle import route, post, request, run
from bottle import TEMPLATE_PATH, jinja2_template as template

base_url = "https://api.twitter.com/1.1/"
update_url="statuses/update.json"


consumer_key="hoge"
consumer_secret="hoge"
access_token="hoge"
access_token_secret="hoge"


TEMPLATE_PATH.append("./template")



class Twitter:
    def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret):
        self.twitter_ = OAuth1Session(consumer_key, consumer_secret, access_token, access_token_secret)

    def update(self, msg):
        param="{'status:': '" + msg + "'}"
        return(self.twitter_.post(base_url+update_url, param))


@route('/')
def HomeHandler_():
    return template("home.j2", posts="Get timeline soon")

@post('/1/twitter/post')
def UpdateHandler_():
    global twitter_
    msg = request.forms.get('status')
    print("post:"+msg)
    req = twitter_.update(msg)
    return template("home.j2", posts="Get timeline soon")


twitter_ = Twitter(secret.consumer_key, secret.consumer_secret, secret.access_token, secret.access_token_secret)


if __name__ == "__main__":
    run(host='localhost', port=1046, debug=True, reloader=True)


home.j2


{% extends "base.j2" %}

{% block content %}
  <div id="postform">
    <form method="POST" action="/1/twitter/post">
      <table>
        <tr><td><textarea cols="70" rows="3" name="status"></textarea></td></tr>
        <tr><td align="right"><input type="submit" name="doit" value="Update"></td></tr>
      </table>
    </form>
  </div>

<h2>Timeline</h2>
<i>aaa</i><br>
{% for post in posts %}
{{ post }}
{% endfor %}

{% endblock %}

I feel like the code is done properly. It doesn't work. ..

I tried my best for about 2 hours, but I couldn't tweet well, so I give up

Tweepy You can easily change the library. I met a lot, but somehow I decided on a library called Tweepy. I do not have a reason By the way, it will be modularized

The module name will be Twitter.py main is

import Twitter

Add

Add the module name namespace to the Twitter.hoge part Change to Twitter.Twitter.hoge

Twitter.py


# -*- encoding: utf-8 -*-
import tweepy



__author__ = 'miyatake_y'

base_url = "https://api.twitter.com/1.1/"
update_url="statuses/update.json"



class Twitter:
    def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret):
        self.auth_ = tweepy.OAuthHandler(consumer_key,consumer_secret)
        self.auth_.set_access_token(access_token,access_token_secret)
        self.twitter_ = tweepy.API(self.auth_)

    def update(self, msg):
        print("Twitter.update:" + msg)
        return(self.twitter_.update_status(status=msg))

You can now POST from the form! Moreover, it can be operated from IntelliJ! But Japanese is garbled. Next time I will deal with that

Japanese localization

It was very easy. All you have to do is call decode () on request

msg = request.forms.decode().get('status')

Now you can post in Japanese!

Timeline acquisition & display

Getting the timeline is easy Immediately with Tweepy

twitter_.home_timeline()

Then a list of status objects will be returned. Arguments are how many tweets are fetched, from what number, etc. By default, 20 will be brought from the latest

print(twitter_.home_timeline()[0].text)

If so, the latest Tweet text will be displayed In addition to text, the status object also contains other data such as time.

This time I get a list of timelines Pass the list to the jinja2 template engine To loop in the template

Added method to Twitter class. Now that I think about it, I thought it would be easier to use Tweepy live.

Twitter.py


    def home_timeline(self):
        return(self.twitter_.home_timeline())

Give a status list as an argument to the template

main.py


    return template("home.j2", posts=twitter_.home_timeline())

And turn the template with for

home.j2


{% for post in posts %}
{{ post.text }} <br><hr>
{% endfor %}

Now you can see the timeline! !!

Features I'm thinking of adding

View your POST. template I want to increase the API, so it's a friend. Get ACCESS TOKEN programmatically

Recommended Posts

Second half of the first day of studying Python Try hitting the Twitter API with Bottle
Try hitting the Twitter API quickly and easily with Python
Play by hitting the Riot Games API in Python First half
Try hitting the YouTube API in Python
Hit a method of a class instance with the Python Bottle Web API
Note: How to get the last day of the month with python (added the first day of the month)
[First API] Try to get Qiita articles with Python
I tried hitting the API with echonest's python client
Use Twitter API with Python
Try using the Twitter API
Try using the Twitter API
Call the API with python3.
Try scraping the data of COVID-19 in Tokyo with Python
A note about hitting the Facebook API with the Python SDK
The first API to make with python Djnago REST framework
Let's touch the API of Netatmo Weather Station with Python. #Python #Netatmo
Try to automate the operation of network devices with Python
Aggregate the number of hits per second for one day from the web server log with Python
First Python 3 ~ The beginning of repetition ~
March 14th is Pi Day. The story of calculating pi with python
Specifying the date with the Twitter API
First python ② Try to write code while examining the features of python
Crawling with Python and Twitter API 2-Implementation of user search function
Hit the Etherpad-lite API with Python
Access the Twitter API in Python
List of language codes used in twitter (including API) (with Python dictionary). What is the most commonly used language?
Try to image the elevation data of the Geographical Survey Institute with Python
I tried to get the authentication code of Qiita API with Python.
Get the number of articles accessed and likes with Qiita API + Python
The result of making the first thing that works with Python (image recognition)
I tried to get the movie information of TMDb API with Python
Collecting information from Twitter with Python (Twitter API)
Try using the Wunderlist API in Python
Try using the Kraken API in Python
Check the existence of the file with python
Tweet using the Twitter API in Python
[Python] Try pydash of the Python version of lodash
The second night of the loop with for
Try hitting the Spotify API in Django.
I'm an amateur on the 14th day of python, but I want to try machine learning with scikit-learn
Rewrite the sampling node of SPSS Modeler with Python ①: First N cases, random sampling
Try out the touch of data-driven testing with Selenium Python Bindings and py.test
Try the python version of emacs-org parser orgparse
Prepare the execution environment of Python3 with Docker
[Note] Export the html of the site with python.
Try to solve the man-machine chart with Python
Try using the BitFlyer Ligntning API in Python
Calculate the total number of combinations with python
Check the date of the flag duty with Python
[Python] Read the source code of Bottle Part 1
Try the free version of Progate [Python I]
After hitting the Qiita API with Python to get a list of articles for beginners, we will visit the god articles
Explosive speed with Python (Bottle)! Web API development
Predict the second round of summer 2016 with scikit-learn
Try using the collections module (ChainMap) of python3
Find out the day of the week with datetime
Convert the character code of the file with Python3
[Python] Get the day of the week (English & Japanese)
Try accessing the YQL API directly from Python 3
[Python] Determine the type of iris with SVM
Try using the DropBox Core API in Python