finfree-be/routes/conditions.py

77 lines
2.6 KiB
Python

from flask import jsonify, request, redirect, render_template
from db import get_connection, getRethinkDB
table_name = 'conditions'
route = table_name
r = getRethinkDB()
booleans = ["disbled"]
def create_conditions_routes(app):
# Create a table (if not exists)
if table_name not in r.table_list().run(get_connection()):
r.table_create(table_name).run(get_connection())
# Routes for CRUD operations
# Create operation
@app.route('/' + route + '/create', methods=['GET'])
def create_form():
return render_template(route + '/create.html')
@app.route('/' + route, methods=['POST'])
def create_condition():
if request.headers['Content-Type'] == 'application/json':
data = request.json
else: # Assuming form data is in 'application/x-www-form-urlencoded' format
data = request.form.to_dict()
# convert checkboxes to true/false
for key in booleans:
data[key] = key in request.form
result = r.table(table_name).insert(data).run(get_connection())
return render_template(route + '/create.html')
# Read operation
@app.route('/' + route, methods=['GET'])
def get_conditions():
cursor = r.table(table_name).run(get_connection())
conditions = list(cursor)
return jsonify(conditions)
@app.route('/' + route + '/<id>', methods=['GET'])
def get_condition(id):
cursor = r.table(table_name).get(id).run(get_connection())
json = jsonify(cursor)
if request.headers.get('Content-Type') == 'application/json':
return json
else:
return render_template(route + '/update.html', data=cursor)
# Update operation
@app.route('/' + route + '/<id>', methods=['POST'])
def update_condition(id):
if request.headers['Content-Type'] == 'application/json':
data = request.json
else:
data = request.form.to_dict()
# convert checkboxes to true/false
for key in booleans:
data[key] = key in request.form
r.table(table_name).get(id).update(data).run(get_connection())
return "<script>window.close();</script>"
# Delete operation
@app.route('/' + route + '/delete/<id>', methods=['POST'])
def delete_post(id):
r.table(table_name).get(id).delete().run(get_connection())
return jsonify({'message': 'condition deleted successfully'})
@app.route('/' + route + '/<id>', methods=['DELETE'])
def delete_condition(id):
r.table(table_name).get(id).delete().run(get_connection())
return jsonify({'message': 'condition deleted successfully'})