-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
302 lines (226 loc) · 9.04 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
from flask import Flask, render_template, flash, redirect, url_for, session, request, logging, g
from flask_mysqldb import MySQL
from passlib.hash import pbkdf2_sha256
from functools import wraps
import tweepy
import os
from random import randint
# import secret_code
from form_class import PhraseForm, RegisterForm
app = Flask(__name__) # create the application instance
app.config.from_object(__name__) # load config from this file, app.py
app.config.update(dict(
# Secret key
SECRET_KEY=os.getenv("SECRET_KEY"),
# MySQL config
MYSQL_HOST=os.getenv("MYSQL_HOST"),
MYSQL_USER=os.getenv("MYSQL_USER"),
MYSQL_PASSWORD=os.getenv("MYSQL_PASSWORD"),
MYSQL_DB=os.getenv("MYSQL_DB"),
MYSQL_CURSORCLASS='DictCursor'
))
# init MySQL
mysql = MySQL(app)
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'mysql_db'):
g.mysql_db = mysql.connect
return g.mysql_db
def init_db():
"""Inizializes the Database. Function used only for tests"""
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
query = " ".join(f.readlines())
cur = db.cursor()
cur.execute(query)
more = True
while more:
more = cur.nextset()
db.commit()
@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'mysql_db'):
g.mysql_db.close()
# Homepage - Dashboard
@app.route('/', methods=['GET', 'POST'])
def index():
# Check for db connection
db = get_db()
# Create cursor
cur = db.cursor()
# Get tweets
result = cur.execute("SELECT author.first_name, author.last_name, tweets.tweet_phrase, tweets.tweet_date FROM author JOIN tweets ON author.author_id = tweets.author_id ORDER BY tweets.tweet_date DESC")
tweets = cur.fetchall() # tweets is a tuple of dicts because app.config['MYSQL_CURSORCLASS'] = 'DictCursor'. Default is tuple instead of dict.
# Logging result and tweets to the console
app.logger.info(result)
app.logger.info(tweets)
if result > 0:
return render_template('home.html', tweets=tweets)
else:
msg = 'No Records Found'
return render_template('home.html', msg=msg)
# User login
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# Get Form Fields
username = request.form['username']
password_candidate = str(request.form['password'])
# Check for db connection
db = get_db()
# Create cursor
cur = db.cursor()
#Get user by username
result = cur.execute("SELECT * FROM users WHERE username = %s", (username,))
if result > 0:
# Get stored hash
data = cur.fetchone()
password = data['password']
# Compare Passwords
if pbkdf2_sha256.verify(password_candidate, password):
# Passed
session['logged_in'] = True
session['username'] = username
flash('You are now logged in', 'success')
return redirect(url_for('add_phrase'))
else:
error = 'Invalid login'
return render_template('login.html', error=error)
else:
error = 'Username not found'
return render_template('login.html', error=error)
else:
return render_template('login.html')
# Check if user logged in
def is_logged_in(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('Unauthorized, Please login', 'danger')
return redirect(url_for('login'))
return wrap
# Logout
@app.route('/logout')
@is_logged_in
def logout():
session.clear()
flash('You are now logged out', 'success')
return redirect(url_for('login'))
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm(request.form)
if request.method == 'POST' and form.validate():
name = form.name.data
password = pbkdf2_sha256.hash(str(form.password.data))
register_key_candidate = form.key.data
# Check register key
if register_key_candidate != os.getenv("REGISTER_KEY"):
flash('Invalid Key', 'danger')
return redirect(url_for('register'))
else:
# Check for db connection
db = get_db()
# Create cursor
cur = db.cursor()
cur.execute("INSERT INTO users(username, password) VALUES(%s, %s)", (name, password))
# Commit to DB
db.commit()
flash('You are now registered and can login in', 'success')
return redirect(url_for('index'))
else:
return render_template('register.html', form=form)
# Add Phrase
@app.route('/add_phrase', methods=['GET', 'POST'])
@is_logged_in
def add_phrase():
# Check for db connection
db = get_db()
# Create cursor
cur = db.cursor()
# Get tweets
result = cur.execute("SELECT author.first_name, author.last_name, new_phrases.new_phrase, new_phrases.new_phrase_date FROM author JOIN new_phrases ON author.author_id = new_phrases.author_id ORDER BY new_phrases.new_phrase_date;")
tweets = cur.fetchall() # tweets is a tuple of dicts because app.config['MYSQL_CURSORCLASS'] = 'DictCursor'. Default is tuple instead of dict.
app.logger.info(result)
app.logger.info(tweets)
if result == 0:
msg = 'No New Phrases Found'
else:
msg = 'Showing new phrases!'
form = PhraseForm(request.form)
if request.method == 'POST' and form.validate():
first_name = form.first_name.data.capitalize()
#.replace("'", "\u02C8")
last_name = form.last_name.data.capitalize()
#.replace("'", "\u02C8")
phrase = form.phrase.data.capitalize()
#.replace("'", "\u02C8")
# Check for db connection
db = get_db()
# Create cursor
cur = db.cursor()
result = cur.execute("SELECT * FROM author WHERE first_name= %s AND last_name= %s", (first_name, last_name))
#Check weather author exists
# if author exists then insert phrase into new_phrases table
if result > 0:
author = cur.fetchone()
cur.execute("INSERT INTO new_phrases(new_phrase, author_id) VALUES (%s, %s)", (phrase, author['author_id']))
# else insert first_name and last_name into author and new_phrase and author_id into new_phrases
else:
cur.execute("INSERT INTO author(first_name, last_name) VALUES (%s, %s)", (first_name, last_name))
result = cur.execute("SELECT * FROM author WHERE first_name= %s AND last_name= %s", (first_name, last_name))
author = cur.fetchone()
cur.execute("INSERT INTO new_phrases(new_phrase, author_id) VALUES (%s, %s)", (phrase, author['author_id']))
# Commit to DB
db.commit()
flash('Phrase Created', 'success')
return redirect(url_for('add_phrase'))
else:
return render_template('add_phrase.html', form=form, tweets=tweets, msg=msg)
# Tweet
@app.route('/tweet')
@is_logged_in
def tweet():
# Check for db connection
db = get_db()
# Create cursor
cur = db.cursor()
result = cur.execute("SELECT * FROM new_phrases ORDER BY new_phrase_date limit 1")
if result > 0:
row = cur.fetchone()
new_phrase = row['new_phrase']
cur.execute("SELECT * FROM author WHERE author_id = %s", (row['author_id'],))
author_name = cur.fetchone()
author_first_name = author_name['first_name']
author_last_name = author_name['last_name']
message = f"{new_phrase}\n{author_first_name} {author_last_name}"
cur.execute("INSERT INTO tweets(tweet_phrase, author_id) VALUES (%s, %s)", (new_phrase, author_name['author_id']))
# Deleting the tweet from new_phrases
cur.execute("DELETE FROM new_phrases WHERE new_phrase_id = %s", (row['new_phrase_id'],) )
# Commit to DB
db.commit()
else:
result = cur.execute("SELECT * FROM tweets")
tweets = cur.fetchall()
number = randint(0, result - 1)
row = tweets[number]
cur.execute("SELECT * FROM author WHERE author_id = %s", (row['author_id'],))
author_name = cur.fetchone()
author_first_name = author_name['first_name']
author_last_name = author_name['last_name']
message = f"{row['tweet_phrase']}\n{author_first_name} {author_last_name}"
# Twitter authentication
auth = tweepy.OAuthHandler(os.getenv("CONSUMER_KEY"), os.getenv("CONSUMER_SECRET"))
auth.set_access_token(os.getenv("ACCESS_TOKEN"), os.getenv("ACCESS_TOKEN_SECRET"))
api = tweepy.API(auth)
auth.secure = True
# Posting Twitter message
api.update_status(status=message)
flash('Tweet sent!', 'success')
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)