I touched both bottle and Django, so Flask. As usual, we will use the Twitter API again.
$ python3 -m venv flaskworks
$ ls flaskworks/
$ . flaskworks/bin/activate
(flaskworks)$ pip install flask
(flaskworks)$ pip install requests requests_oauthlib
It's very easy to create a directory like a bottle.
(flaskworks)$ cd flaskworks
(flaskworks)$ mkdir static
(flaskworks)$ mkdir templates
Create two because it uses template inheritance.
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}}I posted</p>
{% endif %}
{% endblock %}
For the time being, I decided to add a simple login function. The reality is almost the same as bottle, isn't it?
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>Please login</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>The user name is different</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
That's it.
It's a thin book, but it's summarized https://www.amazon.co.jp/dp/B0714D1VGP
Recommended Posts