Skip to content

Commit

Permalink
running linting and formatting adn fixing any issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Natalie Chan committed Oct 2, 2024
1 parent efc0afa commit 6ee57f8
Show file tree
Hide file tree
Showing 6 changed files with 70 additions and 49 deletions.
9 changes: 9 additions & 0 deletions pra3/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,13 @@ export FLASK_APP=project/app.py
export DATABASE_URL="the value of the external database URL you copied earlier"

flask shell
```

### Linting and Code Formatting
```bash
# linting
python -m flake8 --exclude env --ignore E402,E501 .

# code formatting
python -m black --exclude=env .
```
4 changes: 1 addition & 3 deletions pra3/create_db.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
from project.app import app, db
from project.models import Post


with app.app_context():
# create the database and the db table
db.create_all()

# commit the changes
db.session.commit()
db.session.commit()
87 changes: 50 additions & 37 deletions pra3/project/app.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import sqlite3
import os
from pathlib import Path
from flask import Flask, g, render_template, request, session, \
flash, redirect, url_for, abort, jsonify
from flask import (
Flask,
render_template,
request,
session,
flash,
redirect,
url_for,
abort,
jsonify,
)
from flask_sqlalchemy import SQLAlchemy
from functools import wraps

Expand All @@ -14,7 +22,7 @@
PASSWORD = "admin"
SECRET_KEY = "change_me"

url = os.getenv('DATABASE_URL', f'sqlite:///{Path(basedir).joinpath(DATABASE)}')
url = os.getenv("DATABASE_URL", f"sqlite:///{Path(basedir).joinpath(DATABASE)}")
if url.startswith("postgres://"):
url = url.replace("postgres://", "postgresql://", 1)
SQLALCHEMY_DATABASE_URI = url
Expand All @@ -29,80 +37,85 @@

from project import models


def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get('logged_in'):
flash('Please log in.')
return jsonify({'status': 0, 'message': 'Please log in.'}), 401
if not session.get("logged_in"):
flash("Please log in.")
return jsonify({"status": 0, "message": "Please log in."}), 401
return f(*args, **kwargs)

return decorated_function

@app.route('/')

@app.route("/")
def index():
"""Searches the database for entries, then displays them."""
entries = db.session.query(models.Post)
return render_template('index.html', entries=entries)
return render_template("index.html", entries=entries)


@app.route('/add', methods=['POST'])
@app.route("/add", methods=["POST"])
def add_entry():
"""Adds new post to the database."""
if not session.get('logged_in'):
if not session.get("logged_in"):
abort(401)
new_entry = models.Post(request.form['title'], request.form['text'])
new_entry = models.Post(request.form["title"], request.form["text"])
db.session.add(new_entry)
db.session.commit()
flash('New entry was successfully posted')
return redirect(url_for('index'))
flash("New entry was successfully posted")
return redirect(url_for("index"))


@app.route('/login', methods=['GET', 'POST'])
@app.route("/login", methods=["GET", "POST"])
def login():
"""User login/authentication/session management."""
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
if request.method == "POST":
if request.form["username"] != app.config["USERNAME"]:
error = "Invalid username"
elif request.form["password"] != app.config["PASSWORD"]:
error = "Invalid password"
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('index'))
return render_template('login.html', error=error)
session["logged_in"] = True
flash("You were logged in")
return redirect(url_for("index"))
return render_template("login.html", error=error)


@app.route('/logout')
@app.route("/logout")
def logout():
"""User logout/authentication/session management."""
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('index'))
session.pop("logged_in", None)
flash("You were logged out")
return redirect(url_for("index"))


@app.route('/delete/<int:post_id>', methods=['GET'])
@app.route("/delete/<int:post_id>", methods=["GET"])
@login_required
def delete_entry(post_id):
"""Deletes post from database."""
result = {'status': 0, 'message': 'Error'}
result = {"status": 0, "message": "Error"}
try:
new_id = post_id
db.session.query(models.Post).filter_by(id=new_id).delete()
db.session.commit()
result = {'status': 1, 'message': "Post Deleted"}
flash('The entry was deleted.')
result = {"status": 1, "message": "Post Deleted"}
flash("The entry was deleted.")
except Exception as e:
result = {'status': 0, 'message': repr(e)}
result = {"status": 0, "message": repr(e)}
return jsonify(result)

@app.route('/search/', methods=['GET'])

@app.route("/search/", methods=["GET"])
def search():
query = request.args.get("query")
entries = db.session.query(models.Post)
if query:
return render_template('search.html', entries=entries, query=query)
return render_template('search.html')
return render_template("search.html", entries=entries, query=query)
return render_template("search.html")


if __name__ == "__main__":
app.run()
app.run()
Binary file modified pra3/project/flaskr.db
Binary file not shown.
2 changes: 1 addition & 1 deletion pra3/project/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ def __init__(self, title, text):
self.text = text

def __repr__(self):
return f'<title {self.title}>'
return f"<title {self.title}>"
17 changes: 9 additions & 8 deletions pra3/tests/app_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
import pytest
import json
from pathlib import Path
Expand Down Expand Up @@ -76,6 +75,7 @@ def test_messages(client):
assert b"&lt;Hello&gt;" in rv.data
assert b"<strong>HTML</strong> allowed here" in rv.data


def test_delete_message(client):
"""Ensure the messages are being deleted"""
rv = client.get("/delete/1")
Expand All @@ -86,30 +86,31 @@ def test_delete_message(client):
data = json.loads(rv.data)
assert data["status"] == 1


def test_search(client):
"""Ensure search is working"""
login(client, app.config["USERNAME"], app.config["PASSWORD"])

# create test entry
rv_entry = client.post(
client.post(
"/add",
data=dict(title="<Hello>", text="<strong>HTML</strong> allowed here"),
follow_redirects=True,
)

# send query for Hello -- note search.html converts query to lowercase
# and checks for matching title or text
rv_search = client.get(
rv = client.get(
"/search/",
query_string={"query": "Hello"},
follow_redirects=True,
)
assert b"&lt;Hello&gt;" in rv_search.data
assert b"<strong>HTML</strong> allowed here" in rv_search.data
assert b"&lt;Hello&gt;" in rv.data
assert b"<strong>HTML</strong> allowed here" in rv.data

rv_search = client.get(
rv = client.get(
"/search/",
query_string={"query": "Bye"},
follow_redirects=True,
)
assert b"" in rv_search.data
assert b"" in rv.data

0 comments on commit 6ee57f8

Please sign in to comment.