0% found this document useful (0 votes)
3 views

Code without logic.py

Code for project

Uploaded by

k2rqng5pyy
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Code without logic.py

Code for project

Uploaded by

k2rqng5pyy
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

from flask import Flask, request, jsonify

import mysql.connector
from datetime import datetime
import pytz

app = Flask(__name__)

# Database configuration
db_config = {
'host': 'localhost',
'user': 'your_username',
'password': 'your_password',
'database': 'attendance_db'
}

def get_db_connection():
return mysql.connector.connect(**db_config)

# Create necessary database tables


def setup_database():
conn = get_db_connection()
cursor = conn.cursor()

# Create employees table


cursor.execute('''
CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
card_id VARCHAR(50) UNIQUE,
department VARCHAR(50)
)
''')

# Create attendance table


cursor.execute('''
CREATE TABLE IF NOT EXISTS attendance (
id INT AUTO_INCREMENT PRIMARY KEY,
employee_id INT,
timestamp DATETIME,
FOREIGN KEY (employee_id) REFERENCES employees(id)
)
''')

conn.commit()
conn.close()

@app.route('/record_attendance', methods=['POST'])
def record_attendance():
data = request.get_json()
card_id = data.get('card_id')

if not card_id:
return jsonify({'error': 'No card ID provided'}), 400

try:
conn = get_db_connection()
cursor = conn.cursor()

# Get employee ID from card ID


cursor.execute('SELECT id, name FROM employees WHERE card_id = %s',
(card_id,))
employee = cursor.fetchone()

if not employee:
return jsonify({'error': 'Unknown card ID'}), 404

employee_id, employee_name = employee

# Record attendance
current_time = datetime.now(pytz.UTC)
cursor.execute(
'INSERT INTO attendance (employee_id, timestamp) VALUES (%s, %s)',
(employee_id, current_time)
)

conn.commit()

return jsonify({
'message': 'Attendance recorded successfully',
'employee_name': employee_name,
'timestamp': current_time.isoformat()
})

except Exception as e:
return jsonify({'error': str(e)}), 500
finally:
conn.close()

@app.route('/get_attendance_report', methods=['GET'])
def get_attendance_report():
start_date = request.args.get('start_date')
end_date = request.args.get('end_date')

try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)

query = '''
SELECT
e.name,
e.department,
a.timestamp
FROM attendance a
JOIN employees e ON a.employee_id = e.id
WHERE a.timestamp BETWEEN %s AND %s
ORDER BY a.timestamp DESC
'''

cursor.execute(query, (start_date, end_date))


records = cursor.fetchall()

return jsonify(records)

except Exception as e:
return jsonify({'error': str(e)}), 500
finally:
conn.close()
if __name__ == '__main__':
setup_database()
app.run(host='0.0.0.0', port=5000)

You might also like