def update_profile(): session = db.Session() attribs = ['gcm_id', 'email', 'phone_number', 'address', 'blood_type'] response = None if request.data: data = json.loads(request.data) user_id = request.args.get('user_id') user = session.query(db.User).filter_by(user_id=user_id).first() if user: for attr in attribs: val = data.get(attr) if val is not None: setattr(user, attr, val) # trigger update if attr == 'blood_type': user.blood_typeF = session.query( db.BloodType).filter_by(type=val).first() session.commit() response = ApiResponse({'status': 'OK'}) session.close() return response or ApiResponse({ 'status': 'Failed', 'message': 'No data found' })
def gcm_message(): if request.form.get('message'): gcmClient = GCMClient(api_key=os.environ.get('GCM_API_KEY')) alert = { 'subject': 'Subject goes here', # TODO: set a better subject 'message': request.form.get('message') } session = db.Session() gcm_id_list = [user.gcm_id for user in session.query(db.User).all()] session.close() response = gcmClient.send(gcm_id_list, alert, time_to_live=3600) if response: return ApiResponse({ 'message': 'Mesazhi u dergua' }) else: return ApiResponse({ 'message': 'Father, why have you forsaken me?' }) else: return ApiResponse({ 'message': 'Can\'t send a blank message...' })
def get_campaigns_by_bloodtype(): session = db.Session() user_id = request.args.get('user_id', 0) # filter by user Blood Type user = session.query(db.User).filter_by(user_id=user_id).first() if not user: session.close() return ApiResponse({ 'status': 'error', 'message': 'No user with id {0} found'.format(user_id) }) campaigns_blood = session.query( db.CampaignBlood).filter_by(blood_type=user.blood_type).all() campaigns = [{ 'name': c.campaign.name, 'hospital': { 'name': c.campaign.hospital.name, 'latitude': c.campaign.hospital.latitude, 'longitude': c.campaign.hospital.longitude, }, 'message': c.campaign.message, 'start_date': to_timestamp(c.campaign.start_date), 'end_date': to_timestamp(c.campaign.end_date) } for c in campaigns_blood] session.close() # return data return ApiResponse({"campaigns": campaigns})
def user_past_donations(user_id=None): session = db.Session() if user_id is None: user_id = request.args.get('user_id', 0) user = session.query(db.User).filter_by(user_id=user_id).first() if not user: session.close() return ApiResponse({ 'status': 'error', 'message': 'No user with id {0} found'.format(id) }) donations = session.query( db.UserHistory).filter_by(user_id=user.user_id).all() result = { 'user': user.user_id, 'history': [{ 'date': to_timestamp(d.donation_date), 'amount': d.amount, 'hospital': d.hospital.name } for d in donations] } session.close() return ApiResponse({'history': result})
def edit_user_blood_type(): valid_blood_types = { 'A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', '0+', '0-' } # @TODO Move form validation in the respective class in db.py session = db.Session() data = json.loads(request.data) user_id = request.args.get('user_id', 0) hospital_id = request.args.get('hospital_id') user = session.query(db.User).filter_by(user_id=user_id).first() user_has_donated = session.query(db.UserHistory).filter_by( user_id=user_id, hospital_id=hospital_id).exists() blood_type = request.args.get('blood_type', '').upper() if not user_has_donated: return ApiResponse({ 'status': 'Error', 'message': 'Permission denied.' }, status='403') if blood_type not in valid_blood_types: return ApiResponse({ 'status': 'Error', 'message': 'Bad request: %s is not a valid blood type' % blood_type, }, status='400') user.blood_type = blood_type user.blood_typeF = session.query(db.BloodType).filter_by(type=blood_type).first() session.commit() return ApiResponse({ 'status': 'OK' })
def create_campaign(): session = db.Session() data = json.loads(request.data) hospital_id = request.args.get('hospital_id', 0) # hospital = session.query(db.Hospital).filter_by(_id=hospital_id).first() hospital = session.query(db.Hospital).first() name = data['name'] message = data['message'] bloodtypes = data['bloodtypes'] start_date = datetime.datetime.now() end_date = datetime.datetime.now() + datetime.timedelta(days=10) campaign = db.Campaign(hospital._id, name, message, start_date, end_date) session.add(campaign) session.commit() for bloodtype in bloodtypes: campaign_blood = db.CampaignBlood(campaign._id, bloodtype) session.add(campaign_blood) session.commit() gcmClient = GCMClient(api_key=os.environ.get('GCM_API_KEY')) alert = { 'subject': 'Fushate e re', 'message': campaign.hospital.name, 'data': { 'id': campaign._id, 'name': name, 'hospital': { 'name': campaign.hospital.name, 'latitude': campaign.hospital.latitude, 'longitude': campaign.hospital.longitude, }, 'message': message, 'start_date': to_timestamp(start_date), 'end_date': to_timestamp(end_date) } } interested_users = session.query(db.User).filter(db.User.blood_type.in_(bloodtypes)) gcm_id_list = [user.gcm_id for user in interested_users] session.close() response = gcmClient.send(gcm_id_list, alert, time_to_live=3600) if response: return ApiResponse({ 'status': 'ok' }) else: return ApiResponse({ 'status': 'some error occurred' })
def post(self, *args, **kwargs): form = UploadRecognizeFileForm(self.request.POST, self.request.FILES) if form.is_valid(): res = self.client.plantDetect( form.cleaned_data.get('image').read()) name = res.get('result')[0].get('name') score = res.get('result')[0].get('score') return ApiResponse({'name': name, 'score': score}) else: logger.error("上传失败" + form.errors) return ApiResponse(message="上传失败")
def login(): data = json.loads(request.data) user_id = data['user_id'] gcmID = data['gcmID'] fb_token = data['fb_token'] payload = {'access_token': fb_token, 'fields': 'id'} fb_response = requests.get(config.FB_ENDPOINT, params=payload).json() if 'error' in fb_response: return ApiResponse(config.ACCESS_DENIED_MSG, status='403') elif user_id != fb_response['id']: return ApiResponse(config.ACCESS_DENIED_MSG, status='403') # Facebook login was successful user = session.query(User).filter_by(user_id=user_id).first() gcm_id = request.args.get('gcm_id', '') blood_type = request.args.get('blood_type', '') if user: user.fb_token = fb_token token, expires_at = User.generate_session_token() user.session_token = token user.session_token_expires_at = expires_at if gcm_id: user.gcm_id = gcm_id if blood_type: user.blood_type = blood_type session.commit() else: user = User(user_id, fb_token=fb_token, gcm_id=gcm_id, blood_type=blood_type) session.add(user) session.commit() if user: return ApiResponse({ 'status': 'OK', 'session_token': user.session_token, 'expires_at': to_timestamp(user.session_token_expires_at) }) else: return ApiResponse({ 'status': 'Failed', 'message': "Couldn't create new user" })
def login(): session = db.Session() data = json.loads(request.data) user_id = data['user_id'] gcm_id = data['gcm_id'] fb_token = data['fb_token'] payload = {'access_token': fb_token, 'fields': ['id', 'name']} fb_response = requests.get(config.FB_ENDPOINT, params=payload).json() if 'error' in fb_response: return ApiResponse(config.ACCESS_DENIED_MSG, status='403') elif user_id != fb_response['id']: return ApiResponse(config.ACCESS_DENIED_MSG, status='403') # Facebook login was successful user = session.query(db.User).filter_by(user_id=user_id).first() if user: user.fb_token = fb_token token, expires_at = db.User.generate_session_token() user.session_token = token user.session_token_expires_at = expires_at if gcm_id: user.gcm_id = gcm_id else: name = fb_response['name'].split() user = db.User(user_id, name[0], name[-1], fb_token=fb_token, gcm_id=gcm_id) #blood_type=blood_type) session.add(user) session.commit() response = ApiResponse( { 'status': 'OK', 'session_token': user.session_token, 'expires_at': to_timestamp(user.session_token_expires_at) } if user else { 'status': 'Failed', 'message': "Couldn't create new user" }) session.close() return response
def reactivate_campaign(campaign_id): session = db.Session() campaign = session.query(db.Campaign).filter_by(_id=campaign_id).first() if not campaign: session.close() response = ApiResponse({ 'status': 'wrong campaign id' }) else: campaign.activate() session.add(campaign) session.commit() response = ApiResponse({ 'status': 'ok' }) session.close() return response
def safe_handler(*args, **kwargs): session_token = request.args.get('session_token', '') user_id = request.args.get('user_id', 0) user = session.query(User).filter_by(user_id=user_id).first() sleep_amount = random.random()/5 if user and utils.str_equal(user.session_token, session_token) and \ utils.to_timestamp(user.session_token_expires_at) > time.time(): return handler(*args, **kwargs) else: time.sleep(sleep_amount) return ApiResponse(config.ACCESS_DENIED_MSG, status='403')
def logout(): session = db.Session() hospital_id = request.args.get('hospital_id', 0) # TODO: shiko per injection hospital = session.query(db.Hospital).filter_by(_id=hospital_id).first() hospital.logout() session.add(hospital) session.commit() session.close() return ApiResponse({ 'status': 'ok' })
def safe_handler(*args, **kwargs): session = db.Session() session_token = request.args.get('session_token', '') user_id = request.args.get('user_id', 0) user = session.query(db.User).filter_by(user_id=user_id).first() if user and utils.str_equal(user.session_token, session_token) and \ utils.to_timestamp(user.session_token_expires_at) > time.time(): response = handler(*args, **kwargs) else: response = ApiResponse(config.ACCESS_DENIED_MSG, status='403') session.close() return response
def demo_user_history(id): session = db.Session() user = session.query(db.User).filter_by(user_id=id).first() if not user: return ApiResponse({ 'status': 'error', 'message': 'No user with id {0} found'.format(id) }) donations = session.query(db.UserHistory).filter_by(user_id=user.user_id).all() result = { 'user': user.user_id, 'history': [{ 'date': str(d.donation_date), 'amount': d.amount, 'hospital': d.hospital.name } for d in donations] } session.close() return ApiResponse({ 'history': result })
def safe_handler(*args, **kwargs): session = db.Session() session_token = request.args.get('session_token', '') hospital_id = request.args.get('hospital_id', 0) print hospital_id hospital = session.query(db.Hospital).filter_by(_id=hospital_id).first() if hospital and hospital.session_token and \ utils.str_equal(hospital.session_token, session_token): response = handler(*args, **kwargs) else: response = ApiResponse(config.ACCESS_DENIED_MSG, status='403') session.close() return response
def login_hospital(): data = json.loads(request.data) username = data['username'] password = data['password'].encode('ascii', 'replace') session = db.Session() h = session.query(db.Hospital).filter_by(username=username).first() pwd = h.password.encode('ascii', 'replace') if not h or bcrypt.hashpw(password, pwd) != pwd: session.close() return ApiResponse(config.ACCESS_DENIED_MSG, status='403') h.login() session.add(h) session.commit() response = ApiResponse({ 'id': h._id, 'session_token': h.session_token }) session.close() return response
def get_users(): session = db.Session() response = ApiResponse([{ 'user_id': x.user_id, 'blood_type': x.blood_type, 'email': x.email, 'address': x.address, 'phone_number': x.phone_number, 'first_name': x.first_name, 'last_name': x.last_name } for x in session.query(db.User).all()]) session.close() return response
def all_hospitals(): session = db.Session() hospitals = session.query(db.Hospital).all() response = ApiResponse({ 'hospitals': [{ 'id': h._id, 'name': h.name, 'email': h.email, 'address': h.address, 'contact': h.contact, 'latitude': h.latitude, 'longitude': h.longitude } for h in hospitals] }) session.close() return response
def get_profile(): session = db.Session() user_id = request.args.get('user_id', 0) user = session.query(db.User).filter_by(user_id=user_id).first() response = ApiResponse({ 'gcm_id': user.gcm_id, 'blood_type': user.blood_type, 'email': user.email, 'phone_number': user.phone_number, 'address': user.address } if user else { 'status': 'Failed', 'message': 'Wrong data' }) session.close() return response
def demo_history(): session = db.Session() users = session.query(db.User).all() result = [] for u in users: donations = session.query(db.UserHistory).filter_by(user_id=u.user_id).all() result.append({ 'user': u.user_id, 'history': [{ 'date': str(d.donation_date), 'amount': d.amount, 'hospital': d.hospital.name } for d in donations] }) session.close() return ApiResponse({ 'history': result })
def all_campaigns(): session = db.Session() hospital_id = request.args.get('hospital_id', 0) #campaigns = session.query(db.Campaign).filter_by(hospital_id=hospital_id).all() campaigns = session.query(db.Campaign).all() bloodtypes = session.query() response = ApiResponse({ 'campaigns': [ { 'id': c._id, 'name': c.name, 'message': c.message, 'start_date': to_timestamp(c.start_date), 'end_date': to_timestamp(c.end_date), 'active': c.active, 'bloodtypes': [r.blood_type for r in c.requirement] } for c in campaigns] }) session.close() return response
def version(): return ApiResponse({ "version": config.API_VERSION, })
def get_blood_types(): session = db.Session() response = ApiResponse([x.type for x in session.query(db.BloodType).all()]) session.close() return response
def hello(): return ApiResponse({ "message": "To every action, there is always opposed an equal reaction. | Sir Isaac Newton |" })