-
-
Notifications
You must be signed in to change notification settings - Fork 783
Expand file tree
/
Copy pathapp.py
More file actions
executable file
·65 lines (48 loc) · 1.68 KB
/
app.py
File metadata and controls
executable file
·65 lines (48 loc) · 1.68 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
#!/usr/bin/env python3
import datetime
import logging
import connexion
import orm
from connexion import NoContent
db_session = None
def get_pets(limit, animal_type=None):
q = db_session.query(orm.Pet)
if animal_type:
q = q.filter(orm.Pet.animal_type == animal_type)
return [p.dump() for p in q][:limit]
def get_pet(pet_id):
pet = db_session.query(orm.Pet).filter(orm.Pet.id == pet_id).one_or_none()
return pet.dump() if pet is not None else ("Not found", 404)
def put_pet(pet_id, pet):
p = db_session.query(orm.Pet).filter(orm.Pet.id == pet_id).one_or_none()
pet["id"] = pet_id
if p is not None:
logging.info("Updating pet %s..", pet_id)
p.update(**pet)
else:
logging.info("Creating pet %s..", pet_id)
pet["created"] = datetime.datetime.now(tz=datetime.timezone.utc).replace(
tzinfo=None
)
db_session.add(orm.Pet(**pet))
db_session.commit()
return NoContent, (200 if p is not None else 201)
def delete_pet(pet_id):
pet = db_session.query(orm.Pet).filter(orm.Pet.id == pet_id).one_or_none()
if pet is not None:
logging.info("Deleting pet %s..", pet_id)
db_session.query(orm.Pet).filter(orm.Pet.id == pet_id).delete()
db_session.commit()
return NoContent, 204
else:
return NoContent, 404
logging.basicConfig(level=logging.INFO)
db_session = orm.init_db("sqlite:///:memory:")
app = connexion.FlaskApp(__name__)
app.add_api("openapi.yaml")
application = app.app
@application.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
if __name__ == "__main__":
app.run(port=8081, use_reloader=False, threaded=False)