web: Add data model using SQLAlchemy
parent
a3c69c2771
commit
dbd6d12499
|
@ -3,3 +3,4 @@
|
|||
__pycache__/
|
||||
*.py[co]
|
||||
*.ini
|
||||
*.sqlite
|
||||
|
|
1
setup.py
1
setup.py
|
@ -12,5 +12,6 @@ setup(
|
|||
package_dir={'': 'src'},
|
||||
install_requires=[
|
||||
'Milla>=0.3',
|
||||
'SQLAlchemy',
|
||||
],
|
||||
)
|
||||
|
|
|
@ -0,0 +1,37 @@
|
|||
from . import model
|
||||
import argparse
|
||||
import milla.util
|
||||
import sqlalchemy
|
||||
|
||||
|
||||
def createdb(args):
|
||||
config = milla.util.read_config(args.config)
|
||||
engine = sqlalchemy.engine_from_config(config, 'sqlalchemy.')
|
||||
engine.echo = not args.quiet
|
||||
session = model.Session(bind=engine)
|
||||
model.Base.metadata.create_all(session.bind)
|
||||
session.commit()
|
||||
session.close()
|
||||
session.bind.dispose()
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(prog=__package__)
|
||||
sp = parser.add_subparsers(metavar='command')
|
||||
sp.required = True
|
||||
p_createdb = sp.add_parser('createdb',
|
||||
help='Create initial database schema')
|
||||
p_createdb.add_argument('--quiet', '-q', action='store_true',
|
||||
default=False,
|
||||
help='Do not print issued SQL')
|
||||
p_createdb.add_argument('config', help='Path to configuration file')
|
||||
p_createdb.set_defaults(func=createdb)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = parse_args()
|
||||
args.func(args)
|
||||
|
||||
|
||||
main()
|
|
@ -0,0 +1,35 @@
|
|||
from __future__ import unicode_literals
|
||||
from sqlalchemy import schema, types, orm
|
||||
from sqlalchemy.ext import declarative
|
||||
|
||||
|
||||
Base = declarative.declarative_base()
|
||||
|
||||
Session = orm.session.sessionmaker()
|
||||
|
||||
|
||||
# pylint: disable=too-few-public-methods
|
||||
|
||||
class Serializable(object):
|
||||
|
||||
def to_json(self):
|
||||
data = {}
|
||||
for attr in self.__table__.columns.keys():
|
||||
if attr.startswith('_'):
|
||||
continue
|
||||
value = getattr(self, attr)
|
||||
if attr.endswith('_'):
|
||||
data[attr[:-1]] = value
|
||||
else:
|
||||
data[attr] = value
|
||||
return data
|
||||
|
||||
|
||||
class Host(Base, Serializable):
|
||||
|
||||
__tablename__ = 'hosts'
|
||||
|
||||
id = schema.Column(types.Integer, autoincrement=True, primary_key=True)
|
||||
macaddr = schema.Column(types.String(18), nullable=False)
|
||||
ipaddr = schema.Column(types.String(46))
|
||||
hostname = schema.Column(types.Unicode(253))
|
Loading…
Reference in New Issue