|
| 1 | +import json |
| 2 | +import uuid |
| 3 | + |
| 4 | +from flask import Flask |
| 5 | +from flask import request |
| 6 | +from flask import render_template |
| 7 | + |
| 8 | +from model.post import Post |
| 9 | +from errors import register_error_handlers |
| 10 | + |
| 11 | + |
| 12 | +app = Flask(__name__) |
| 13 | + |
| 14 | +register_error_handlers(app) |
| 15 | + |
| 16 | + |
| 17 | +@app.route("/api/posts", methods = ["POST"]) |
| 18 | +def create_post(): |
| 19 | + post_data = request.get_json(force=True, silent=True) |
| 20 | + if post_data == None: |
| 21 | + return "Bad request", 400 |
| 22 | + post = Post(post_data["title"], post_data["content"]) |
| 23 | + post.save() |
| 24 | + return json.dumps(post.to_dict()), 201 |
| 25 | + |
| 26 | + |
| 27 | +@app.route("/api/posts", methods = ["GET"]) |
| 28 | +def list_posts(): |
| 29 | + result = {"result": []} |
| 30 | + for post in Post.all(): |
| 31 | + result["result"].append(post.to_dict()) |
| 32 | + return json.dumps(result) |
| 33 | + |
| 34 | + |
| 35 | +@app.route("/api/posts/<post_id>", methods = ["GET"]) |
| 36 | +def get_post(post_id): |
| 37 | + return json.dumps(Post.find(post_id).to_dict()) |
| 38 | + |
| 39 | + |
| 40 | +@app.route("/api/posts/<post_id>", methods = ["DELETE"]) |
| 41 | +def delete_post(post_id): |
| 42 | + Post.delete(post_id) |
| 43 | + return "" |
| 44 | + |
| 45 | + |
| 46 | +@app.route("/api/posts/<post_id>", methods = ["PATCH"]) |
| 47 | +def update_post(post_id): |
| 48 | + post_data = request.get_json(force=True, silent=True) |
| 49 | + if post_data == None: |
| 50 | + return "Bad request", 400 |
| 51 | + |
| 52 | + post = Post.find(post_id) |
| 53 | + if "title" in post_data: |
| 54 | + post.title = post_data["title"] |
| 55 | + if "content" in post_data: |
| 56 | + post.content = post_data["content"] |
| 57 | + return json.dumps(post.save().to_dict()) |
| 58 | + |
| 59 | + |
| 60 | +@app.route("/", methods = ["GET"]) |
| 61 | +def posts(): |
| 62 | + return render_template("index.html") |
| 63 | + |
| 64 | + |
| 65 | +@app.route("/posts/<post_id>", methods = ["GET"]) |
| 66 | +def view_post(post_id): |
| 67 | + return render_template("post.html", post=Post.find(post_id)) |
| 68 | + |
| 69 | + |
0 commit comments