Exemplo n.º 1
0
def do_admin_login():

    if request.method == "POST":
        POST_USERNAME = str(request.form['username'])
        POST_PASSWORD = str(request.form['password'])

        db = Db()
        engine = db.create_session()
        # Base = declarative_base()
        Session = sessionmaker(bind=engine)
        s = Session()

        query = s.query(User).filter(User.username.in_([POST_USERNAME]),
                                     User.password.in_([POST_PASSWORD]))
        result = query.first()

        if result:
            session['logged_in'] = True
            # session['nombre']=result.nombre
            return home()
        else:
            return render_template("errors_users.html")

    else:
        return redirect(url_for('controller_module.home'))
Exemplo n.º 2
0
def create_app():
    app_flask = Flask(__name__)
    secret = secrets.token_urlsafe(32)
    app_flask.secret_key = secret
    app_flask.config.from_object('src.custom_config.DevelopmentConfig')
    # path = src.config['PATH_CONFIG']
    os.environ['PATH_CONFIG']='./config/Dashboard_dev.yaml'
    yml = init_properties(os.environ['PATH_CONFIG'])

    PropertiesDb(yml['db'])
    PropertiesGenerales(yml['generales'])
    PropertiesDf(yml['df'])
    PropertiesSQL(yml['sql'])
    PropertiesQueries(yml['queries'])
    PropertiesQueriesHistorico(yml['queries_historicos'])
    PropertiesDemanda(yml['queries_distribucion_demanda'])
    PropertiesTendencia(yml['queries_tendencia_venta'])
    PropertiesEstancia(yml['queries_estancia'])
    PropertiesUsuario(yml['nuevo_usuario'])
    PropertiesCostos(yml['costos'])
	
    app_flask.register_blueprint(controller_module)
    app_flask.register_blueprint(errors)

    db = Db()
    db.create_session()
    
    log.info("Empieza la aplicacion")
    return app_flask
Exemplo n.º 3
0
    def test_insert(self):
        table = mock.Mock(spec=Table)
        table.name = 'users'

        db = Db([table])
        db.insert('users', id=2, name='Roger')
        table.insert.assert_called_once_with(id=2, name='Roger')
Exemplo n.º 4
0
    def test_exception_if_table_does_not_exist(self):
        table = mock.Mock(spec=Table)
        table.name = 'users'

        db = Db([table])
        with self.assertRaises(Exception):
            db.insert('despacito', id=2)
Exemplo n.º 5
0
	def setUp(self):
		migrate = Migration('amity_test')
		migrate.drop()
		migrate.install()
		self.db = Db('amity_test')
		self.data = {
		'firstname':'sunday',
		'lastname':'Nwuguru',
		'allocated':1,
		'living_space':1
		}
		self.db.table_name = 'person'
Exemplo n.º 6
0
    def test_export(self):
        table = mock.Mock(spec=Table)
        table.name = 'users'
        table.export.return_value = [
            {'id': 1, 'name': 'Roger'},
            {'id': 2, 'name': 'Patrick'}
        ]

        db = Db([table])
        self.assertEqual(db.export(), [
            {'users': [
                {'id': 1, 'name': 'Roger'},
                {'id': 2, 'name': 'Patrick'}
            ]}
        ])
Exemplo n.º 7
0
def default_database():
    """ Set up local database (localhost)

        Test if a local Cassandra instance is available for testing. If not
        use mock data to run tests.
    """
    global DB  # pylint: disable=global-statement

    DB = Db()

    if DB.check_connection():
        # Delete existing keyspaces
        sel_stmt = "SELECT keyspace_name FROM system_schema.keyspaces"
        rows = DB.exec_query(sel_stmt)

        keyspace_names = [
            row.get("keyspace_name") for row in rows
            if not row.get("keyspace_name").startswith("system")
        ]

        for keyspace in keyspace_names:
            DB.exec_query("DROP KEYSPACE IF EXISTS \"{}\"".format(keyspace))

        # Populate instance with sample schemas
        with open("./tests/setup/cql/create_excalibur.cql", "r") as f:
            cmd_stmt = f.read()

        cmds = cmd_stmt.split(";")
        for cmd in cmds:
            trimmed_cmd = cmd.strip()
            if trimmed_cmd:
                DB.exec_query(trimmed_cmd)

        return DB

    return MockDb()
Exemplo n.º 8
0
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, inspect, func
from sqlalchemy import select, distinct
from sqlalchemy import exc
from src.db import Db
from src.properties_estancia import PropertiesEstancia
from src.log import log
from src.customException import BadRequest
from datetime import datetime, timedelta

