Implement multi db backend support;

This commit is contained in:
Benjamin Bouvier 2017-12-29 15:45:37 +01:00
parent e07a749e4a
commit 4a5ea453c3
3 changed files with 35 additions and 5 deletions

30
main.py
View File

@ -1,5 +1,6 @@
import json import json
import dateutil import dateutil
import configparser
from datetime import datetime, timezone from datetime import datetime, timezone
from flask import Flask, request, abort from flask import Flask, request, abort
@ -8,10 +9,15 @@ from feedgen.feed import FeedGenerator
from pony import orm from pony import orm
from pony.orm import Required, Optional, Set from pony.orm import Required, Optional, Set
config = configparser.ConfigParser()
config.read('settings.ini')
site_url = config['general']['site_url']
if site_url[:-1] != '/':
site_url += '/'
site_url += 'feeds/'
app = Flask(__name__) app = Flask(__name__)
SITE_URL = 'http://localhost:5000/feeds/'
db = orm.Database() db = orm.Database()
class Feed(db.Entity): class Feed(db.Entity):
@ -31,7 +37,21 @@ class Item(db.Entity):
content = Required(str) content = Required(str)
date = Required(datetime) date = Required(datetime)
db.bind(provider='sqlite', filename='db.sqlite', create_db=True) db_config = config['db']
db_adapter = db_config['adapter']
if db_adapter == 'sqlite':
filename = db_config['filename']
db.bind(provider='sqlite', filename=filename, create_db=True)
elif db_adapter == 'postgres':
user = db_config['user']
password = db_config['password']
host = db_config['host']
database = db_config['database']
db.bind(provider='postgres', user=user, password=password, host=host, database=database)
else:
raise Exception('unhandled db adapter: {}'.format(db_adapter))
db.generate_mapping(create_tables=True) db.generate_mapping(create_tables=True)
orm.set_sql_debug(True) orm.set_sql_debug(True)
@ -54,7 +74,7 @@ def add_feed():
if 'title' not in data or 'description' not in data or 'admin_token' not in data: if 'title' not in data or 'description' not in data or 'admin_token' not in data:
abort(400, "missing title or description or admin_token") abort(400, "missing title or description or admin_token")
url = SITE_URL + slug url = site_url + slug
with orm.db_session: with orm.db_session:
feed = Feed(slug=slug, feed = Feed(slug=slug,

View File

@ -1,3 +1,4 @@
Flask Flask
feedgen feedgen
pony pony
psycopg2cffi

9
settings.ini Normal file
View File

@ -0,0 +1,9 @@
[general]
site_url=http://localhost:5000
[db]
adapter=postgres
host=localhost
user=postgres
password=mysecretpassword
database=postgres