Skip to content

Commit

Permalink
deserealizadores con marshmallow y endpoints funcionando correctamente
Browse files Browse the repository at this point in the history
  • Loading branch information
Aaronga19 committed Dec 17, 2021
1 parent 0b21bdb commit c1036ae
Show file tree
Hide file tree
Showing 6 changed files with 160 additions and 38 deletions.
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ importlib-metadata==4.8.2
itsdangerous==2.0.1
Jinja2==3.0.3
MarkupSafe==2.0.1
marshmallow==3.14.1
marshmallow-sqlalchemy==0.26.1
numpy==1.21.4
openpyxl==3.0.9
pandas==1.3.5
Expand Down
4 changes: 3 additions & 1 deletion sepomex/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@
from sepomex.config import settings
from flask_bcrypt import Bcrypt
from flask_login import LoginManager, login_manager
from flask_marshmallow import Marshmallow


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']= f'postgresql://{settings.database_username}:{settings.database_password}@{settings.database_hostname}:{settings.database_port}/{settings.database_name}'
app.config['SECRET_KEY'] = settings.secret_key
db = SQLAlchemy(app)

ma = Marshmallow(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
Expand Down
56 changes: 56 additions & 0 deletions sepomex/data_structures/linked_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
class Node:
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def to_list(self):
l = []
if self.head is None:
return l

node = self.head
while node:
l.append(node.data)
node = node.next_node
return l

def print_ll(self):
ll_string = ""
node = self.head
if node is None:
print(None)
while node:
ll_string += f" {str(node.data)} ->"
node = node.next_node
ll_string += " None"
print(ll_string)

def insert_beginning(self, data):
if self.head is None:
self.head = Node(data, None)
self.last_node = self.head

new_node = Node(data, self.head)
self.head = new_node


def insert_at_end(self, data):
if self.head is None:
self.insert_beginning(data)
return

self.last_node.next_node = Node(data, None)
self.last_node = self. last_node.next_node

def get_user_by_id(self, user_id):
node = self.head
while node:
if node.data["id"] is int(user_id):
return node.data
node = node.next_node
return None
4 changes: 4 additions & 0 deletions sepomex/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ def load_user(user_id):
return User.query.get(int(user_id))

class User(db.Model, UserMixin):
" Modelo de tabla de usuarios para acceder a la api"
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer(), primary_key=True)
username = db.Column(db.String(length=30), nullable=False, unique=True)
Expand Down Expand Up @@ -35,6 +36,9 @@ class States(db.Model):
name = db.Column(db.String(length=50), nullable=False, unique=True)
data = db.relationship('Records', backref="state", lazy=True)

def __repr__(self):
return f'Item: {self.name}'


class Records(db.Model):
"Tabla de registros de cada una de los lugares de cada estado"
Expand Down
105 changes: 68 additions & 37 deletions sepomex/routes.py
Original file line number Diff line number Diff line change
@@ -1,64 +1,74 @@
from flask import render_template, redirect, url_for, flash, request, jsonify
from flask.helpers import flash
import flask_login
# import linked_list
import requests
from sepomex.__init__ import app, db
from sepomex.models import User, States, Records
from sepomex.forms import RegisterForm, LoginForm
from flask_login import login_user, logout_user, login_required, current_user
from sepomex.json_read import states, load_json
from sepomex.schemas import RecordSchema, UserSchema, StateSchema, StateSchemaNoRel

from sepomex.sepomexextractinfo import data


@app.route('/')
@app.route('/home')
def home():
return render_template('index.html')

# API

@app.route('/api/welcome', methods=['GET'])
@login_required
def api_welcome():

return jsonify({'message':'Bienvenido a la API'})
"""Da la bievenida para que el usuario sepa que ahora tiene acceso a la ap"""

return jsonify({'message':'Bienvenido a la API'})

@app.route('/api/sepomex/one/<id>', methods=['GET'])
# Rutas de Estados API

@app.route('/api/get/one/state/<state_name>', methods=['GET'])
@login_required
def get_one_state(id: int):
# Consultas a la base de datos
state = States.query.get_or_404(id)
return {'name': state.name, 'data': state.data}


