did some formatting and cleaning

This commit is contained in:
2023-09-20 01:25:33 +03:30
parent abf5ab25f1
commit 41fdbcd1f2
2 changed files with 107 additions and 26 deletions

View File

@@ -1 +1,5 @@
SQLALCHEMY_DATABASE_URI = 'mysql+mariadb://your_username:your_password@your_database_host/scenesense_db' import os
class Config:
# Use the environment variable for the database URI
SQLALCHEMY_DATABASE_URI = os.environ.get("SQLALCHEMY_DATABASE_URI")

View File

@@ -1,13 +1,13 @@
from flask import Flask, request, jsonify from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy from flask_sqlalchemy import SQLAlchemy
from api_keys import api_keys from api_keys import api_keys
from config import SQLALCHEMY_DATABASE_URI import config
import datetime import datetime
app = Flask(__name__) app = Flask(__name__)
# Configuration for SQLAlchemy and your database connection # Configuration for SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI app.config.from_object(config.Config)
db = SQLAlchemy(app) db = SQLAlchemy(app)
# Database Model for Records # Database Model for Records
@@ -16,89 +16,166 @@ class Record(db.Model):
timestamp = db.Column(db.String(255), nullable=False) timestamp = db.Column(db.String(255), nullable=False)
description = db.Column(db.String(255), nullable=False) description = db.Column(db.String(255), nullable=False)
# Parse a timestamp string into a datetime object
def parse_timestamp(timestamp_str): def parse_timestamp(timestamp_str):
try: try:
return datetime.strptime(timestamp_str, '%Y-%m-%d %H:%M:%S') return datetime.strptime(timestamp_str, '%Y-%m-%d %H:%M:%S')
except ValueError: except ValueError:
return None return None
# Custom middleware for API key authentication # API key authentication
@app.before_request @app.before_request
def authenticate(): def authenticate():
# Check if the API key provided in the request headers is valid
api_key = request.headers.get("Authorization") api_key = request.headers.get("Authorization")
if api_key not in api_keys: if api_key not in api_keys:
# Return a 401 Unauthorized response for invalid API keys
return jsonify({'error': 'Invalid API key'}), 401 return jsonify({'error': 'Invalid API key'}), 401
# Route to add a new record
@app.route('/add_record', methods=['POST']) @app.route(
'/add_record',
methods=['POST']
)
def add_record(): def add_record():
try: try:
data = request.get_json() data = request.get_json()
timestamp = data['timestamp'] timestamp = data['timestamp']
description = data['description'] description = data['description']
# Create a new record and add it to the database # Create a new record with provided data and add it to the db
new_record = Record(timestamp=timestamp, description=description) new_record = Record(
timestamp=timestamp, description=description
)
db.session.add(new_record) db.session.add(new_record)
db.session.commit() db.session.commit()
return jsonify({'message': 'Record added successfully'}), 201 return jsonify({'message': 'Record added successfully'}), 201
except Exception as e: except Exception as e:
# Return a 500 Internal Server Error response if an exception occurs
return jsonify({'error': 'An error occurred: {}'.format(e)}), 500 return jsonify({'error': 'An error occurred: {}'.format(e)}), 500
@app.route('/get_last_record', methods=['GET']) # Route to get the last recorded entry
@app.route(
'/get_last_record',
methods=['GET']
)
def get_last_record(): def get_last_record():
# Retrieve the last record from the database based on its ID
last_record = Record.query.order_by(Record.id.desc()).first() last_record = Record.query.order_by(Record.id.desc()).first()
if last_record: if last_record:
return jsonify({'id': last_record.id, 'timestamp': last_record.timestamp, 'description': last_record.description}) # Return the data of the last record as JSON
return jsonify({
'id': last_record.id,
'timestamp': last_record.timestamp,
'description': last_record.description
})
else: else:
# Return a 404 Not Found response if no records are found
return jsonify({'message': 'No records found'}), 404 return jsonify({'message': 'No records found'}), 404
# Route to get all records
@app.route('/get_all_records', methods=['GET']) @app.route(
'/get_all_records',
methods=['GET']
)
def get_all_records(): def get_all_records():
# Retrieve all records from the database
# and format them into a list of dictionaries
records = Record.query.order_by(Record.id.desc()).all() records = Record.query.order_by(Record.id.desc()).all()
records_list = [{'id': record.id, 'timestamp': record.timestamp, 'description': record.description} for record in records] records_list = []
for record in records:
record_data = {
'id': record.id,
'timestamp': record.timestamp,
'description': record.description
}
records_list.append(record_data)
# Return the list of records as JSON
return jsonify(records_list) return jsonify(records_list)
# Route to get records since a given timestamp
@app.route(
# Route to get records from a given timestamp till now '/get_records_since/<timestamp_str>',
@app.route('/get_records_since/<timestamp_str>', methods=['GET']) methods=['GET']
)
def get_records_since(timestamp_str): def get_records_since(timestamp_str):
timestamp = parse_timestamp(timestamp_str) timestamp = parse_timestamp(timestamp_str)
if timestamp is None: if timestamp is None:
return jsonify({'error': 'Invalid timestamp format'}), 400 return jsonify({'error': 'Invalid timestamp format'}), 400
records = Record.query.filter(Record.timestamp >= timestamp).order_by(Record.id.desc()).all() # Retrieve records from the database where
records_list = [{'id': record.id, 'timestamp': record.timestamp, 'description': record.description} for record in records] # the timestamp is greater than or equal to the provided timestamp
records = Record.query.filter(
Record.timestamp >= timestamp
).order_by(Record.id.desc()).all()
records_list = []
for record in records:
record_data = {
'id': record.id,
'timestamp': record.timestamp,
'description': record.description
}
records_list.append(record_data)
# Return the list of matching records as JSON
return jsonify(records_list) return jsonify(records_list)
# Route to get records between two timestamps # Route to get records between two timestamps
@app.route('/get_records_between/<start_timestamp_str>/<end_timestamp_str>', methods=['GET']) @app.route(
'/get_records_between/'
'<start_timestamp_str>/<end_timestamp_str>',
methods=['GET']
)
def get_records_between(start_timestamp_str, end_timestamp_str): def get_records_between(start_timestamp_str, end_timestamp_str):
# Parse the provided start and end timestamps into datetime objects
start_timestamp = parse_timestamp(start_timestamp_str) start_timestamp = parse_timestamp(start_timestamp_str)
end_timestamp = parse_timestamp(end_timestamp_str) end_timestamp = parse_timestamp(end_timestamp_str)
if start_timestamp is None or end_timestamp is None: if start_timestamp is None or end_timestamp is None:
return jsonify({'error': 'Invalid timestamp format'}), 400 return jsonify({'error': 'Invalid timestamp format'}), 400
records = Record.query.filter(Record.timestamp.between(start_timestamp, end_timestamp)).order_by(Record.id.desc()).all() # Retrieve records from the database
records_list = [{'id': record.id, 'timestamp': record.timestamp, 'description': record.description} for record in records] # that fall within the provided timestamp range
records = Record.query.filter(
Record.timestamp.between(start_timestamp, end_timestamp)
).order_by(Record.id.desc()).all()
records_list = []
for record in records:
record_data = {
'id': record.id,
'timestamp': record.timestamp,
'description': record.description
}
records_list.append(record_data)
return jsonify(records_list) return jsonify(records_list)
# Route to get records from now up until a timestamp # Route to get records until a given timestamp
@app.route('/get_records_until/<timestamp_str>', methods=['GET']) @app.route('/get_records_until/<timestamp_str>', methods=['GET'])
def get_records_until(timestamp_str): def get_records_until(timestamp_str):
timestamp = parse_timestamp(timestamp_str) timestamp = parse_timestamp(timestamp_str)
if timestamp is None: if timestamp is None:
return jsonify({'error': 'Invalid timestamp format'}), 400 return jsonify({'error': 'Invalid timestamp format'}), 400
records = Record.query.filter(Record.timestamp <= timestamp).order_by(Record.id.desc()).all() records = Record.query.filter(
records_list = [{'id': record.id, 'timestamp': record.timestamp, 'description': record.description} for record in records] Record.timestamp <= timestamp
).order_by(Record.id.desc()).all()
records_list = []
for record in records:
record_data = {
'id': record.id,
'timestamp': record.timestamp,
'description': record.description
}
records_list.append(record_data)
return jsonify(records_list) return jsonify(records_list)
# Run the Flask app
if __name__ == '__main__': if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000) app.run(host='0.0.0.0', port=5000)