Commit c47806e8 authored by Pietro Albini's avatar Pietro Albini

Add an SQLite database

parent 45a28f05
......@@ -18,6 +18,7 @@ import os
import flask
from . import db
from . import pages
from . import cache
from . import utils
......@@ -42,6 +43,10 @@ def create_app(data_path):
with open(os.path.join(data_path, "secret_key")) as f:
app.secret_key = f.read().strip()
# Initialize the database
app.db = db.Database(os.path.join(data_path, "database.db"))
app.db.init()
app.config["CACHE_PATH"] = os.path.join(data_path, "cache")
cache.install_cache(app)
......
# Source code of the Ubuntu-it website
# Copyright (C) 2015 Pietro Albini <pietroalbini@ubuntu.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; witout even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import threading
import sqlite3
import pkg_resources
_LOCAL = threading.local()
class Database:
def __init__(self, path):
self._path = path
def init(self):
"""Initialize the database"""
db_version = int(self.query("PRAGMA user_version;")[0][0])
cursor = self.cursor()
if db_version == 0:
cursor.executescript("""
CREATE TABLE migrations (name TEXT PRIMARY KEY);
PRAGMA user_version = 1;
""")
applied = [m[0] for m in self.query("SELECT * FROM migrations;")]
for name, sql in MIGRATIONS:
if name in applied:
continue
cursor.executescript(sql)
cursor.execute("INSERT INTO migrations (name) VALUES (?)", [name])
cursor.connection.commit()
def cursor(self):
"""Get a new cursor"""
if not hasattr(_LOCAL, "db"):
_LOCAL.db = sqlite3.connect(self._path)
return _LOCAL.db.cursor()
def query(self, query, *params, update=False):
"""Make a new query against the db"""
cursor = self.cursor()
cursor.execute(query, params)
try:
if update:
cursor.connection.commit()
else:
return cursor.fetchall()
finally:
cursor.close()
def update(self, query, *params):
"""Make a new update query against the db"""
self.query(query, *params, update=True)
MIGRATIONS = []
......@@ -95,7 +95,7 @@
Sito web realizzato dal Gruppo Web di Ubuntu-it, con
<a href="https://www.python.org/">Python</a>,
<a href="https://www.palletsproject.com/p/flask/">Flask</a> e
<a href="http://www.postgresql.org/">PostgreSQL</a>.
<a href="https://www.sqlite.org/">SQLite</a>.
</p>
<ul>
<li><a href="{{ url_for("pages.cookies") }}">
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment