Commit c0a86139 authored by Zach Perkins's avatar Zach Perkins
Browse files

Fixed a thing and reworked point creation

parent 61d2aaed
...@@ -5,6 +5,14 @@ from where.model.field_types import FieldType ...@@ -5,6 +5,14 @@ from where.model.field_types import FieldType
app = Flask(__name__) app = Flask(__name__)
def create_resource(session, model_cls, data, get_function):
model = model_cls(**data)
response = make_response(jsonify(model.as_json()), 201)
response.headers['Location'] = url_for(get_function,
return response
@app.route('/') @app.route('/')
def index(): def index():
...@@ -122,23 +130,11 @@ def get_point(session, id): ...@@ -122,23 +130,11 @@ def get_point(session, id):
@app.route('/add-point', methods=['POST']) @app.route('/add-point', methods=['POST'])
@with_session @with_session
def add_point(session): def add_point(session):
allowed_params = {'name', 'lat', 'lon', 'attributes', 'category_id', 'parent_id'}
data = request.get_json() data = request.get_json()
data = {key: val for key, val in data.items() if key in allowed_params} data['category'] = session.query(Category).get(data['category'])
data['parent_id'] = data.pop('parent', None)
# TODO: For some reason point.category is NULL when we do validation, even though the category ID is present
# this is causing an exception whenever a non-null attributes object is passed
point = Point(category_id=data.pop('category_id'))
for key, val in data.items():
setattr(point, key, val)
response = make_response(jsonify(point.as_json()), 201)
response.headers['Location'] = url_for('get_point',
return response
return create_resource(session, Point, data, 'get_point')
@app.route('/point', methods=['GET']) @app.route('/point', methods=['GET'])
@with_session @with_session
...@@ -61,12 +61,20 @@ class Point(Base): ...@@ -61,12 +61,20 @@ class Point(Base):
parent = relationship('Point', remote_side=[id]) parent = relationship('Point', remote_side=[id])
children = relationship('Point') children = relationship('Point')
def __init__(self, **kwargs):
# Need to load category first or else attribute validation will fail
if 'category' in kwargs:
self.category = kwargs.pop('category')
super(Point, self).__init__(**kwargs)
@validates('attributes') @validates('attributes')
def validate_data(self, _, data): def validate_data(self, _, data):
if data is None: if data is None:
return return
fields = self.category.fields fields = self.category.fields
for key in data: for key in data:
# Find Field object that corresponds to this key # Find Field object that corresponds to this key
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment