def push_notify_expired_contracts(expiring_contracts):
for contract in expiring_contracts:
try:
provider_name = Provider.query.filter(Provider.id==Contract.provider_id).one()
except (NoResultFound, MultipleResultsFound) as e:
err = "No valid provider associated with contract (id={}).".format(contract.id)
print_log(err)
raise InvalidUsage(message=err, status_code=500)
res = client.send(contract.user.phone_id,
"Your contract with \"{}\" is expiring soon!".format(provider_name))
if res.errors:
print_log(res.errors)
python类MultipleResultsFound()的实例源码
def patch_users_contracts():
contract_id = g.req.data.get('contract_id')
try:
contract = Contract.query.filter(Contract.id == contract_id).one()
except (NoResultFound, MultipleResultsFound) as e:
raise InvalidUsage(message="Failed to due to invalid contract ID.")
provider_name = g.req.data.get('provider_name')
if provider_name:
contract.provider_name = str(provider_name)
rate = g.req.data.get('rate')
if rate:
contract.rate = float(rate)
expiration = g.req.data.get('expiration')
if expiration:
contract.expiration=datetime.strptime(expiration, '%m/%d/%y')
term = g.req.data.get('term')
if term:
contract.term = str(term)
cancellation = g.req.data.get('cancellation')
if cancellation:
contract.cancellation = str(cancellation)
enrollment = g.req.data.get('enrollment')
if enrollment:
contract.enrollment = str(enrollment)
db.session.add(contract)
db.session.commit()
g.res.message = "Updated existing contract with id \"{}\".".format(contract.id)
return jsonify(g.res)
# DELETE /users/contracts/<contract_id>
def post_users_login():
try:
user = user_from_attribute('email', g.req.data.get('email'))
except NoResultFound:
raise InvalidUsage(message="No user exists with the provided e-mail address.")
except MultipleResultsFound:
raise InvalidUsage(message="Multiple, identical e-mail addresses found.",
status_code=500)
if not password_matches_user(g.req.data.get('password'), user=user):
raise InvalidUsage(message="Password is invalid.")
# Ensure that there are never any collisions with user tokens.
# Guaranteed with unique constraint for User.token.
while True:
user.token = generate_user_token()
db.session.add(user)
try:
db.session.commit()
break
except IntegrityError:
print_log("Failed generating user token due to collision, retrying...")
g.res.update_data({'user': {'token': user.token}})
g.res.message = "User with id \"{}\" was logged in.".format(user.id)
return jsonify(g.res)
# POST /users/logout/
def create_seasons(session, start_yr, end_yr):
"""
Adds Years and calendar and European Seasons records to database.
:param session: Transaction session object.
:param start_yr: Start of year interval.
:param end_yr: End of year interval, inclusive.
"""
def exists(model, **conditions):
return session.query(model).filter_by(**conditions).count() != 0
logger.info("Creating Years between {0} and {1}...".format(start_yr, end_yr))
year_range = range(start_yr, end_yr+1)
for yr in year_range:
if not exists(Years, yr=yr):
session.add(Years(yr=yr))
session.commit()
session.flush()
logger.info("Creating Seasons...")
# insert calendar year season record
for year in year_range:
try:
yr_obj = session.query(Years).filter_by(yr=year).one()
except NoResultFound:
logger.error("Cannot insert Season record: {} not in database".format(year))
continue
except MultipleResultsFound:
logger.error("Cannot insert Season record: multiple {} records in database".format(year))
continue
if not exists(Seasons, start_year=yr_obj, end_year=yr_obj):
logger.info("Creating record for {0} season".format(yr_obj.yr))
season_record = Seasons(start_year=yr_obj, end_year=yr_obj)
session.add(season_record)
# insert European season record
for start, end in zip(year_range[:-1], year_range[1:]):
try:
start_yr_obj = session.query(Years).filter_by(yr=start).one()
end_yr_obj = session.query(Years).filter_by(yr=end).one()
except NoResultFound:
logger.error("Cannot insert Season record: {} or {} not in database".format(start, end))
continue
except MultipleResultsFound:
logger.error("Cannot insert Season record: multiple {} or {} records in database".format(start, end))
continue
if not exists(Seasons, start_year=start_yr_obj, end_year=end_yr_obj):
logger.info("Creating record for {0}-{1} season".format(start_yr_obj.yr, end_yr_obj.yr))
season_record = Seasons(start_year=start_yr_obj, end_year=end_yr_obj)
session.add(season_record)
session.commit()
logger.info("Season records committed to database")
logger.info("Season creation complete.")
def get_measurement(measurement_id):
# XXX this query is SUPER slow
m = RE_MSM_ID.match(measurement_id)
if not m:
raise BadRequest("Invalid measurement_id")
msm_no = int(m.group(1))
q = current_app.db_session.query(
Measurement.report_no.label('report_no'),
Measurement.frame_off.label('frame_off'),
Measurement.frame_size.label('frame_size'),
Measurement.intra_off.label('intra_off'),
Measurement.intra_size.label('intra_size'),
Report.report_no.label('r_report_no'),
Report.autoclaved_no.label('r_autoclaved_no'),
Autoclaved.filename.label('a_filename'),
Autoclaved.autoclaved_no.label('a_autoclaved_no'),
).filter(Measurement.msm_no == msm_no)\
.join(Report, Report.report_no == Measurement.report_no)\
.join(Autoclaved, Autoclaved.autoclaved_no == Report.autoclaved_no)
try:
msmt = q.one()
except exc.MultipleResultsFound:
current_app.logger.warning("Duplicate rows for measurement_id: %s" % measurement_id)
msmt = q.first()
except exc.NoResultFound:
# XXX we should actually return a 404 here
raise BadRequest("No measurement found")
# Usual size of LZ4 frames is 256kb of decompressed text.
# Largest size of LZ4 frame was ~55Mb compressed and ~56Mb decompressed. :-/
range_header = "bytes={}-{}".format(msmt.frame_off, msmt.frame_off + msmt.frame_size - 1)
r = requests.get(urljoin(current_app.config['AUTOCLAVED_BASE_URL'], msmt.a_filename),
headers={"Range": range_header})
r.raise_for_status()
blob = r.content
if len(blob) != msmt.frame_size:
raise RuntimeError('Failed to fetch LZ4 frame', len(blob), msmt.frame_size)
blob = lz4framed.decompress(blob)[msmt.intra_off:msmt.intra_off+msmt.intra_size]
if len(blob) != msmt.intra_size or blob[:1] != b'{' or blob[-1:] != b'}':
raise RuntimeError('Failed to decompress LZ4 frame to measurement.json', len(blob), msmt.intra_size, blob[:1], blob[-1:])
# There is no replacement of `measurement_id` with `msm_no` or anything
# else to keep sanity. Maybe it'll happen as part of orchestration update.
# Also, blob is not decoded intentionally to save CPU
return current_app.response_class(
blob,
mimetype=current_app.config['JSONIFY_MIMETYPE']
)
def get_category_by_name(session, name):
'''
Get the category matching a name.
- Category name can be a simple name, or a full path to a category
inside the Category hierarchy.
- A full path consists of a sequence of category names separated by
'->' e.g. 'Refined->Gasoline'
'''
full_path = name.split('->')
if len(full_path) > 1:
# traverse the path
try:
cat_obj = (session.query(Category)
.filter(Category.name == full_path[0])
.filter(Category.parent == None)
.one())
for cat_name in full_path[1:]:
matching_catlist = [c for c in cat_obj.children
if c.name == cat_name]
if len(matching_catlist) > 1:
raise MultipleResultsFound('One matching child Category '
'required, found {} categories '
'matching the name {}'
.format(len(matching_catlist),
cat_name))
elif len(matching_catlist) == 0:
raise NoResultFound('child Category matching the name {} '
'not found'
.format(cat_name))
cat_obj = matching_catlist[0]
except Exception:
cat_obj = None
else:
# just a simple name
try:
cat_obj = (session.query(Category)
.filter(Category.name == name).one())
except Exception:
cat_obj = None
return cat_obj
def __init__(self, app_token: str, timestamp: float, data=None):
""" Initialize a request given an app token, a request-sent timestamp, and additional data
provided from the caller. App token and timestamp validation will be performed.
Parameters
----------
app_token : str
Allows ability to validate that request is from a valid caller.
timestamp : float
When the the original request was sent, used for ensuring requests are recent.
data : dict, optional
Additional information supplied by the caller.
"""
if not data:
data = {}
# App Token provided with the request.
if not app_token:
raise InvalidRequestError('No app token.')
if not validate_app_token(app_token):
raise InvalidRequestError('Invalid app token.')
self.app_token = app_token
# Set request timestamp.
timestamp = floor_unix_epoch(timestamp)
time_limit = floor_unix_epoch(time.time() - EXPIRATION_SECONDS)
if time_limit > timestamp:
raise InvalidRequestError('Request expired.')
self.timestamp = timestamp
# Authentication details.
user_token = data.get("user_token")
email = data.get("email")
if user_token:
try:
if validate_user_token(user_token):
self.user_token = user_token
except (NoResultFound, MultipleResultsFound) as e:
raise InvalidRequestError('Invalid user token: {}'.\
format(str(e)))
try:
self.user = user_from_attribute('token', user_token)
except (NoResultFound, MultipleResultsFound):
self.user = None
elif email:
if "@" not in email:
raise InvalidRequestError('Invalid e-mail address.')
self.email = email
try:
self.user = user_from_attribute('email', email)
except (NoResultFound, MultipleResultsFound):
self.user = None
else:
raise InvalidRequestError('No authentication provided.')
# Extra data provided with the request.
self.data = data