starting refactor and extending app

This commit is contained in:
lza_menace 2020-07-28 13:31:07 -07:00
parent d199943b45
commit 37af78e539
8 changed files with 109 additions and 48 deletions

View file

@ -3,13 +3,12 @@ import uuid
import os import os
import json import json
import requests import requests
from flask import Flask, g, request, redirect, url_for, abort from flask import Flask, request, redirect, url_for, abort
from flask import jsonify, render_template, flash, session from flask import jsonify, render_template, flash, session
from flask import send_from_directory, make_response from flask import send_from_directory, make_response
from flask_session import Session from flask_session import Session
from playhouse.flask_utils import PaginatedQuery
from werkzeug.utils import secure_filename from werkzeug.utils import secure_filename
from suchwow.models import Meme, db from suchwow.models import Post, Profile, Comment, Notification, db
app = Flask(__name__) app = Flask(__name__)
@ -17,9 +16,9 @@ app.config.from_envvar("FLASK_SECRETS")
app.secret_key = app.config["SECRET_KEY"] app.secret_key = app.config["SECRET_KEY"]
Session(app) Session(app)
OPENID_URL = app.config["OIDC_URL"][0] OPENID_URL = app.config["OIDC_URL"]
OPENID_CLIENT_ID = app.config["OIDC_CLIENT_ID"][0] OPENID_CLIENT_ID = app.config["OIDC_CLIENT_ID"]
OPENID_CLIENT_SECRET = app.config["OIDC_CLIENT_SECRET"][0] OPENID_CLIENT_SECRET = app.config["OIDC_CLIENT_SECRET"]
OPENID_REDIRECT_URI = "http://localhost:5000/auth" OPENID_REDIRECT_URI = "http://localhost:5000/auth"
@ -27,9 +26,22 @@ def allowed_file(filename):
return "." in filename and \ return "." in filename and \
filename.rsplit(".", 1)[1].lower() in app.config["ALLOWED_EXTENSIONS"] filename.rsplit(".", 1)[1].lower() in app.config["ALLOWED_EXTENSIONS"]
def debug_login():
session["auth"] = {
"state": "active",
"session_state": "debug",
"code": "abcdefg",
"preferred_username": "debuguser",
"debug": True
}
return
def login_required(f): def login_required(f):
@wraps(f) @wraps(f)
def decorated_function(*args, **kwargs): def decorated_function(*args, **kwargs):
if app.debug:
debug_login()
return f(*args, **kwargs)
if "auth" not in session or not session["auth"]: if "auth" not in session or not session["auth"]:
return redirect(url_for("login")) return redirect(url_for("login"))
return f(*args, **kwargs) return f(*args, **kwargs)
@ -38,31 +50,31 @@ def login_required(f):
@app.route("/") @app.route("/")
def index(): def index():
page = request.args.get('page') page = request.args.get("page", "1")
if page.isdigit() is False: if page.isdigit() is False:
flash("Wow, wtf hackerman. Cool it.") flash("Wow, wtf hackerman. Cool it.")
page = 1 page = 1
memes = Meme.select().order_by(Meme.timestamp).paginate(int(page), 10) posts = Post.select().order_by(Post.timestamp).paginate(int(page), 10)
return render_template("index.html", memes=memes, page=page) return render_template("index.html", posts=posts, page=page)
@app.route("/meme/<id>") @app.route("/post/<id>")
def meme(id): def read_post(id):
if Meme.filter(id=id): if Post.filter(id=id):
meme = Meme.get(Meme.id == id) post = Post.get(Post.id == id)
return render_template("meme.html", meme=meme) return render_template("post.html", post=post)
else: else:
return "no meme there brah" return "no meme there brah"
@app.route("/uploads/<path:filename>") @app.route("/uploads/<path:filename>")
def uploaded_file(filename): def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename) return send_from_directory(app.config["UPLOAD_FOLDER"], filename)
@app.route("/submit", methods=["GET", "POST"]) @app.route("/post/create", methods=["GET", "POST"])
@login_required @login_required
def submit(): def create_post():
if request.method == "POST": if request.method == "POST":
meme_title = request.form.get('title') post_title = request.form.get("title")
# check if the post request has the file part # check if the post request has the file part
if "file" not in request.files: if "file" not in request.files:
flash("You didn't upload a caliente meme, bro! You're fuckin up!") flash("You didn't upload a caliente meme, bro! You're fuckin up!")
@ -73,21 +85,25 @@ def submit():
if file.filename == "": if file.filename == "":
flash("You didn't upload a caliente meme, bro! You're fuckin up!") flash("You didn't upload a caliente meme, bro! You're fuckin up!")
return redirect(request.url) return redirect(request.url)
if meme_title is "": if post_title is "":
flash("You didn't give your meme a spicy title, bro! You're fuckin up!") flash("You didn't give your meme a spicy title, bro! You're fuckin up!")
return redirect(request.url) return redirect(request.url)
if file and allowed_file(file.filename): if file and allowed_file(file.filename):
filename = secure_filename(file.filename) filename = secure_filename(file.filename)
save_path = os.path.join(app.config["UPLOAD_FOLDER"], filename) save_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
file.save(save_path) file.save(save_path)
meme = Meme( # gen wallet
title=meme_title, post = Post(
title=post_title,
subtitle=request.form.get("subtitle", ""),
submitter=session["auth"]["preferred_username"], submitter=session["auth"]["preferred_username"],
image_name=filename, image_name=filename,
account_index=0,
address_index=0
) )
meme.save() post.save()
return redirect(url_for("meme", id=meme.id)) return redirect(url_for("read_post", id=post.id))
return render_template("submit.html") return render_template("create_post.html")
@app.route("/login") @app.route("/login")
def login(): def login():
@ -99,7 +115,11 @@ def login():
f"response_type=code&" \ f"response_type=code&" \
f"state={state}" f"state={state}"
return redirect(url) if app.debug:
debug_login()
return redirect(url_for("index"))
else:
return redirect(url)
@app.route("/auth/") @app.route("/auth/")
@ -169,9 +189,9 @@ def logout():
def not_found(error): def not_found(error):
return make_response(jsonify({"error": "Page not found"}), 404) return make_response(jsonify({"error": "Page not found"}), 404)
@app.cli.command('dbinit') @app.cli.command("dbinit")
def dbinit(): def dbinit():
db.create_tables([Meme]) db.create_tables([Post, Profile, Comment, Notification])
if __name__ == "__main__": if __name__ == "__main__":
app.run() app.run()

