The hompeage now shows a random quote instead of a news thing

This commit is contained in:
SecretlyTaco 2017-04-20 03:08:55 +01:00 committed by socks
parent 60f529cfb9
commit 165d3b4eb6

View file

@ -1,16 +1,17 @@
import datetime import datetime
import logging import random
import psycopg2 import logging
from flask import render_template, Markup, request, abort, session, g import psycopg2
from flask import render_template, Markup, request, abort, session, g
from smash.models_sqlalchemy import *
from smash import app, conf, db from smash.models_sqlalchemy import *
from smash import app, conf, db
logger = logging.getLogger(__name__)
logger = logging.getLogger(__name__)
def timestamp():
return datetime.datetime.now().strftime("%H:%M:%S %d/%m/%y") def timestamp():
return datetime.datetime.now().strftime("%H:%M:%S %d/%m/%y")
def message(level, msg): def message(level, msg):
@ -26,296 +27,300 @@ def message(level, msg):
def before_request(): def before_request():
g.appname = conf.config['APPNAME'] g.appname = conf.config['APPNAME']
g.appbrand = conf.config['APPBRAND'] g.appbrand = conf.config['APPBRAND']
@app.route('/')
def index():
welcome = conf.config['MOTD']
news = ("<p><b>{}</b></p><h4>{} running on smash quote database"
" engine launched today</h4>").format(
datetime.datetime.now().strftime("%d/%m/%y"),
conf.config['APPNAME']
)
#Show random quote on the homepage if any exist
quotes = Quote.query.filter_by(approved=True).order_by(Quote.id.desc())all()
numOfQuotes = len(quotes)
if len(quotes)>0:
quoteNum = random.choice(range(1,numOfQuotes+1))
quote = quotes[quoteNum]
news = str(Markup.escape(quote.content)).replace('\n', '<br />')
@app.route('/') return render_template(
def index(): "index.html",
welcome = conf.config['MOTD'] title="Quotes",
news = ("<p><b>{}</b></p><h4>{} running on smash quote database" welcometext=welcome,
" engine launched today</h4>").format( newstext=news
datetime.datetime.now().strftime("%d/%m/%y"), )
conf.config['APPNAME']
)
@app.route('/login', methods=['GET', 'POST'])
return render_template( def login_page():
"index.html", if request.method == 'POST':
title="Quotes", if request.form["secret"] == conf.config['ADMINSECRET']:
welcometext=welcome, session['authorized'] = True
newstext=news
) return render_template(
@app.route('/login', methods=['GET', 'POST'])
def login_page():
if request.method == 'POST':
if request.form["secret"] == conf.config['ADMINSECRET']:
session['authorized'] = True
return render_template(
"login.html", "login.html",
) )
@app.route('/latest') @app.route('/latest')
def latest(): def latest():
quotes = Quote.query.filter_by(approved=True).order_by(Quote.id.desc()).all() quotes = Quote.query.filter_by(approved=True).order_by(Quote.id.desc()).all()
allquotes = len(quotes) allquotes = len(quotes)
quotes = quotes[:10] quotes = quotes[:10]
if len(quotes)>0: if len(quotes)>0:
# Replace line breaks with html breaks and escape special characters # Replace line breaks with html breaks and escape special characters
for quote in quotes: for quote in quotes:
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>') quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>')
return render_template( return render_template(
"latest.html", "latest.html",
title="Latest", title="Latest",
quotes=quotes, quotes=quotes,
numpages=1 + allquotes//10, numpages=1 + allquotes//10,
curpage=0, curpage=0,
page_type="latest" page_type="latest"
) )
else: else:
return message("alert-warning", "No quotes in the database.") return message("alert-warning", "No quotes in the database.")
@app.route('/latest/<int:page>') @app.route('/latest/<int:page>')
def latest_page(page): def latest_page(page):
allquotes = len(Quote.query.filter_by(approved=True).order_by(Quote.id.desc()).all()) allquotes = len(Quote.query.filter_by(approved=True).order_by(Quote.id.desc()).all())
quotes = Quote.query.filter_by(approved=True).order_by(Quote.id.desc()).all()[(page-1)*10:page*10] quotes = Quote.query.filter_by(approved=True).order_by(Quote.id.desc()).all()[(page-1)*10:page*10]
for quote in quotes: for quote in quotes:
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>') quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>')
return render_template( return render_template(
"latest.html", "latest.html",
title="Latest - page {}".format(page), title="Latest - page {}".format(page),
quotes=quotes, quotes=quotes,
numpages=1 + allquotes//10, numpages=1 + allquotes//10,
curpage=page-1, curpage=page-1,
page_type="latest" page_type="latest"
) )
@app.route('/queue') @app.route('/queue')
def queue(): def queue():
if not session.get('authorized'): if not session.get('authorized'):
return message("alert-danger", "You are not authorized to view this page.") return message("alert-danger", "You are not authorized to view this page.")
quotes = Quote.query.filter_by(approved=False).order_by(Quote.id).all() quotes = Quote.query.filter_by(approved=False).order_by(Quote.id).all()
if len(quotes)>0: if len(quotes)>0:
# Replace line breaks with html breaks and escape special characters # Replace line breaks with html breaks and escape special characters
for quote in quotes: for quote in quotes:
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>') quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>')
return render_template( return render_template(
"queue.html", "queue.html",
title="Queue", title="Queue",
quotes=quotes quotes=quotes
) )
else: else:
return message("alert-warning", "No quotes in the database.") return message("alert-warning", "No quotes in the database.")
@app.route('/moderate', methods=['POST']) @app.route('/moderate', methods=['POST'])
def moderate(): def moderate():
if not session.get('authorized'): if not session.get('authorized'):
return message("alert-danger", "You are not authorized to perform this action.") return message("alert-danger", "You are not authorized to perform this action.")
if request.form['submit'] == "Approve": if request.form['submit'] == "Approve":
quote = Quote.query.filter_by(id=request.form['quoteid']).first() quote = Quote.query.filter_by(id=request.form['quoteid']).first()
quote.approved = True quote.approved = True
db.session.commit() db.session.commit()
return message("alert-success", "Quote approved.") return message("alert-success", "Quote approved.")
elif request.form['submit'] == "Delete": elif request.form['submit'] == "Delete":
quote = Quote.query.filter_by(id=request.form['quoteid']).first() quote = Quote.query.filter_by(id=request.form['quoteid']).first()
# Delete dangling tags (alive only with current Quote) db.session.delete(quote)
dangling_tags = [tag for tag in quote.tags if tag.quotes.count() == 1] db.session.commit()
for tag in dangling_tags:
db.session.delete(tag) return message("alert-success", "Quote deleted.")
db.session.delete(quote)
db.session.commit() abort(501)
return message("alert-success", "Quote deleted.")
@app.route('/quote/<int:id>')
abort(501) def quote(id):
quote = Quote.query.filter_by(id=id, approved=True).first()
@app.route('/quote/<int:id>') if quote is None:
def quote(id): return render_template(
quote = Quote.query.filter_by(id=id, approved=True).first() "message.html",
alertclass="alert-warning",
if quote is None: message="No such quote."
return render_template( )
"message.html", else:
alertclass="alert-warning", quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>')
message="No such quote." return render_template(
) "latest.html",
else: title="Quote #{}".format(quote.id),
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>') quotes=[quote,],
return render_template( numpages=1,
"latest.html", curpage=0,
title="Quote #{}".format(quote.id), page_type="quote"
quotes=[quote,], )
numpages=1,
curpage=0,
page_type="quote" @app.route('/tag/<tagname>')
) def tag(tagname):
tag = Tag.query.filter_by(name=tagname).first()
@app.route('/tag/<tagname>') if len(list(tag.quotes))>0:
def tag(tagname): allquotes = len(list(tag.quotes))
tag = Tag.query.filter_by(name=tagname).first() tag.quotes = tag.quotes[:10]
if len(list(tag.quotes))>0: # Replace line breaks with html breaks and escape special characters
allquotes = len(list(tag.quotes)) for quote in tag.quotes:
tag.quotes = tag.quotes[:10] quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>')
# Replace line breaks with html breaks and escape special characters return render_template(
for quote in tag.quotes: "latest.html",
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>') title="Tag - {}".format(tagname),
quotes=tag.quotes,
return render_template( numpages=1 + allquotes//10,
"latest.html", curpage=0,
title="Tag - {}".format(tagname), page_type="tag/{}".format(tagname)
quotes=tag.quotes, )
numpages=1 + allquotes//10, else:
curpage=0, return message("alert-warning", "No quotes with this tag.")
page_type="tag/{}".format(tagname)
)
else: @app.route('/tag/<tagname>/<int:page>')
return message("alert-warning", "No quotes with this tag.") def tag_page(tagname, page):
tag = Tag.query.filter_by(name=tagname).first()
@app.route('/tag/<tagname>/<int:page>') if len(list(tag.quotes))>0:
def tag_page(tagname, page): allquotes = len(list(tag.quotes))
tag = Tag.query.filter_by(name=tagname).first() tag.quotes = tag.quotes[(page-1)*10:page*10]
if len(list(tag.quotes))>0: for quote in tag.quotes:
allquotes = len(list(tag.quotes)) quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>')
tag.quotes = tag.quotes[(page-1)*10:page*10]
return render_template(
for quote in tag.quotes: "latest.html",
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>') title="Tag - {} - page {}".format(tagname, page),
quotes=tag.quotes,
return render_template( numpages=1 + allquotes//10,
"latest.html", curpage=0,
title="Tag - {} - page {}".format(tagname, page), page_type="tag/{}".format(tagname)
quotes=tag.quotes, )
numpages=1 + allquotes//10,
curpage=0,
page_type="tag/{}".format(tagname) @app.route('/tags')
) def tags():
tags = Tag.query.order_by(Tag.name).distinct().all()
tags = list(set([x.name for x in tags]))
@app.route('/tags')
def tags(): return render_template(
tags = Tag.query.order_by(Tag.name).distinct().all() "tags.html",
tags = list(set([x.name for x in tags])) title="Tags",
tags=tags
return render_template( )
"tags.html",
title="Tags",
tags=tags @app.route('/search/<query>')
) def search(query):
quotes = Quote.query.filter_by(approved=True).filter(Quote.content.ilike('%{}%'.format(query))).order_by(Quote.id.desc()).all()
@app.route('/search/<query>') allquotes = len(quotes)
def search(query): quotes = quotes[:10]
quotes = Quote.query.filter_by(approved=True).filter(Quote.content.ilike('%{}%'.format(query))).order_by(Quote.id.desc()).all()
if len(quotes)>0:
allquotes = len(quotes) # Replace line breaks with html breaks and escape special characters
quotes = quotes[:10] for quote in quotes:
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>')
if len(quotes)>0:
# Replace line breaks with html breaks and escape special characters return render_template(
for quote in quotes: "search.html",
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>') title="Search for: {}".format(query),
quotes=quotes,
return render_template( numpages=1 + allquotes//10,
"search.html", curpage=0,
title="Search for: {}".format(query), page_type="search",
quotes=quotes, search_query=query
numpages=1 + allquotes//10, )
curpage=0, else:
page_type="search", return message("alert-warning", "No quotes in the database.")
search_query=query
)
else: @app.route('/search/<query>/<int:page>')
return message("alert-warning", "No quotes in the database.") def search_page(query, page):
allquotes = len(Quote.query.filter_by(approved=True).\
filter(Quote.content.ilike('%{}%'.format(query))).\
@app.route('/search/<query>/<int:page>') order_by(Quote.id.desc()).all())
def search_page(query, page): quotes = Quote.query.filter_by(approved=True).\
allquotes = len(Quote.query.filter_by(approved=True).\ filter(Quote.content.ilike('%{}%'.format(query))).\
filter(Quote.content.ilike('%{}%'.format(query))).\ order_by(Quote.id.desc()).all()[(page-1)*10:page*10]
order_by(Quote.id.desc()).all())
quotes = Quote.query.filter_by(approved=True).\ for quote in quotes:
filter(Quote.content.ilike('%{}%'.format(query))).\ quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>')
order_by(Quote.id.desc()).all()[(page-1)*10:page*10]
return render_template(
for quote in quotes: "search.html",
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>') title="Search for: {} - page {}".format(query, page),
quotes=quotes,
return render_template( numpages=1 + allquotes//10,
"search.html", curpage=page-1,
title="Search for: {} - page {}".format(query, page), page_type="search",
quotes=quotes, search_query=query
numpages=1 + allquotes//10, )
curpage=page-1,
page_type="search",
search_query=query @app.route('/add', methods=['GET', 'POST'])
) def add_new():
if request.method == 'POST':
if request.form['submit'] == "Submit":
@app.route('/add', methods=['GET', 'POST']) quote_body = request.form["newquote"]
def add_new(): quote_tags = request.form["tags"].split(',')
if request.method == 'POST':
if request.form['submit'] == "Submit": quote = Quote(quote_body, request.remote_addr, timestamp())
quote_body = request.form["newquote"] quote_tags = [Tag(tag) for tag in quote_tags]
quote_tags = request.form["tags"].split(',')
for tag in quote_tags:
quote = Quote(quote_body, request.remote_addr, timestamp()) dbtag = Tag.query.filter_by(name=tag.name).first()
quote_tags = [Tag(tag) for tag in quote_tags] if dbtag is not None:
quote.tags.append(dbtag)
for tag in quote_tags: else:
dbtag = Tag.query.filter_by(name=tag.name).first() quote.tags.append(tag)
if dbtag is not None: #quote.tags.extend(quote_tags)
quote.tags.append(dbtag)
else: db.session.add(quote)
quote.tags.append(tag) db.session.commit()
#quote.tags.extend(quote_tags)
return render_template(
db.session.add(quote) "message.html",
db.session.commit() alertclass="alert-success",
message="Quote added succesfully. It will need to be reviewed by the administrators before it shows up."
return render_template( )
"message.html",
alertclass="alert-success", elif request.form['submit'] == "Preview":
message="Quote added succesfully. It will need to be reviewed by the administrators before it shows up." preview = Quote(request.form['newquote'], request.remote_addr, timestamp())
) preview_tags = request.form["tags"].split(',')
preview.approved = True
elif request.form['submit'] == "Preview": preview.tags = [Tag(tag) for tag in preview_tags]
preview = Quote(request.form['newquote'], request.remote_addr, timestamp())
preview_tags = request.form["tags"].split(',') return render_template(
preview.approved = True "latest.html",
preview.tags = [Tag(tag) for tag in preview_tags] title="Quote preview",
quotes=[preview,],
return render_template( numpages=1,
"latest.html", curpage=0,
title="Quote preview", page_type="quote"
quotes=[preview,], )
numpages=1, else:
curpage=0, abort(501)
page_type="quote"
) elif request.method == 'GET':
else: return render_template(
abort(501) "add.html",
title="Add new"
elif request.method == 'GET': )
return render_template(
"add.html",
title="Add new"
)