db = Db()
queries = PropertiesEstancia()


def query_estancia(fecha_menor, fecha_mayor):
    engine = db.create_session()
    consulta = engine.execute(
        sqlalchemy.text(queries.QUERY_ESTANCIA.format(fecha_menor,
                                                      fecha_mayor)))
    lista_diccionario = []
    for c in consulta:
        lista_diccionario.append(c)
    log.info("Consulta Dao Distribucion Demanda")
    return lista_diccionario
Exemplo n.º 9
0
 def db(cls) -> Db:
     return Db()
Exemplo n.º 10
0
    def test_instanciation(self):
        table = mock.Mock(spec=Table)

        db = Db([table])
Exemplo n.º 11
0
class TestDb(unittest.TestCase):
	"""Test cases for Db class"""

	def setUp(self):
		migrate = Migration('amity_test')
		migrate.drop()
		migrate.install()
		self.db = Db('amity_test')
		self.data = {
		'firstname':'sunday',
		'lastname':'Nwuguru',
		'allocated':1,
		'living_space':1
		}
		self.db.table_name = 'person'


	def test_db_find_returns_false_when_invalid_table(self):
		self.db.table_name = ''
		data = self.db.find(0)
		self.assertEqual(data, False)

	def test_db_prepareinsert(self):
		res = self.db.prepare_insert(self.data)
		self.assertEqual(res['column'], 'lastname,allocated,living_space,firstname')


	def test_db_create(self):
		self.db.create(self.data)
		self.assertEqual(self.db.error_message, '')

	def test_db_find(self):
		self.db.create(self.data)
		id = self.db.last_id()
		res = self.db.find(id)
		self.assertEqual(self.db.error_message, '')
		self.assertEqual(res['firstname'], 'sunday')

	def test_db_findall(self):
		self.db.create(self.data)
		res = self.db.find_all()
		self.assertEqual(self.db.error_message, '')
		self.assertNotEqual(len(res), 0)
	
	def test_db_findbyattr(self):
		self.db.create(self.data)
		res = self.db.find_by_attr({'firstname':'sunday','allocated':1},'AND')
		self.assertEqual(self.db.error_message, '')
		self.assertNotEqual(len(res), 0)

	def test_db_set_attr(self):
		self.db.create(self.data)
		res = self.db.find(1)
		self.assertEqual(self.db.error_message, '')
		self.assertEqual(self.db.firstname, self.data['firstname'])

	def test_db_prepare_update(self):
		res = self.db.prepare_update(self.data)
		self.assertEqual(res, 'lastname = :lastname,allocated = :allocated,living_space = :living_space,firstname = :firstname')

	def test_db_prepare_attr(self):
		res = self.db.prepare_attr(self.data,'AND')
		self.assertEqual(res, 'lastname = :lastname AND allocated = :allocated AND living_space = :living_space AND firstname = :firstname')

	def test_db_validate_id(self):
		res = self.db.validate_id(None)
		self.assertEqual(res, False)

	def test_db_update_without_id(self):
		self.assertRaises(ValueError, self.db.update, self.data)

	def test_db_update_with_id_from_find(self):
		self.db.create(self.data)
		id = self.db.last_id()
		self.db.find(id)
		self.data['firstname'] = 'david'
		self.db.update(self.data)
		self.assertEqual(self.db.error_message, '')
		self.db.find(id)
		self.assertEqual(self.db.firstname, 'david')

	def test_db_update_with_id_known(self):
		self.db.create(self.data)
		id = self.db.last_id()
		self.data['firstname'] = 'david'
		self.db.update(self.data,id)
		self.assertEqual(self.db.error_message, '')
		self.db.find(id)
		self.assertEqual(self.db.firstname, 'david')
Exemplo n.º 12
0
from src.db import Db
from src.log import log
from sqlalchemy import *
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref


db=Db()
engine = db.create_session()
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    nombre = Column(String(50))
    apellido = Column(String(50))
    username = Column(String(50))
    password = Column(String(50))

    def __init__(self, nombre, apellido,username, password):
        self.nombre = nombre
        self.apellido= apellido
        self.username=username
        self.password=password

    def __repr__(self):
Exemplo n.º 13
0
from src.field import Field
from src.table import Table
from src.db import Db

fields = [
    Field('id', 'int', primary_key=True),
    Field('name', 'str'),
    Field('city', 'str', nullable=True),
    Field('activated', 'bool')
]
table = Table('users', fields)

db = Db([table])

print(Db)
Exemplo n.º 14
0
	def __init__(self):
		self.db = Db()
		self.file_manager = FileMan('')