View file

@ -5,5 +5,5 @@ OIDC_REDIRECT_URL = 'http://localhost:5000/auth'
SECRET = 'yyyyyyyyyyyyy', SECRET = 'yyyyyyyyyyyyy',
SESSION_TYPE = 'filesystem' SESSION_TYPE = 'filesystem'
UPLOAD_FOLDER = '/path/to/the/uploads' UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif']) ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
MAX_CONTENT_LENGTH = 16 * 1024 * 1024 MAX_CONTENT_LENGTH = 16 * 1024 * 1024

View file

@ -4,11 +4,45 @@ from datetime import datetime
db = SqliteDatabase('data/sqlite.db') db = SqliteDatabase('data/sqlite.db')
class Meme(Model): class Post(Model):
id = AutoField() id = AutoField()
title = CharField() title = CharField()
subtitle = CharField()
# submitter = ForeignKeyField(Profile, field=Profile.username)
submitter = CharField() submitter = CharField()
image_name = CharField() image_name = CharField()
readonly = BooleanField(default=False)
hidden = BooleanField(default=False)
account_index = IntegerField()
address_index = IntegerField()
timestamp = DateTimeField(default=datetime.now)
class Meta:
database = db
class Profile(Model):
id = AutoField()
username = CharField()
address = CharField()
notifications = IntegerField()
class Meta:
database = db
class Comment(Model):
id = AutoField()
comment = TextField()
commenter = ForeignKeyField(Profile, field=Profile.username)
post = ForeignKeyField(Post, field=id)
timestamp = DateTimeField(default=datetime.now)
class Meta:
database = db
class Notification(Model):
type = CharField()
message = TextField()
username = ForeignKeyField(Profile, field=Profile.username)
timestamp = DateTimeField(default=datetime.now) timestamp = DateTimeField(default=datetime.now)
class Meta: class Meta:

View file

View file

@ -5,6 +5,7 @@
<h1>Upload new File</h1> <h1>Upload new File</h1>
<form method=post enctype=multipart/form-data> <form method=post enctype=multipart/form-data>
<input type="text" name="title"><br> <input type="text" name="title"><br>
<input type="text" name="subtitle"><br>
<input type=file name=file> <input type=file name=file>
<input type=submit value=Submit> <input type=submit value=Submit>
</form> </form>

View file

@ -2,7 +2,7 @@
{% block content %} {% block content %}
<a href="{{ url_for('submit') }}">Submit A Meme</a><br> <a href="{{ url_for('create_post') }}">Submit A Meme</a><br>
<a href="{{ url_for('debug') }}">Debug</a> <a href="{{ url_for('debug') }}">Debug</a>
{% block header %} {% block header %}
@ -10,10 +10,11 @@
{% endblock %} {% endblock %}
<ul> <ul>
{% for meme in memes %} {% for post in posts %}
<li><a href="{{ url_for('meme', id=meme.id) }}">{{ meme.title }}</a></li> <li><a href="{{ url_for('read_post', id=post.id) }}">{{ post.title }}</a></li>
{% endfor %} {% endfor %}
</ul> </ul>
{{ page }} {{ page }}
{% endblock %}
{% endblock %}

View file

@ -1,14 +0,0 @@
{% extends 'base.html' %}
{% block header %}
<h1>{% block title %}View Meme{% endblock %}</h1>
{% endblock %}
{% block content %}
<p>Submitter: {{ session['auth']['preferred_username'] }}</p>
<p>ID: {{ meme.id }}</p>
<p>Title: {{ meme.title }}</p>
<p>Submitted: {{ meme.timestamp }}</p>
<p>Image Name: {{ meme.image_name }}</p>
<img src="{{ url_for('uploaded_file', filename=meme.image_name) }}" width=400/>
{% endblock %}

View file

@ -0,0 +1,19 @@
{% extends 'base.html' %}
{% block header %}
<h1>{% block title %}View Post{% endblock %}</h1>
{% endblock %}
{% block content %}
{% if post.hidden %}
You cannot see this post
{% else %}
<p>Submitter: {{ post.submitter }}</p>
<p>ID: {{ post.id }}</p>
<p>Title: {{ post.title }}</p>
<p>Subtitle: {{ post.subtitle }}</p>
<p>Submitted: {{ post.timestamp }}</p>
<p>Image Name: {{ post.image_name }}</p>
<img src="{{ url_for('uploaded_file', filename=post.image_name) }}" width=500/>
{% endif %}
{% endblock %}