I'm using the following function to process API parameters for an specific endpoint. Using SQLAlchemy and Flask, I want to get feedback in terms of simplifying calling SQL code and nested statements.
date_filter = r'\d{4}-((1[0-2]|[1-9])|0[1-9])-((3[01]|[12][0-9]|[1-9])|0[1-9])'
def bits_filter(request):
"""
:param request:
:return:(Model.Bits) List of bits
"""
# Get parameters.
log.info('/bits request: %s', request)
# Date parameters.
date_value = request.args.get('date')
# Bit or newsletter.
bit_type_value = request.args.get('bit_type')
# Process parameters.
date_value = date_value or settings.DATE_VALUE
bit_type = bit_type_value or settings.BIT_TYPE
log.info('bit_type: %r', bit_type)
if date_value and isinstance(date_value, unicode):
# Bit type.
if date_value.lower() == u'latest':
return Model.Bits.query.filter(Model.Bits.bit_type == bit_type).order_by(
Model.Bits.published.desc()).limit(settings.max_bits).all()
# Dated format.
elif re.match(date_filter, date_value):
return Model.Bits.query.filter(
Model.Bits.bit_type == bit_type & Model.Bits.published == date_value).limit(
settings.max_bits).all()
else:
log.error('Invalid date value parameter: %r', date_value)
return None
else:
return Model.Bits.query.filter(Model.Bits.bit_type == bit_type).order_by(
Model.Bits.published.desc()).limit(settings.max_bits).all()