def get(self, id): try: _qrg = """ SELECT array_to_json(array_agg(row_to_json(t) )) as collection FROM ( SELECT id, name, description, completed_at FROM %s WHERE deleted_at IS NULL AND completed_at is NULL and create_id=%s and id = %s)t; """ % ( self._table, g.user.id, id, ) g.db_conn.execute(_qrg) if g.db_conn.count() > 0: _collection = g.db_conn.one()[0] if _collection: _data = {self._table: _collection} _get = processing_rest_success(data=_data) else: raise ExceptionRest( status_code=404, message="No se han encontrado resultados") else: raise ExceptionRest(status_code=404, message="No se han encontrado resultados") except (Exception, ExceptionRest), e: _get = processing_rest_exception(e)
def get(self): try: _where = " WHERE deleted_at is null " _by = request.args.get("by", False) if _by: if _by == 'project_task_participed_id': _project_task_id = request.args.get('project_task_participed_id', False) _where = _where + " and project_task_participed_id=%s " % (_project_task_id,) else: _where = _where + " and create_id =%s " % (g.user.id,) else: _where = _where + " and create_id =%s " % (g.user.id,) _completed = request.args.get("completed") if _completed == 'True' or _completed == 'true': _where = _where + " and completed_at is not null " elif _completed == 'False' or _completed == 'false': _where = _where + " and completed_at is null " _qrg = self._query_get % _where g.db_conn.execute(_qrg) if g.db_conn.count() > 0: _collection = g.db_conn.one()[0] if _collection: _data = {self._table: _collection} _get = processing_rest_success(data=_data) else: raise ExceptionRest(status_code=404, message="No se han encontrado resultados") else: raise ExceptionRest(status_code=404, message="No se han encontrado resultados") except (Exception, ExceptionRest), e: _get = processing_rest_exception(e)
def put(self, id): _request = request.json try: _errors = validate_rest(fields=self._fields, request=_request, method='put') if not _errors: _val = type_of_update_rest(self._fields, _request) _qrp = "UPDATE %s SET %s WHERE id=%s;" % ( self._table, _val, id, ) g.db_conn.execute(_qrp) if g.db_conn.count() > 0: _put = processing_rest_success( status_code=201, message="El registro fue actualizado correctamente") else: raise ExceptionRest( status_code=404, message= "No se ha podido encontrar el registro, para actualizar." ) else: raise ExceptionRest(status_code=400, errors=_errors) except (Exception, ExceptionRest), e: _put = processing_rest_exception(e)
def put(self, id): _request = request.json try: _errors = validate_rest(fields=self._fields, request=_request, method='put') if not _errors: _val = type_of_update_rest(self._fields, _request) _qrp = "UPDATE %s SET %s WHERE id=%s;" % ( self._table, _val, id, ) g.db_conn.execute(_qrp) if g.db_conn.count() > 0: _put = processing_rest_success( status_code=201, message=_("The record was successfully updated")) else: raise ExceptionRest(status_code=404, message=_("Not found record")) else: raise ExceptionRest(status_code=400, errors=_errors) except (Exception, ExceptionRest), e: _put = processing_rest_exception(e)
def post(self): _request = request.json try: if 'assigned_user_id' not in _request: _request['assigned_user_id'] = g.user.id print _request _errors = validate_rest(fields=self._fields, request=_request) if not _errors: _col, _val = type_of_insert_rest(self._fields, _request) _qrp = """ INSERT INTO %s (create_id , %s ) VALUES (%s, %s) RETURNING (select row_to_json(collection) FROM (VALUES(id)) collection(id)); """ % (self._table, _col, g.user.id, _val) g.db_conn.execute(_qrp) if g.db_conn.count() > 0: _data = {self._table: g.db_conn.one()} _post = processing_rest_success( data=_data, message='Fue creado correctamente', status_code=201) else: raise ExceptionRest(status_code=500, message='No se ha podido registrar') else: raise ExceptionRest(status_code=400, errors=_errors) except (Exception, ExceptionRest), e: _post = processing_rest_exception(e)
def get(self, id): try: _qrg = """ SELECT array_to_json(array_agg(row_to_json(t) )) as collection FROM ( SELECT id, created_at, name, reach_goal,reward ,due_date_at, completed_at FROM %s WHERE deleted_at is null and completed_at is null and create_id=%s and id = %s)t; """ % ( self._table, g.user.id, id, ) g.db_conn.execute(_qrg) if g.db_conn.count() > 0: _collection = g.db_conn.one()[0] if _collection: _data = {self._table: _collection} _get = processing_rest_success(data=_data) else: raise ExceptionRest(status_code=404, message=_("Not found record")) else: raise ExceptionRest(status_code=404, message=_("Not found record")) except (Exception, ExceptionRest), e: _get = processing_rest_exception(e)
def get(self): try: where1 = " and id not in ( (select project_id from project_teams_projects where user_id = %s) ) " \ " and create_id =%s " % (g.user.id, g.user.id, ) where2 = " and ptp.user_id =%s " % (g.user.id, ) _completed = request.args.get("completed") if _completed == 'True' or _completed == 'true': where1 = where1 + " and completed_at is not null " where2 = where2 + " and p.completed_at is not null " elif _completed == 'False' or _completed == 'false': where1 = where1 + " and completed_at is null " where2 = where2 + " and p.completed_at is null " _qrg = self._query_get % (where1, where2) g.db_conn.execute(_qrg) if g.db_conn.count() > 0: _collection = g.db_conn.one()[0] if _collection: _data = {self._table: _collection} _get = processing_rest_success(data=_data) else: raise ExceptionRest(status_code=404, message="No se han encontrado resultados") else: raise ExceptionRest(status_code=404, message="No se han encontrado resultados") except (Exception, ExceptionRest), e: _get = processing_rest_exception(e)
def post(self): _request = request.json try: _errors = validate_rest(fields=self._fields, request=_request) if not _errors: _col, _val = type_of_insert_rest(self._fields, _request) _qrp = """ INSERT INTO %s (create_id, %s) VALUES (%s,%s) RETURNING (select row_to_json(collection) FROM (VALUES(id)) collection(id)); """ % (self._table, _col, g.user.id, _val) g.db_conn.execute(_qrp) if g.db_conn.count() > 0: _data = g.db_conn.one() # add default 4 columns for _column in ['Today', 'Tomorrow', 'Upcoming', 'Someday']: qryIprojectTask = """ INSERT INTO project_tasks (create_id, name, project_id) VALUES ({}, '{}',{}) """.format(g.user.id, _column, _data[0]['id']) g.db_conn.execute(qryIprojectTask) _data = {self._table: _data} _post = processing_rest_success(data=_data, message='El proyecto fue creado correctamente', status_code=201) else: raise ExceptionRest(status_code=500, message='No se ha podido registrar el proyecto.') else: raise ExceptionRest(status_code=400, errors=_errors) except (Exception, ExceptionRest), e: _post = processing_rest_exception(e)
def get(self): try: _resource = request.args.get("resource", 'all') if _resource == 'habit': _resource_id = request.args.get("resource_id", 0) _qrg = """ SELECT array_to_json(array_agg(row_to_json(t) )) as collection FROM ( SELECT * FROM {} WHERE deleted_at IS NULL and resource='habit' and resource_id ={})t; """.format(self._table, _resource_id) g.db_conn.execute(_qrg) if g.db_conn.count() > 0: _data = g.db_conn.one()[0] if _data: _get = processing_rest_success( data={self._table: _data}) else: raise ExceptionRest(status_code=404, message=_("Not found record")) else: raise ExceptionRest(status_code=404, message=_("Not found record")) else: raise ExceptionRest(status_code=400, message=_("Bad request")) except (Exception, ExceptionRest), e: _get = processing_rest_exception(e)
def put(self, reminder_id): _request = request.json try: _params = _request.get('params', None) val_params = '' if _params: del _request['params'] val_params = " params=cast('{}' as json), ".format( json.dumps(_params)) _errors = validate_rest(fields=self._fields, request=_request, method="put") if not _errors: _val = type_of_update_rest(self._fields, _request) _qrp = "UPDATE {} SET {} last_datetime_notify=NULL, {} WHERE id={};".format( self._table, val_params, _val, reminder_id) print _qrp g.db_conn.execute(_qrp) if g.db_conn.count() > 0: _put = processing_rest_success( status_code=200, message=_("The record was successfully updated")) else: raise ExceptionRest(status_code=404, message=_("Not found record")) else: raise ExceptionRest(status_code=400, errors=_errors) except (Exception, ExceptionRest), e: _put = processing_rest_exception(e)
def account_exists(self, email): id = False _qry = \ """ SELECT id FROM users WHERE email= '{}' and (google_plus != '' OR facebook != ''); """.format(email) g.db_conn.execute(_qry) if g.db_conn.count() > 0: id = g.db_conn.one()[0] _token = str(uuid.uuid4()) _qry_token = """ select token ('create', '{}', {},'reset-password'); """.format(_token, id) g.db_conn.execute(_qry_token) if g.db_conn.count() > 0: _new_token = g.db_conn.one()[0] _url = request.url_root + 'reset/password?token=' + _new_token self.template_email_reset_password(email, _url) else: raise ExceptionRest( status_code=400, message= 'Error al generar el token, vuelva a intentar mas tarde!') else: raise ExceptionRest(status_code=400, message='La cuenta no esta registrada!') return id
def get(self): try: _get = request.args.get("get", False) _qrg = '' # """ # SELECT array_to_json(array_agg(row_to_json(t) )) as collection # FROM ( SELECT id, email, name, last_name FROM %s WHERE # deleted_at IS NULL AND create_id=%s )t; # """ % (self._table, g.user.id,) if _get == 'team': _by = request.args.get('by', False) if _by == 'project_task_id': _project_task_id = request.args.get( 'project_task_id', False) _qrg = """ SELECT array_to_json(array_agg(row_to_json(t) )) as collection FROM ( SELECT id, email, name, last_name FROM users WHERE id = %s UNION ALL SELECT u.id, u.email, u.name, u.last_name FROM project_teams pt INNER JOIN project_teams_projects ptp ON pt.id = ptp.team_id AND ptp.deleted_at IS NULL AND pt.deleted_at IS NULL INNER JOIN users u ON u.id = ptp.user_id WHERE ptp.project_id = (SELECT project_id FROM project_tasks WHERE id = %s) AND u.id NOT IN (%s) )t; """ % (g.user.id, _project_task_id, g.user.id) else: abort(404) g.db_conn.execute(_qrg) if g.db_conn.count() > 0: _collection = g.db_conn.one()[0] if _collection: _data = {self._table: _collection} _get = processing_rest_success(data=_data) else: raise ExceptionRest( status_code=404, message="No se han encontrado resultados") else: raise ExceptionRest(status_code=404, message="No se han encontrado resultados") except (Exception, ExceptionRest), e: _get = processing_rest_exception(e)
def put(self, history_habit_id): _put = jsonify() try: raise ExceptionRest(status_code=401) _data = request.json qru = "update %s set state ='%s' where user_id=%s and id = %s" % \ (self._table, _data.get('state'), g.user.id, history_habit_id) g.db_conn.execute(qru) if g.db_conn.count() > 0: _put.status_code = 201 else: raise ExceptionRest(status_code=404) except ExceptionRest, e: _put.status_code = e.status_code
def get(self, id): try: _qrg = self._query_get + " WHERE deleted_at is null and id=%s" % (id,) g.db_conn.execute(_qrg) if g.db_conn.count() > 0: _collection = g.db_conn.one()[0] if _collection: _data = {self._table: _collection} _get = processing_rest_success(data=_data) else: raise ExceptionRest(status_code=404, message="No se han encontrado resultados") else: raise ExceptionRest(status_code=404, message="No se han encontrado resultados") except (Exception, ExceptionRest), e: _get = processing_rest_exception(e)
def get(self): try: _qry_params = '' _data = None _activities = request.args.get("activities", False) _statistic = request.args.get('statistic', False) if _statistic: if _statistic == 'week': _data = self.get_statistic_of_the_week(timezone=g.user.timezone, user_id=g.user.id) elif _statistic == 'month': _data = self.get_statistic_of_the_month(timezone=g.user.timezone, user_id=g.user.id) elif _statistic =='year': _data = self.get_statistic_of_the_year(timezone=g.user.timezone, user_id=g.user.id) elif _activities: if _activities == 'registered': _data = self.get_activities_registred(user_id=g.user.id) if _data: _get = processing_rest_success(data=_data, status_code=200) else: raise ExceptionRest(status_code=404, message="No se han encontrado resultados") except (Exception, ExceptionRest), e: _get = processing_rest_exception(e)
def login(self, data): _login = None try: _email = data.get('email') _uid = data.get('uid') _auth = data.get('auth') _token = data.get('token') _mode = data.get('mode', 'app') _errors = [] if not _email: _errors.append({'email': 'Is required'}) if not _uid: _errors.append({'uid': 'Is required'}) if not _auth: _errors.append({'auth': 'Is required'}) if not _token: _errors.append({'token': 'Is required'}) _login = jsonify() if len(_errors) == 0: qry = "SELECT login('%s', '%s', '%s', '%s');" % (_email, _uid, _auth, _token) g.db_conn.execute(qry) if g.db_conn.count() > 0: _data_qry = g.db_conn.one()[0] if _data_qry: _status_code = _data_qry['status_code'] del _data_qry[u'status_code'] if _mode == 'web': # session.pop('X-Authorization', None) # session.pop('User', None) session['X-Authorization'] = _data_qry.get( 'user').get('token') session['user'] = _data_qry.get('user') _login = processing_rest_success( None, status_code=_status_code) else: _login = jsonify(_data_qry) _login.status_code = _status_code else: raise ExceptionRest( status_code=404, message="Verifique su usuario y contrseña") else: raise ExceptionRest(status_code=404, message="El usuario no esta registrado") except (Exception, ExceptionRest), e: _login = processing_rest_exception(e)
def delete(self, id): try: _qrd = "UPDATE %s SET deleted_at=current_timestamp WHERE id=%s;" % (self._table, id) g.db_conn.execute(_qrd) if g.db_conn.count() > 0: _delete = processing_rest_success(status_code=201, message="El registro fue eliminado correctamente") else: raise ExceptionRest(status_code=404, message="No se ha podio encontrar el registro, para eliminar.") except (Exception, ExceptionRest), e: _delete = processing_rest_exception(e)
def get(self, history_habit_id): _get = jsonify() try: g.db_conn.execute( 'select * from %s where user_id =%s and id = %s;' % (self._table, g.user.id, str(history_habit_id))) if g.db_conn.count() > 0: _get = jsonify(tuple2list(self._fields, g.db_conn.fetch())) _get.status_code = 200 else: raise ExceptionRest(status_code=404) except ExceptionRest, e: _get.status_code = e.status_code
def get(self): _get = jsonify() try: _view = request.args.get("view") if not _view: data = g.db_conn.execute( "select * from %s where user_id='%s' order by id asc;" % ( self._table, g.user.id, )) if g.db_conn.count() > 0: _get = jsonify(tuple2list(self._fields, data)) _get.status_code = 200 else: raise ExceptionRest(status_code=404) elif _view == 'current_task': _date = request.args.get("date") _get = jsonify(self.current_task(_date)) _get.status_code = 200 else: raise ExceptionRest(status_code=404) except ExceptionRest, e: _get.status_code = e.status_code
def password_change(): _request = request.json _fields = {'password': {'required': True}, 'token': {'required': True}} try: _errors = validate_rest(fields=_fields, request=_request) if not _errors: _new_password = _request['password'] _token = _request['token'] rpo = ResetPasswordMdl() if rpo.password_change(_new_password, _token): _change = processing_rest_success( data=None, message='La contraseña fue actualizado correctamente!', status_code=200) else: raise ExceptionRest( status_code=400, message= 'Ocurrio un problema al intentar cambiar la contraseña, por favor intenta mas tarde :(' ) else: raise ExceptionRest(status_code=400, errors=_errors) except (Exception, ExceptionRest), e: _change = processing_rest_exception(e)
def get(self): _get = jsonify() try: data = g.db_conn.execute("select * from %s where user_id='%s'" % ( self._table, g.user.id, )) if g.db_conn.count() > 0: _get = tuple2list(self._fields, data) _get = jsonify(_get) _get.status_code = 200 else: raise ExceptionRest(status_code=404) except ExceptionRest, e: _get.status_code = e.status_code
def post(self): _request = request.json try: _errors = validate_rest(fields=self._fields, request=_request) if not _errors: _col, _val = type_of_insert_rest(self._fields, _request) _qrp = """ INSERT INTO %s (create_id , %s ) VALUES (%s, %s) RETURNING (select row_to_json(collection) FROM (VALUES(id)) collection(id)); """ % (self._table, _col, g.user.id, _val) g.db_conn.execute(_qrp) if g.db_conn.count() > 0: _data = {self._table: g.db_conn.one()} _post = processing_rest_success( data=_data, message=_('It was created correctly'), status_code=201) else: raise ExceptionRest(status_code=500, message=_('Unable to register')) else: raise ExceptionRest(status_code=400, errors=_errors) except (Exception, ExceptionRest), e: _post = processing_rest_exception(e)
def post(self): _post = jsonify() try: _data = request.json _insert = [] qri = "insert into %s (user_id, habit_id, state) values(%s, %s, '%s') returning id;" \ % (self._table, g.user.id, _data.get('habit_id'), _data.get('state')) g.db_conn.execute(qri) if g.db_conn.count() > 0: _insert.append({"id": g.db_conn.one()[0]}) _post = jsonify(_insert) _post.status_code = 201 else: raise ExceptionRest(status_code=400) except ExceptionRest, e: _post.status_code = e.status_code
def delete(self, id): try: _qrd = "UPDATE %s SET deleted_at=current_timestamp WHERE id=%s;" % ( self._table, id, ) g.db_conn.execute(_qrd) if g.db_conn.count() > 0: _delete = processing_rest_success( status_code=201, message=_("The record was successfully removed")) else: raise ExceptionRest(status_code=404, message=_("Not found record")) except (Exception, ExceptionRest), e: _delete = processing_rest_exception(e)
def token(): _request = request.json _field = {'email': {'required': True}} try: _errors = validate_rest(fields=_field, request=_request) if not _errors: _email = _request['email'] rpo = ResetPasswordMdl() rpo.account_exists(email=_email) _get = processing_rest_success( data=None, message= 'El token fue enviado correctamente para actualizar su contraseña!', status_code=200) else: raise ExceptionRest(status_code=400, errors=_errors) except (Exception, ExceptionRest), e: _get = processing_rest_exception(e)
def get_by(self): try: _data = [] _by = request.args.get("by", False) _resource = request.args.get("resource", False) _resource_id = request.args.get("resource_id", False) if _by == 'resource': if _resource and _resource_id: _data = self.get_comment_by_resource( _resource, _resource_id) if len(_data) > 0: _data = {self._table: _data} if _data: _get = processing_rest_success(data=_data, status_code=200) else: raise ExceptionRest(status_code=404, message="No se han encontrado resultados") except (Exception, ExceptionRest), e: _get = processing_rest_exception(e)
def current_task(self, _date): _timezone_user = "******" + g.user.timezone + "' " if g.user.timezone else "" _qrs = """ SELECT d.id, d.name, '' state, ( SELECT count(id) FROM history_habits tdh1 WHERE tdh1.habit_id =d.id and tdh1.user_id =d.user_id and tdh1.state='success' ) success , CASE WHEN ( (CAST(current_timestamp AS DATE ) - CAST(d.created_date AS DATE )) - (SELECT count(id) FROM history_habits tdh1 WHERE tdh1.habit_id =d.id and tdh1.user_id =d.user_id and tdh1.state='success') ) >= 0 THEN ( (CAST(current_timestamp AS DATE ) - CAST(d.created_date AS DATE )) - (SELECT count(id) FROM history_habits tdh1 WHERE tdh1.habit_id =d.id and tdh1.user_id =d.user_id and tdh1.state='success') ) ELSE 0 END fail FROM habits d LEFT JOIN history_habits dh ON d.id =dh.habit_id AND d.user_id = dh.user_id and CAST(dh.created_date AT TIME ZONE 'UTC' %s AS DATE) = '%s' where d.closed_date IS NULL and d.user_id = %s and dh.id is NULL; ;""" % (_timezone_user, _date, g.user.id) _current_task = [] _data = g.db_conn.execute(_qrs) if g.db_conn.count() > 0: _current_task = tuple2list( ['id', 'name', 'status', 'success', 'fail'], _data) else: raise ExceptionRest(status_code=404) return _current_task