-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
79 lines (69 loc) · 2.33 KB
/
app.py
File metadata and controls
79 lines (69 loc) · 2.33 KB
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
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from os import getenv
import sys
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = getenv(
"STP_MAIN_DATABASE_CONNECTION_STRING")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
migrate = Migrate(app, db)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True, index=True)
title = db.Column(db.String, nullable=False, unique=True)
authorEmail = db.Column(db.String, nullable=False)
content = db.Column(db.String)
def __repr__(self):
return f"Post <{self.title}>"
@app.route("/posts", methods=["GET"])
def get_posts():
try:
return jsonify(
{
"message": "success",
"data": [
{
"title": post.title,
"authorEmail": post.authorEmail,
"content": post.content,
}
for post in Post.query.all()
],
}
)
except Exception as err:
# If anything goes wrong, log the error.
# You can later access the log data in the AWS console.
print(str(err), file=sys.stderr)
return jsonify({"message": "error", "error": str(err)})
@app.route("/posts", methods=["POST"])
def create_post():
try:
data = request.get_json()
if not "title" in data or not "authorEmail" in data:
raise Exception('"title" and "authorEmail" are required.')
post = Post(
authorEmail=data["authorEmail"],
title=data["title"],
content=data["content"] if "content" in data else None,
)
db.session.add(post)
db.session.commit()
return jsonify(
{
"message": "success",
"data": {
"title": post.title,
"authorEmail": post.authorEmail,
"content": post.content,
},
}
)
except Exception as err:
print(str(err), file=sys.stderr)
return jsonify({"message": "error", "error": str(err)})
if __name__ == "__main__":
from waitress import serve
port = getenv("PORT", 3000)
serve(app, host="0.0.0.0", port=port)