Skip to content

Instantly share code, notes, and snippets.

@yuriwoof
Created December 31, 2016 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuriwoof/508a147955a05d51e0c4c1a1c5824b10 to your computer and use it in GitHub Desktop.
Save yuriwoof/508a147955a05d51e0c4c1a1c5824b10 to your computer and use it in GitHub Desktop.
petstore/default_controller.py
import logging
import datetime
from connexion import NoContent
from db import db_session
from models import Pet
from sqlalchemy import or_
logger = logging.getLogger(__name__)
def add_pet(pet):
print(pet)
# すでに指定したidが登録されているか
p = Pet.query.filter(Pet.id == pet['id']).one_or_none()
# print(p)
if p is not None:
logging.info('Updating pet %s..', id)
p.update(**pet)
else:
logging.info('Creating pet %s..', id)
pet['created'] = datetime.datetime.utcnow()
print(pet)
db_session.add(Pet(**pet))
db_session.commit()
return pet, (200 if p is not None else 201)
def delete_pet(id):
pet = Pet.query.filter(Pet.id == id).one_or_none()
if pet is not None:
logger.info('Deleting pet %s', id)
db_session.delete(pet)
db_session.commit()
return NoContent, 204
else:
return NoContent, 404
def find_pet_by_id(id):
pet = Pet.query.filter(Pet.id == id).one_or_none()
print(pet is None)
if pet is None:
return NoContent, 404
else:
return pet.as_dict(), 200
def find_pets(tags=None, limit=None):
print(tags)
if tags is None:
pets = Pet.query.all()
else:
or_filters = or_(*[Pet.tag == tag for tag in tags])
print(or_filters)
pets = Pet.query.filter(or_filters).all()
return [pet.as_dict() for pet in pets][:limit]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment