This repository has been archived by the owner on Dec 9, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathapi_pony.py
191 lines (157 loc) · 5.74 KB
/
api_pony.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Hello Pony.'''
from datetime import datetime, timedelta
from flask import Flask, jsonify, request, render_template, abort
from flask.ext.classy import FlaskView
from pony import orm
from serializers import ItemSerializer, PersonSerializer
class Settings:
DB_PROVIDER = "sqlite"
DB_NAME = "inventory.db"
DEBUG = True
app = Flask(__name__)
app.config.from_object(Settings)
### Models ###
db = orm.Database('sqlite', 'inventory.db', create_db=True)
class Person(db.Entity):
_table_ = 'people'
firstname = orm.Required(unicode, 80, nullable=False)
lastname = orm.Required(unicode, 80, nullable=False)
created = orm.Required(datetime, default=datetime.utcnow)
items = orm.Set("Item")
@property
def n_items(self):
return orm.count(item for item in self.items)
def __repr__(self):
return "<Person '{0} {1}'>".format(self.firstname, self.lastname)
class Item(db.Entity):
_table_ = 'items'
name = orm.Required(unicode, 100, nullable=False)
person = orm.Optional(Person)
checked_out = orm.Required(bool, default=False)
updated = orm.Required(datetime, default=datetime.utcnow)
def __repr__(self):
return '<Item {0!r}>'.format(self.name)
### API ###
class ItemsView(FlaskView):
route_base = '/items/'
def index(self):
'''Get all items.'''
all_items = orm.select(item for item in Item)\
.order_by(orm.desc(Item.updated))[:]
data = ItemSerializer(all_items, many=True).data
return jsonify({"items": data})
def get(self, id):
'''Get an item.'''
try:
item = Item[id]
except orm.ObjectNotFound:
abort(404)
return jsonify(ItemSerializer(item).data)
def post(self):
'''Insert a new item.'''
data = request.json
name = data.get("name", None)
checked_out = data.get('checked_out', False)
if not name:
abort(400)
pid = data.get("person_id")
if pid:
person = Person.get(id=pid) # None if not found
else:
person = None
item = Item(name=name, person=person, checked_out=checked_out)
orm.commit()
return jsonify({"message": "Successfully added new item",
"item": ItemSerializer(item).data}), 201
def delete(self, id):
'''Delete an item.'''
try:
item = Item[id]
except orm.ObjectNotFound:
abort(404)
item.delete()
orm.commit()
return jsonify({"message": "Successfully deleted item.",
"id": id}), 200
def put(self, id):
'''Update an item.'''
try:
item = Item[id]
except orm.ObjectNotFound:
abort(404)
# Update item
item.name = request.json.get("name", item.name)
item.checked_out = request.json.get("checked_out", item.checked_out)
pid = request.json.get("person_id")
if pid:
person = Person.get(id=pid)
item.person = person or item.person
else:
item.person = None
item.updated = datetime.utcnow()
orm.commit()
return jsonify({"message": "Successfully updated item.",
"item": ItemSerializer(item).data})
class PeopleView(FlaskView):
route_base = '/people/'
def index(self):
'''Get all people, ordered by creation date.'''
all_people = orm.select(p for p in Person).order_by(orm.desc(Person.created))[:]
data = PersonSerializer(all_people, many=True, exclude=('created',)).data
return jsonify({"people": data})
def get(self, id):
'''Get a person.'''
try:
person = Person[id]
except orm.ObjectNotFound:
abort(404)
return jsonify(PersonSerializer(person).data)
def post(self):
'''Insert a new person.'''
data = request.json
firstname = data.get("firstname")
lastname = data.get("lastname")
if not firstname or not lastname:
abort(400) # Must specify both first and last name
person = Person(firstname=firstname, lastname=lastname)
orm.commit()
return jsonify({"message": "Successfully added new person.",
"person": PersonSerializer(person).data}), 201
def delete(self, id):
'''Delete a person.'''
try:
person = Person[id]
except orm.ObjectNotFound:
abort(404)
person.delete()
orm.commit()
return jsonify({"message": "Successfully deleted person.",
"id": id}), 200
class RecentCheckoutsView(FlaskView):
'''Demonstrates a more complex query.'''
route_base = '/recentcheckouts/'
def index(self):
'''Return items checked out in the past hour.'''
hour_ago = datetime.utcnow() - timedelta(hours=1)
recent = orm.select(item for item in Item
if item.checked_out and
item.updated > hour_ago)\
.order_by(Item.updated.desc())[:]
return jsonify({"items": ItemSerializer(recent, many=True).data})
@app.route("/")
def home():
return render_template('index.html', orm="Pony ORM")
# Generate object-database mapping
db.generate_mapping(check_tables=False)
# Register views
api_prefix = "/api/v1/"
ItemsView.register(app, route_prefix=api_prefix)
PeopleView.register(app, route_prefix=api_prefix)
RecentCheckoutsView.register(app, route_prefix=api_prefix)
if __name__ == '__main__':
db.create_tables()
# Make sure each thread gets a db session
app.wsgi_app = orm.db_session(app.wsgi_app)
app.run(port=5000)