This repository has been archived by the owner on Apr 30, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
articles.py
137 lines (102 loc) · 3.25 KB
/
articles.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#!/usr/bin/env python
#
# Copyright 2017 Gianni Valdambrini, Develer s.r.l. <[email protected]>
# All rights reserved.
from flask import Flask
from flask_restful import Api
from flask_restful import reqparse
from flask_restful import Resource
from flask_cors import CORS, cross_origin
from http.client import CREATED
from http.client import NO_CONTENT
from http.client import NOT_FOUND
from http.client import OK
from peewee import CharField
from peewee import Model
from peewee import SqliteDatabase
from peewee import UUIDField
import uuid
app = Flask(__name__)
api = Api(app)
CORS(app)
DATABASE_FN = 'articles.db'
database = SqliteDatabase(DATABASE_FN)
@app.before_request
def _db_connect():
if database.is_closed():
database.connect()
@app.teardown_request
def _db_close(exc):
if not database.is_closed():
database.close()
class BaseModel(Model):
class Meta:
database = database
class ArticleModel(BaseModel):
aid = UUIDField(unique=True)
title = CharField()
content = CharField()
def json(self):
return {
'aid': str(self.aid),
'title': self.title,
'content': self.content
}
def create_tables():
database.connect()
ArticleModel.create_table(fail_silently=True)
def add_dummy_data():
for i in range(10):
ArticleModel.create(title="Title {}".format(
i), content="Content {}".format(i), aid=uuid.uuid4())
def non_empty_str(val, name):
if not str(val).strip():
raise ValueError('The argument {} is not empty'.format(name))
return str(val)
class Articles(Resource):
"""Article collection endpoints"""
def get(self):
return [o.json() for o in ArticleModel.select()], OK
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('title', type=non_empty_str, required=True)
parser.add_argument('content', type=non_empty_str, required=True)
args = parser.parse_args(strict=True)
obj = ArticleModel.create(
aid=uuid.uuid4(),
title=args['title'],
content=args['content']
)
return obj.json(), CREATED
class Article(Resource):
"""Article endpoints"""
def get(self, aid):
try:
return ArticleModel.get(aid=aid).json(), OK
except ArticleModel.DoesNotExist:
return None, NOT_FOUND
def put(self, aid):
try:
obj = ArticleModel.get(aid=aid)
except ArticleModel.DoesNotExist:
return None, NOT_FOUND
parser = reqparse.RequestParser()
parser.add_argument('title', type=non_empty_str, required=True)
parser.add_argument('content', type=non_empty_str, required=True)
args = parser.parse_args(strict=True)
obj.title = args['title']
obj.content = args['content']
obj.save()
return obj.json(), OK
def delete(self, aid):
try:
obj = ArticleModel.get(aid=aid)
except ArticleModel.DoesNotExist:
return None, NOT_FOUND
obj.delete_instance()
return None, NO_CONTENT
create_tables()
api.add_resource(Articles, '/articles/')
api.add_resource(Article, '/articles/<uuid:aid>')
if __name__ == '__main__':
app.run(debug=True)