-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
58 lines (42 loc) · 1.71 KB
/
app.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
from flask import Flask, request, jsonify
import datetime
app = Flask(__name__)
posts = []
@app.route('/posts/<int:post_id>', methods=['GET'])
def get_post(post_id):
post = next((post for post in posts if post['id'] == post_id), None)
if post is None:
return jsonify({'error': 'Post not found'}), 404
return jsonify(post), 200
@app.route('/posts', methods=['POST'])
def create_post():
if not request.json or not 'title' in request.json or not 'content' in request.json or not 'author' in request.json:
return jsonify({'error': 'Bad Request, missing mandatory parameters'}), 400
post = {
'id': posts[-1]['id'] + 1 if posts else 1,
'title': request.json['title'],
'content': request.json['content'],
'author': request.json['author'],
'time': datetime.datetime.now()
}
posts.append(post)
return jsonify(post), 201
@app.route('/posts/<int:post_id>', methods=['PUT'])
def update_post(post_id):
post = next((post for post in posts if post['id'] == post_id), None)
if post is None:
return jsonify({'error': 'Post is no longer available.'}), 404
post['time'] = datetime.datetime.now()
post.update(
title=request.json.get('title', post['title']),
content=request.json.get('content', post['content']),
author=request.json.get('author', post['author'])
)
return jsonify(post), 200
@app.route('/posts/<int:post_id>', methods=['DELETE'])
def delete_post(post_id):
global posts
posts = [post for post in posts if post['id'] != post_id]
return jsonify({'success': True}), 200
if __name__ == '__main__':
app.run(debug=True)