def patch(self, conntype, id): if conntype not in CONNECTION_TYPE_MAPPING: return ('TYPE', 400, []) conn_dict = CONNECTION_TYPE_MAPPING[conntype] conn_class = conn_dict['class'] conn = self._get_instance(conntype, id) if not isinstance(conn, conn_class): # error return conn logged_user = get_logged_user() if conntype == 'friendships': type_status = request.json.get('type_status') if type_status: # pending status can be changed only by the other counterpart # (to be improved yet) if (conn.type_status['current'] == 'pending' and conn.user_from_id == logged_user.id): return ('UNAUTHORIZED', 405, []) try: make_transition(conn, 'type_status', type_status) except StateValueError: return (jsonify(build_error_dict([ 'Invalid "type_status" value.'])), 400, []) except StateTransitionError: return (jsonify(build_error_dict([ 'Invalid "type_status" transition.'])), 400, []) return jsonify(conn.serializer_func(logged_user))
def patch(self, direction, msgtype, id): user = get_logged_user() request_json = json_loads(request.data) if msgtype not in MESSAGE_TYPE_MAPPING: return ('TYPE', 400, []) msg_dict = MESSAGE_TYPE_MAPPING[msgtype] msg_notification_class = msg_dict['notification_class'] if direction == 'out': # PATCH op is allowed only for incoming msgs return ('FORBIDDEN', 403, []) elif direction != 'in': # Invalid direction value return ('DIRECTION', 400, []) msg_list = filter_by_direction( msgtype, 'in', user, additional_filters={'id': id}) if not msg_list: return ('NOT FOUND', 404, []) msg = msg_list[0] added_flags, removed_flags = ( request_json.get('flags_in'), request_json.get('flags_out')) msg.change_flags(added_flags, removed_flags) msg_notification = msg.get_notification(user) errors = [] try: msg_notification.change_status(request_json.get('message_status')) except ValueError: # Invalid transition errors.append('Invalid "message_status" value.') if msgtype == 'hospitality_request': request_status = request_json.get('request_status') if (request_status and ((direction == 'out' and request_status == 'canceled') or direction == 'in' and msg.status != 'canceled')): try: msg.change_status(request_status) except ValueError: # Invalid transition errors.append('Invalid "request_status" value.') if errors: # Errors found, returns error structure return (jsonify(build_error_dict(errors)), 400, []) # in case of success, returns the updated message serialization msg.save() msg_notification.save(commit=True) return jsonify(msg.serialized_func(user))
def post(self): """ Creates a new account. """ # TODO: improved password handling? params = dict( first_name=request.json.get('first_name'), last_name=request.json.get('last_name'), birth_date=request.json.get('birth_date'), email=request.json.get('email'), gender=request.json.get('gender'), username=request.json.get('username'), password=request.json.get('password')) optional_params = dict( city_id=request.json.get('city_id')) missing_fields = [k for (k, v) in params.iteritems() if not v] if missing_fields: return (jsonify(build_error_dict([ 'No value specified for "%s".' % field for field in missing_fields])), 400, []) params.update(optional_params) user = User(**params) user.save(commit=True) return UserByIDHandler._get(user)
def post(self, conntype): logged_user = get_logged_user() if conntype not in CONNECTION_TYPE_MAPPING: return ('TYPE', '400', []) conn_dict = CONNECTION_TYPE_MAPPING[conntype] conn_class, conn_validator = ( conn_dict['class'], getattr(self, conn_dict['validator'])) success, param_dict = getattr( self, conn_dict['validator'])(logged_user) if not success: return (jsonify(**param_dict), 400, []) conn = conn_class(**param_dict) conn.save(commit=True) return jsonify(conn.serializer_func(logged_user))
def get(self): # TODO - search to be defined filter_args = get_filter_dict( request.args, ('city_id', 'parent_group_id')) query = Group.query.filter_by(is_active=True) if filter_args: query = query.filter_by(**filter_args) resp = [o.serialized for o in query] return jsonify(resp)
def _get(cls, user): expand_rels = request.args.get('expand') if expand_rels: expand_rels = filter(lambda o: o.lower().strip(), expand_rels.split(',')) user.force_serialize(expand_rels) resp = user.serialized resp['token'] = get_request_token() return jsonify(resp)
def _get(cls, conntype, conn): logged_user = get_logged_user() if not conn: return ('NOT FOUND', 404, []) this_conn = cls._get_instance(conntype, conn) if isinstance(this_conn, tuple): return this_conn return jsonify(this_conn.serializer_func(logged_user))
def post(self): """ Create new group. { "title": str, "description": str, ^"city_id": int, ^"minorlocality_id": int, ^"parent_group_id": int} """ user = get_logged_user() params = dict( title=request.json.get('title'), creator_id=user.id) optional_params = dict( description=request.json.get('description'), city_id=request.json.get('city_id'), minorlocality_id=request.json.get('minorlocality_id'), parent_group_id=request.json.get('parent_group_id')) if not all([v not in (None, '') for v in params.itervalues()]): return (jsonify(error=True), 400, []) if (optional_params['city_id'] is None and optional_params['minorlocality_id'] is not None): return (jsonify(error=True), 400, []) if (optional_params['parent_group_id'] is not None): parent_group = Group.query.filter_by( id=optional_params['parent_group_id']).first() if not parent_group: return (jsonify(error=True), 400, []) elif parent_group.city_id != optional_params['city_id']: return (jsonify(error=True), 400, []) params.update(optional_params) group = Group(**params) group.save(commit=True) return GroupByIDHandler._get(group)
def post(self): logged_user = get_logged_user() success, params = self.validate(logged_user) if not success: return (jsonify(params), 400, []) activity = Activity(**params) activity.save(commit=True) activity.set_user_rsvp(logged_user, "yes") return ActivityByIDHandler._get(activity)
def get(self, direction, msgtype): user = get_logged_user() if msgtype not in MESSAGE_TYPE_MAPPING: return ('TYPE', 400, []) try: msg_list = filter_by_direction(msgtype, direction, user) except ValueError: return ('DIRECTION', 400, []) resp = [msg.serialized_func(user) for msg in msg_list] return jsonify(resp)
def post(self, direction, msgtype): user = get_logged_user() if direction != 'out': return ('NOT ALLOWED', 403, []) logged_user = get_logged_user() if msgtype not in MESSAGE_TYPE_MAPPING: return ('TYPE', 400, []) msg_dict = MESSAGE_TYPE_MAPPING[msgtype] msg_class, msg_validator = ( msg_dict['class'], getattr(self, msg_dict['validator'])) success, param_dict = getattr( self, msg_dict['validator'])(logged_user) if not success: return (jsonify(param_dict), 400, []) msg = msg_class(**param_dict) msg.send_to(*msg.recipient_list) return jsonify(msg.serialized_func(user))
def get(self, conntype): user = get_logged_user() if conntype not in CONNECTION_TYPE_MAPPING: return ('TYPE', '400', []) conn_dict = CONNECTION_TYPE_MAPPING[conntype] conn_class = conn_dict['class'] conn_list = conn_class.query.filter(or_( conn_class.user_from_id == user.id, conn_class.user_to_id == user.id)).all() resp = [conn.serializer_func(user) for conn in conn_list] return jsonify(resp)
def get(self, direction, msgtype, id): user = get_logged_user() if msgtype not in MESSAGE_TYPE_MAPPING: return ('TYPE', 400, []) try: msg_list = filter_by_direction( msgtype, direction, user, additional_filters={'id': id}) except ValueError: return ('DIRECTION', 400, []) if not msg_list: return ('NOT FOUND', 404, []) msg = msg_list[0] return jsonify(msg.serialized_func(user))
def _patch(cls, user): params = dict( first_name=request.json.get('first_name'), last_name=request.json.get('last_name'), birth_date=request.json.get('birth_date'), email=request.json.get('email'), gender=request.json.get('gender'), city_id=request.json.get('city_id')) # password handling password = request.json.get('password') if password: user.set_and_encrypt_password(password) # "normal" param handling for (key, val) in params.iteritems(): if val is None: continue curval = getattr(user, key, None) if curval != val: setattr(user, key, val) # profile details are stored in a different table profile_details = request.json.get('details') if profile_details: detail_object = user.details for (key, val) in profile_details.iteritems(): if key not in ('websites', 'profile_details', 'sections'): continue if val and not detail_object: # detail entry not present, must be created detail_object = UserProfileDetails(user_id=user.id) setattr(detail_object, key, val) else: if not detail_object: continue # no need to create a new entry for now # update existing entry if needed curval = getattr(detail_object, key, None) if curval != val: setattr(detail_object, key, val) if detail_object: # save details here (commit comes later) detail_object.save() user.save(commit=True) return jsonify(user.serialized)
def get(self): """ Currently not implemented. """ ALLOWED_FILTERS = frozenset([ 'city_id', 'gender', 'age', 'n_refs', 'n_friends', 'has_details', 'can_host', 'keywords']) search_dict = parse_search_fields() if search_dict.get('fields'): # only some filters are allowed search_dict['fields'] = dict( (k, v) for k, v in search_dict['fields'].iteritems() if k in ALLOWED_FILTERS) resp = query(User, **search_dict) return jsonify([obj.serialized for _, obj in resp] if resp else [])
def get(self, loctype): logged_user = get_logged_user() if loctype not in LOCATION_TYPE_MAPPING: return ('TYPE', '400', []) location_class = LOCATION_TYPE_MAPPING[loctype] #loc_query = location_class.query #if logged_user: # make_point = lambda c: func.ST_SetSRID( # func.ST_Point(c.x, c.y), 4326) # loc_query = loc_query.filter( # func.ST_Distance_Sphere( # make_point(location_class.coordinates), # make_point(logged_user.city.coordinates)) < 100000) fields = parse_search_fields() fields['query_field'] = 'name' resp = search.query(location_class, **fields) return jsonify([obj.serialized for _, obj in resp])
def post(self, loctype): if loctype not in LOCATION_TYPE_MAPPING: return ('TYPE', '400', []) location_class = LOCATION_TYPE_MAPPING[loctype] params = dict( name=request.json.get('name'), country_id=request.json.get('country_id'), latitude=request.json.get('latitude'), longitude=request.json.get('longitude')) optional_params = dict( rating=request.json.get('rating'), timezone=request.json.get('timezone'), slug=request.json.get('slug'), wikiname=request.json.get('wikiname')) missing_vals = [(k, v) for (k, v) in params.iteritems() if v in (None, '')] if missing_vals: error_dict = build_error_dict([ '"%s" not specified' % k for (k, _) in missing_vals]) return (jsonify(error_dict), 400, []) params.update(optional_params) params['coordinates'] = WKTSpatialElement( 'POINT(%s %s)' % ( params.get('latitude'), params.get('longitude'))) del params['latitude'] del params['longitude'] location = location_class(**params) location.save(commit=True) return LocationByIDHandler._get(loctype, location)
def _get(cls, group): resp = group.serialized return jsonify(resp)
def delete(self): logout() return jsonify(success=True)
def _get(cls, loctype, location): resp = location.serialized resp['type'] = loctype return jsonify(resp)
def get(self): # TODO - TO BE IMPROVED return jsonify([o.serialized for o in Activity.query.all()])
def _get(cls, activity): return jsonify(activity.serialized)