13
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Flaskで作るTwitter投稿クライアント 簡易ログイン機能付き

Last updated at Posted at 2017-05-18

#Flaskの学習

bottleもDjangoも一通り触ったのでFlask。
例によってまたTwitter APIを使います。

$ python3 -m venv flaskworks
$ ls flaskworks/
$ . flaskworks/bin/activate
(flaskworks)$ pip install flask
(flaskworks)$ pip install requests requests_oauthlib

bottleみたいにすごく簡単にディレクトリを作成していきます。

(flaskworks)$ cd flaskworks
(flaskworks)$ mkdir static
(flaskworks)$ mkdir templates

#テンプレートを作る

テンプレートの継承を利用するので2つ作成。

base.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/css/style.css">
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <title>Tweet</title>
</head>
<body>
  <div class="container">
    <div class="row">
      <form method="post" action="/send">
        <input type="text" id="msg" name="msg">
        <input type="submit" value="Send Form">
      </fomr>
        {% block content %}
        {% endblock %}
    </div>
  </div>
</body>
</html>
index.html
{% extends "base.html" %}
{% block content %}
  {% if msg %}
  <p>「{{msg}}」 と投稿しました</p>
  {% endif %}
{% endblock %}

#投稿用のアプリケーションを書いていく

とりあえず簡易ログイン機能をつけることにしました。実態はほぼbottleと同じですねこれは。

tweet.py
import os
from requests_oauthlib import OAuth1Session
import requests
from flask import Flask, render_template, request, redirect, url_for, session
app = Flask(__name__)

app.config['SECRET_KEY'] = os.urandom(24)

C_KEY = '+++++++++++++++++++++++++++++'
C_SECRET = '+++++++++++++++++++++++++++++'
A_KEY = '+++++++++++++++++++++++++++++'
A_SECRET = '+++++++++++++++++++++++++++++'

Post_API = 'https://api.twitter.com/1.1/statuses/update.json'
tw = OAuth1Session(C_KEY,C_SECRET,A_KEY,A_SECRET)

@app.route('/')
def index():
    if 'username' in session:
        return render_template('index.html')
    return '''
        <p>ログインしてください</p>
    '''

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        if username == 'admin':
            session['username'] = request.form['username']
            return redirect(url_for('index'))
        else:
            return '''<p>ユーザー名が違います</p>'''
    return '''
        <form action="" method="post">
            <p><input type="text" name="username">
            <p><input type="submit" value="Login">
        </form>
    '''

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('index'))

@app.route('/send', methods=['GET', 'POST'])
def send():
    if request.method == 'POST':
        msg = request.form['msg']
        url = Post_API
        params = {'status': msg,'lang': 'ja'}
        req = tw.post(url, params = params)

        return render_template('index.html', msg=msg)

if __name__ == '__main__':
    app.debug = True
    app.run()

#動作確認

(flaskworks)$ python tweet.py
スクリーンショット 2017-05-18 10.47.35.png

おしまい。

薄い本ですがまとめています
https://www.amazon.co.jp/dp/B0714D1VGP

13
20
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
13
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?