diff --git a/config.json b/config.json new file mode 100644 index 0000000..bf1d796 --- /dev/null +++ b/config.json @@ -0,0 +1,8 @@ +{ + "database": { + "dbAddress": "localhost", + "dbUser": "root", + "dbName": "duzz-pedidos", + "dbPass": "" + } +} \ No newline at end of file diff --git a/resources/models/__init__.py b/resources/models/__init__.py new file mode 100644 index 0000000..2a34285 --- /dev/null +++ b/resources/models/__init__.py @@ -0,0 +1,65 @@ +from werkzeug.exceptions import BadRequest +from datetime import datetime + + +class Models: + def body_validate(self, body, header, minLen=None, maxLen=None): + body = {} if not body else body + + if not isinstance(body, dict): + body = self.get_dict_from_json(body) + + if minLen: + if len(body) < minLen: + raise BadRequest(message='O tamanho do body é menor que o mínimo permitido') + if maxLen: + if len(body) > maxLen: + raise BadRequest(message='O tamanho do body é maior que o mínimo permitido') + + for item in header: + if header[item]['required']: + try: + body[item] + except KeyError: + raise BadRequest + + for item in body.keys(): + if item not in header.keys(): + raise BadRequest + + if not isinstance(body[item], header[item]['type']): + if header[item]['type'] is datetime: + if isinstance(body[item], str): + dateFormat = header[item].get('dateFormat') + + dateFormat = dateFormat if dateFormat else '%Y%m%d%H%M%S' + + body[item] = datetime.strptime(body[item], dateFormat) + elif header[item]['type'] is dict: + if isinstance(body[item], str): + body[item] = self.get_dict_from_json(body[item]) + else: + raise BadRequest(f'não foi possivel converter o {item} à objeto') + elif type(body[item]) is bool: + try: + if isinstance(body[item], str): + if 'false' in body[item].lower(): + body[item] = False + elif 'true' in body[item].lower(): + body[item] = True + else: + body[item] = bool(int(body[item])) + except: + raise BadRequest + elif type(body[item]) is str: + try: + body[item] = header[item]['type'](body[item]) + except: + raise BadRequest + else: + try: + body[item] = header[item]['type'](body[item]) + except: + raise BadRequest + + return body \ No newline at end of file diff --git a/resources/models/database.py b/resources/models/database.py new file mode 100644 index 0000000..fdbf41d --- /dev/null +++ b/resources/models/database.py @@ -0,0 +1,136 @@ +#encoding utf-8 + +#__author__ = Jonas Duarte, duarte.jsystem@gmail.com +#Python3 + +import os +import MySQLdb as mdb + +import json + + +class Database(): + def __init__(self): + self.connected = False + + + def connect(self): + if not self.connected: + credencials = self.authenticate() + address = credencials.get('DatabaseAddress') + name = credencials.get('DatabaseName') + user = credencials.get('DatabaseUser') + password = credencials.get('DatabaseUserPass') + + try: + self.bank = mdb.connect(address, user, password, name, port=3306) + except: + self.conected = False + raise + else: + self.cursor = self.bank.cursor() + self.conected = True + + return { + 'Database' : self.bank, + 'Cursor' : self.cursor + } + + + def disconnect(self): + if self.connected: + try: + self.bank.close() + except: + raise Exception('Database connection not initialized') + + self.conected = False + return True + + + def authenticate(self): + """ + Utiliza as informações presentes no config para\n + retorná-las em forma de lista como credenciais + Retorno -> Lista:\n + [0] IP banco, [1] Usuario Banco\n + [2] Senha Usuario, [3] Nome Banco + """ + with open('config.json', 'r') as config: + config = json.loads( + config.read() + ) + + config = config['database'] + + db_address = config.get('dbAddress') + db_user = config.get('dbUser') + db_name = config.get('dbName') + db_user_password = config.get('dbPass') + if db_user_password is None: + if os.environ.get('db_pass') is not None: + db_user_password = os.environ.get('db_pass') + else: + db_user_password = '' + + return { + 'DatabaseAddress' : db_address, + 'DatabaseName' : db_name, + 'DatabaseUser' : db_user, + 'DatabaseUserPass' : db_user_password + } + + + def execute_with_commit(self, query): + self.connect() + try: + self.cursor.execute(query) + except: + raise + else: + self.bank.commit() + self.disconnect() + return True + + + def execute_with_return(self, query, header=None): + results = None + + self.connect() + try: + self.cursor.execute(query) + except: + raise + else: + results = list(self.cursor.fetchall()) + + if header: + for _, result in enumerate(results): + results[_] = {f'{header[x]}':result[x] for x in range(len(header))} + + self.disconnect() + + return results + + + def parameters_parse(self, query, parameters={}): + try: + with open(query, 'r') as sql: + query = " ".join(sql.read().split()) + + for parameter in parameters.keys(): + query = query.replace('{'+parameter+'}', parameters[parameter]) + except: + raise + return query + + + def return_columns(self, table): + columns = self.execute_with_return('show tables') + + dict_columns = {} + + for column in columns: + dict_columns[column[0]] = [column[x+1] for x in range(len(column[1:]))] + + return dict_columns diff --git a/resources/pedidos/__init__.py b/resources/pedidos/__init__.py index a73851a..f15a521 100644 --- a/resources/pedidos/__init__.py +++ b/resources/pedidos/__init__.py @@ -1,11 +1,13 @@ from flask_restful import Resource +from resources.models.database import Database + class Pedidos(Resource): def get(self): return { 'codigo': 1 } - + def put(self): pass diff --git a/resources/pedidos/_models/__init__.py b/resources/pedidos/_models/__init__.py new file mode 100644 index 0000000..aa1202e --- /dev/null +++ b/resources/pedidos/_models/__init__.py @@ -0,0 +1,69 @@ +from resources.models.database import Database +from resources.models import Models + + +class ModelPedidos: + def __init__(self): + self.database = Database() + self.models = Models() + + + def novo(self): + pass + + + def editar(self): + pass + + + def excluir(self): + pass + + + def pesquisar(self, data): + data = self.models.body_validate( + data, { + 'id': { + 'required': False, + 'type': int + }, + 'lanches': { + 'required': False, + 'type': str + }, + 'cliente': { + 'required': False, + 'type': str + }, + 'status': { + 'required' + } + } + ) + + if not data: + pedidos = self.database.execute_with_return( + ''' + SELECT + * + FROM + `pedidos` + ''', self.database.return_columns('pedidos') + ) + else: + if data.get('id') is not None: + pedidos = self.database.execute_with_return( + f''' + SELECT + * + FROM + `pedidos` + WHERE + id = {data["id"]} + ''', self.database.return_columns('pedidos') + ) + + else: + + + \ No newline at end of file diff --git a/resources/pedidos/_models/queries/buscar_pedidos.sql b/resources/pedidos/_models/queries/buscar_pedidos.sql new file mode 100644 index 0000000..d4a167f --- /dev/null +++ b/resources/pedidos/_models/queries/buscar_pedidos.sql @@ -0,0 +1,5 @@ +SELECT + * +FROM + `duzz-pedidos` +{WHERE} \ No newline at end of file