This repository has been archived by the owner on Feb 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
103 lines (86 loc) · 2.85 KB
/
main.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
# Author: LolzTheDev
# GitHub: https://github.com/LolzTheDev/py-blog
from flask import Flask, render_template, request, redirect, jsonify
from bson.objectid import ObjectId
from bson import json_util
import json, os, pymongo, datetime, time, bson.errors
os.system('clear||cls')
with open("./config.json") as config:
config_contents = json.load(config)
author = config_contents["author"]
title = config_contents["title"]
db_url = config_contents["mongodb_url"]
debug_mode: bool = bool(config_contents["debug_mode"])
show_post_ids: bool = bool(config_contents["show_post_ids"])
try:
mongo = pymongo.MongoClient(db_url)
db = mongo["blogdb"]
posts = db["posts"]
except Exception as error:
print("Fatal database error. Exiting program.")
print(f"({error})")
app = Flask(__name__)
start_time = time.time()
# filter for unix timestamp -> formatted datetime string
@app.template_filter('utod')
def utod(uts):
return datetime.datetime.fromtimestamp(uts).strftime("%m/%d/%Y, %I:%M:%S %p")
@app.route("/", methods=["GET"])
def home():
if request.method == "GET":
# find and sort posts by time | uses unix timestamps
_posts = posts.find().sort('date', pymongo.DESCENDING)
return render_template(
"home.html",
page_title=title,
posts=_posts,
author=author,
show_id=show_post_ids
)
# api to GET posts
@app.route("/api/", methods=["GET"])
def api_home():
return jsonify({
'uptime': int(time.time() - start_time),
'stats': {
'post_count': posts.count_documents({})
}
})
@app.route("/api/posts/", methods=["GET"])
def api_all_posts():
return jsonify(list(posts.find()))
@app.route("/api/post/<id>", methods=["GET"])
def api_post(id=None):
if id == None:
return redirect("/api/posts/")
else:
try:
if posts.count_documents({"_id" : ObjectId(id)}) > 0:
_post = posts.find_one({"_id" : ObjectId(id)})
return jsonify({
'title': _post["title"],
'content': _post["content"],
'author': _post["author"],
'timestamp': _post["date"],
"id": str(_post["_id"])
})
else:
return jsonify({
'error': {
'code': 404,
'msg': 'post not found'
}
})
except bson.errors.InvalidId as InvalidIdErr:
return jsonify({
'error': {
'code': 404,
'msg': 'post not found (invalid id?)'
}
})
if __name__ == "__main__":
app.run(
host="0.0.0.0",
port=8080,
debug=debug_mode
)