LoginSignup
5
8

More than 5 years have passed since last update.

ブラウザで動かす。bottleで作るTwitterクライアント(POSTのみ

Last updated at Posted at 2015-05-15

Djangoに挫折してとりあえず自分が理解できるフレームワークをと。
そこでbottleに行き着きました。
bottle.pyというスクリプトファイルだけで出来ているフレームワーク。
簡易的なWebアプリなら直ぐに実行できそうな気にさせてくれます。

というわけでブラウザでツイートを送信してみました。

index.py

#!/user/bin/env python
# -*- coding: utf-8 -*-
from bottle import route, run, template, request
from requests_oauthlib import OAuth1Session
import json
import sys, codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)

@route("/")
def post():
    return template("post")

@route("/show", method="GET")
def msg():
    msg = request.query.msg

    C_KEY = "****************************"
    C_SECRET = "****************************"
    A_KEY = "****************************"
    A_SECRET = "****************************"

    url = "https://api.twitter.com/1.1/statuses/update.json"
    params = {"status": msg,"lang": "ja"}
    tw = OAuth1Session(C_KEY,C_SECRET,A_KEY,A_SECRET)
    req = tw.post(url, params = params)


    return template("show", msg=msg)

run(host="localhost", port="8000", debug=True, reloader=True) 

次はテンプレートを作ります。
bottle.py と index.pyと同一ディレクトリに viewsというフォルダを作り、
以下のHTMLファイルをpost.htmlとして保存します。


<!DOCTYPE html>
<html lang=ja>
  <head>
    <meta charset="UTF-8">
    <title>ツイートしよう</title>
  </head>

  <body>
    <h1>ツイートを入力しよう</h1>

    <form method="GET" action="/show">
    <p>ツイート:
    <input type="text" name="msg"></p>
    <input type="submit" value="送信する">
  </body>

</html>

同様にツイート完了画面を作るので、上記HTMLファイルと同じviewsフォルダにshow.htmlとして保存します。


<!DOCTYPE html>
<html lang=ja>
  <head>
    <meta charset="UTF-8">
    <title>ツイート結果</title>
  </head>

  <body>
    <h1>ツイート完了!</h1>
    <p>あなたのツイート: {{msg}} <p>
    <a href="/">Back</a>
    </p>
  </body>

</html>

ターミナルからindex.pyを実行して、
http://127.0.0.1:8000/
にアクセス。おしまい。

ちなみにbottleのテンプレートでは、

% if ~:
や
<%
for i in s:
  print i
%>

などと、%の間はPythonのコードを記載することが可能。

Djangoバージョンも書きました。
http://qiita.com/Gen6/items/735245423b65698428be

5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8