# Con librerias
# state = States.query.all()
# all_states_ll = linked_list.LinkedList()

# for place in states:
# all_states_ll.insert_beginning(
# {
# "id": place.id,
# "name": place.name,
# "records": place.data
# }
# )

# response = all_states_ll.get_user_by_id(state_name)
# return jsonify(response), 200

# Extraer información desde el DataFrame de pandas
# response = data[state].to_json()
# response
# Para leer información desde los archivos json que fueron extraido por script
# path = f'sepomex/json/{state}.json'
# response = load_json(path)
# return response

@app.route('/api/add/record', methods=['POST'])
def get_one_state(state_name: str):
"""Obtener los datos de los estados y la data de la que corresponde cada registro (regresa id) """

state = States.query.filter_by(name=state_name).first()
state_schema = StateSchema()
dump_data = state_schema.dump(state)
return jsonify(dump_data)

@app.route('/api/get/all_states', methods=['GET'])
@login_required
def get_all_states():
"""Obtener todos los estados"""

states = States.query.all()
state_schema = StateSchemaNoRel(many=True)
dump_data = state_schema.dump(states)
return jsonify(dump_data)

# Rutas de Usuario API
@app.route('/api/get/user/<name>', methods=['GET'])
@login_required
def get_user(name: str):
"""Obtener información de un usuario"""
user = User.query.filter_by(username=name).first()
user_schema = UserSchema()
output = user_schema.dump(user)
return jsonify({'user':output})

@app.route('/api/get/all_users', methods=['GET'])
@login_required
def get_users():
"""Obtener información de todos los usuarios en la base"""
users = User.query.all()
user_schema = UserSchema(many=True)
output = user_schema.dump(users)
return jsonify({'users':output})

@app.route('/api/post/record', methods=['POST'])
@login_required
def add_record():
"""Añadir un nuevo registro"""
record = Records(
codigo_postal = request.json['codigo_postal'],
asentamiento = request.json['asentamiento'],
Expand All @@ -69,11 +79,30 @@ def add_record():
db.session.commit()
return {'id', record.id}, 200

# Rutas de Registros
@app.route('/api/get/record/<record_id>', methods=['GET'])
@login_required
def get_record_by_id(record_id: int):
"""obtener información de un registro"""
record = Records.query.filter_by(id=record_id).first()
record_schema = RecordSchema()
output = record_schema.dump(record)
return jsonify({'Registro':output})

@app.route('/api/get/records_from/<state_id>', methods=['GET'])
@login_required
def get_records_by_state_id(state_id: int):
"Obtener todos los registros que corresponden a un estado"
records = Records.query.filter_by(estado_id=state_id).all()
record_schema = RecordSchema(many=True)
output = record_schema.dump(records)
return jsonify({'Registros':output})

# Rutas de usuarios

@app.route('/register', methods=['GET', 'POST'])
def register():
"""Registrar a nuevo usuario"""
form = RegisterForm()
if form.validate_on_submit():
user_to_create = User(
Expand All @@ -97,6 +126,7 @@ def register():

@app.route('/login', methods=['GET', 'POST'])
def login():
"""Inicio de sesion de usuario"""
form = LoginForm()

if form.validate_on_submit():
Expand All @@ -114,6 +144,7 @@ def login():

@app.route('/logout')
def logout():
"""Cerrar session del usuario"""
logout_user()
flash('Has salido de tu sesión', category='info')
return redirect(url_for('home'))
27 changes: 27 additions & 0 deletions sepomex/schemas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from flask_sqlalchemy import model
from sepomex.__init__ import ma
from sepomex.models import User, States, Records


class UserSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = User
load_instance = True
include_relationships= True

class StateSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = States
include_relationships= True
load_instance = True

class StateSchemaNoRel(ma.SQLAlchemyAutoSchema):
class Meta:
model = States
load_instance = True

class RecordSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Records
load_instance = True
include_fk = True

0 comments on commit c1036ae

Please sign in to comment.