initial server_api.py completed

This commit is contained in:
2023-09-19 23:36:02 +03:30
parent 8641e0d0e5
commit abf5ab25f1
4 changed files with 112 additions and 0 deletions

7
server/api_keys.py Normal file
View File

@@ -0,0 +1,7 @@
# api_keys.py
api_keys = {
"your_api_key": "user1",
"another_api_key": "user2",
# Add more API keys as needed
}

1
server/config.py Normal file
View File

@@ -0,0 +1 @@
SQLALCHEMY_DATABASE_URI = 'mysql+mariadb://your_username:your_password@your_database_host/scenesense_db'

View File

104
server/server_api.py Normal file
View File

@@ -0,0 +1,104 @@
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from api_keys import api_keys
from config import SQLALCHEMY_DATABASE_URI
import datetime
app = Flask(__name__)
# Configuration for SQLAlchemy and your database connection
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
db = SQLAlchemy(app)
# Database Model for Records
class Record(db.Model):
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.String(255), nullable=False)
description = db.Column(db.String(255), nullable=False)
def parse_timestamp(timestamp_str):
try:
return datetime.strptime(timestamp_str, '%Y-%m-%d %H:%M:%S')
except ValueError:
return None
# Custom middleware for API key authentication
@app.before_request
def authenticate():
api_key = request.headers.get("Authorization")
if api_key not in api_keys:
return jsonify({'error': 'Invalid API key'}), 401
@app.route('/add_record', methods=['POST'])
def add_record():
try:
data = request.get_json()
timestamp = data['timestamp']
description = data['description']
# Create a new record and add it to the database
new_record = Record(timestamp=timestamp, description=description)
db.session.add(new_record)
db.session.commit()
return jsonify({'message': 'Record added successfully'}), 201
except Exception as e:
return jsonify({'error': 'An error occurred: {}'.format(e)}), 500
@app.route('/get_last_record', methods=['GET'])
def get_last_record():
last_record = Record.query.order_by(Record.id.desc()).first()
if last_record:
return jsonify({'id': last_record.id, 'timestamp': last_record.timestamp, 'description': last_record.description})
else:
return jsonify({'message': 'No records found'}), 404
@app.route('/get_all_records', methods=['GET'])
def get_all_records():
records = Record.query.order_by(Record.id.desc()).all()
records_list = [{'id': record.id, 'timestamp': record.timestamp, 'description': record.description} for record in records]
return jsonify(records_list)
# Route to get records from a given timestamp till now
@app.route('/get_records_since/<timestamp_str>', methods=['GET'])
def get_records_since(timestamp_str):
timestamp = parse_timestamp(timestamp_str)
if timestamp is None:
return jsonify({'error': 'Invalid timestamp format'}), 400
records = Record.query.filter(Record.timestamp >= timestamp).order_by(Record.id.desc()).all()
records_list = [{'id': record.id, 'timestamp': record.timestamp, 'description': record.description} for record in records]
return jsonify(records_list)
# Route to get records between two timestamps
@app.route('/get_records_between/<start_timestamp_str>/<end_timestamp_str>', methods=['GET'])
def get_records_between(start_timestamp_str, end_timestamp_str):
start_timestamp = parse_timestamp(start_timestamp_str)
end_timestamp = parse_timestamp(end_timestamp_str)
if start_timestamp is None or end_timestamp is None:
return jsonify({'error': 'Invalid timestamp format'}), 400
records = Record.query.filter(Record.timestamp.between(start_timestamp, end_timestamp)).order_by(Record.id.desc()).all()
records_list = [{'id': record.id, 'timestamp': record.timestamp, 'description': record.description} for record in records]
return jsonify(records_list)
# Route to get records from now up until a timestamp
@app.route('/get_records_until/<timestamp_str>', methods=['GET'])
def get_records_until(timestamp_str):
timestamp = parse_timestamp(timestamp_str)
if timestamp is None:
return jsonify({'error': 'Invalid timestamp format'}), 400
records = Record.query.filter(Record.timestamp <= timestamp).order_by(Record.id.desc()).all()
records_list = [{'id': record.id, 'timestamp': record.timestamp, 'description': record.description} for record in records]
return jsonify(records_list)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)