47 lines
1.3 KiB
Python
47 lines
1.3 KiB
Python
from flask_sqlalchemy import SQLAlchemy
|
|
from flask import g
|
|
import os
|
|
import sqlite3
|
|
|
|
def get_db():
|
|
db = getattr(g, '_database', None)
|
|
if db is None:
|
|
db = g._database = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'db.sqlite3'))
|
|
return db
|
|
|
|
def create_leaderboard_table():
|
|
db = get_db()
|
|
cursor = db.cursor()
|
|
cursor.execute('''
|
|
CREATE TABLE IF NOT EXISTS leaderboard (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
username TEXT,
|
|
problem_id INTEGER,
|
|
runtime REAL,
|
|
memory_used INTEGER,
|
|
line_number INTEGER,
|
|
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
)
|
|
''')
|
|
db.commit()
|
|
|
|
def log_leaderboard(username, problem_id, runtime, memory_used, line_number):
|
|
db = get_db()
|
|
cursor = db.cursor()
|
|
cursor.execute('''
|
|
INSERT INTO leaderboard (username, problem_id, runtime, memory_used, line_number)
|
|
VALUES (?, ?, ?, ?, ?)
|
|
''', (username, problem_id, runtime, memory_used, line_number))
|
|
db.commit()
|
|
|
|
def get_leaderboard():
|
|
db = get_db()
|
|
cursor = db.cursor()
|
|
cursor.execute('''
|
|
SELECT username, problem_id, runtime, memory_used, line_number, timestamp
|
|
FROM leaderboard
|
|
ORDER BY runtime ASC, memory_used ASC
|
|
LIMIT 20
|
|
''')
|
|
return cursor.fetchall()
|