LoginSignup
14
19

More than 5 years have passed since last update.

Djangoで作るTwitter投稿アプリケーション

Last updated at Posted at 2016-10-24

Twitterに投稿するだけのアプリケーションを作ろう

bottleでもやったことのDjango版になります。単に投稿して、投稿した文字列を返すだけのごく初歩的なアプリケーションを作っていきます。スクリプト自体は焼きましなのでPython2系とゴッチャになってるかもしれませんが、一応動きます。

過去記事 http://qiita.com/Gen6/items/1848f8b4d938807d082e
     http://qiita.com/Gen6/items/a5562c36fc5c67c89916
     http://qiita.com/Gen6/items/e845787a6ad073a77310

前準備はやっておいてください

(virtualenv)$ pip install requests requests_oauthlib

仮想環境下にインストールしておきます。

アプリケーションのイメージ

スクリーンショット 2016-10-24 12.39.17.png

こういうのを作ります。
bootstrapをstaticフォルダを作り投げ込んでおいてもいいですし、CSSを自分で書いてもいいと思います。

中身

myapp/views.py
from requests_oauthlib import OAuth1Session
import json
import re
import os
import requests
import sys, codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)

from django.http.response import HttpResponse
from django.shortcuts import render


def index(request):
    Message = {
        'words': request.GET.get('words'),
    }

    msg = request.GET.get('words')

    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 render(request, 'index.html', Message)
myapp/urls.py
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^template/$', views.index, name='index'),
]
templates/index.html
{% extends "base.html" %}
{% block body %}
  <div class="container">
    <div class="row">
    <form action="" method="get" class="form-group">
      <label>ツイート<input type="text" size="20" name="words" class="form-control"></label>
      <input type="submit" class="btn btn-primary" value="送信">
    </form>
    {% if words %}
      <p>「{{ words }}」 とツイートしました。</p>
    {% endif %}
    </div>
  </div>

{% endblock %}

bottleのときと比較するとなんかグッと楽になった気がするのは気のせいでしょうか。
>bottle版 http://qiita.com/Gen6/items/ee33eb51fbeb969bb9db

続きをやりたい方はこちらで
http://qiita.com/Gen6/items/11fa5265053da95fcf0b

14
19
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
14
19