Skip to content

Commit

Permalink
Featuring: #4. Iniciada comunicação com o banco de dados
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonasdart committed Jul 7, 2021
1 parent 5f97a5f commit 41944fb
Show file tree
Hide file tree
Showing 6 changed files with 286 additions and 1 deletion.
8 changes: 8 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"database": {
"dbAddress": "localhost",
"dbUser": "root",
"dbName": "duzz-pedidos",
"dbPass": ""
}
}
65 changes: 65 additions & 0 deletions resources/models/__init__.py
Original file line number Diff line number Diff line change
@@ -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
136 changes: 136 additions & 0 deletions resources/models/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
#encoding utf-8

#__author__ = Jonas Duarte, [email protected]
#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
4 changes: 3 additions & 1 deletion resources/pedidos/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
69 changes: 69 additions & 0 deletions resources/pedidos/_models/__init__.py
Original file line number Diff line number Diff line change
@@ -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:



5 changes: 5 additions & 0 deletions resources/pedidos/_models/queries/buscar_pedidos.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
SELECT
*
FROM
`duzz-pedidos`
{WHERE}

0 comments on commit 41944fb

Please sign in to comment.