backend: add CRUD for car
This commit is contained in:
@@ -8,10 +8,12 @@ server.py is the main source file for the Dungeon's backend service.
|
||||
from flask import Flask, request, jsonify
|
||||
from dotenv import load_dotenv
|
||||
from db_client import DBClient
|
||||
from car import registerCarEndpoints
|
||||
|
||||
load_dotenv()
|
||||
app = Flask(__name__)
|
||||
database = DBClient()
|
||||
registerCarEndpoints(app=app, database=database)
|
||||
|
||||
@app.route('/login', methods=['POST'])
|
||||
def login():
|
||||
@@ -20,58 +22,7 @@ def login():
|
||||
else:
|
||||
return jsonify({'error': 'Request must contain JSON data'}), 400
|
||||
|
||||
@app.route('/car', methods=['GET'])
|
||||
def get_car():
|
||||
if not request.is_json:
|
||||
return jsonify({'error': 'Request must contain JSON data'}), 400
|
||||
|
||||
data = request.get_json()
|
||||
|
||||
if 'name' not in data or not data['name']:
|
||||
return jsonify({'error': 'Request must contain name field'}), 400
|
||||
|
||||
query = f'SELECT * from car WHERE name = %s'
|
||||
output = database.query(query_str=query, params=(data['name'],))
|
||||
if not output:
|
||||
return jsonify({"message": "No car by that name exist"}), 404
|
||||
car = output[0]
|
||||
if len(car) != 3:
|
||||
return jsonify({'error': 'Car data is corrupted'}), 500
|
||||
|
||||
response = {
|
||||
"name": car[0],
|
||||
"car": car[1],
|
||||
"freeCarSpaces": car[2]
|
||||
}
|
||||
return jsonify(response), 200
|
||||
|
||||
@app.route('/car', methods=['POST'])
|
||||
def add_car():
|
||||
if not request.is_json:
|
||||
return jsonify({'error': 'Request must contain JSON data'}), 400
|
||||
|
||||
data = request.get_json()
|
||||
if not data['name'] or not data['car']:
|
||||
return jsonify({'error': 'JSON must contain car and name fields'}), 400
|
||||
|
||||
query = f'SELECT * from car WHERE name = %s'
|
||||
output = database.query(query_str=query, params=(data['name'],))
|
||||
if output:
|
||||
return jsonify({'error': 'A car with specified name already exists'}), 409
|
||||
|
||||
query = f'INSERT into car (Name, Car) VALUES (%s, %s)'
|
||||
output = database.query(query_str=query, params=(data['name'],data['car']))
|
||||
|
||||
database.commit()
|
||||
return jsonify({"message": "car added", "car": {"car": data['car'], "name": data['name']}}), 200
|
||||
|
||||
@app.route('/car', methods=['UPDATE'])
|
||||
def update_car():
|
||||
return jsonify({"hello": "user"}), 200
|
||||
|
||||
@app.route('/car', methods=['DELETE'])
|
||||
def delete_car():
|
||||
return jsonify({"hello": "user"}), 200
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True)
|
||||
Reference in New Issue
Block a user