Documentos de Académico
Documentos de Profesional
Documentos de Cultura
RUBÉN SANABRIA
>virtual/scripts/actívate
(virtual) PS D:\curso2022_01\flask\curso2\practica4>
Una vez que se haya activado la carpeta virtual, empezamos a bajar las librerías
correspondientes:
pues bien, al crear la aplicación app, debemos crear las carpetas controllers, models, static,
templates dentro de app
Los models:
class User(db.Model):
__tablename__ = 'usuarios'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(60))
clave = db.Column(db.String(10))
email = db.Column(db.String(100))
La clase Post:
from app.models import user
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(60))
APLICACIONES CON FLASK ING. RUBÉN SANABRIA
La clase Follow
from app import db
from app.models import user, post
class Follow(db.Model):
__tablename__ = 'follows'
id = db.Column(db.Integer, primary_key = True)
Estos elementos son llamados en la clase __init__.py, que se encuentra en el proyecto app
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///stock.db'
app.config['SQLALCHEMY_TRACKING'] = False
app.config['SECRET_KEY'] = 'micodigosecreto'
db = SQLAlchemy(app)
db.create_all()
como resultado nos creara las tablas correspondientes con sus respectivas relaciones
APLICACIONES CON FLASK ING. RUBÉN SANABRIA
if __name__=='__main__':
app.run()
@app.route("/")
def index():
return "hola como estan"
La clase userController.py
@app.route("/user")
def registrar_user():
return render_template("add_user.html")
@app.route("/agregar", methods=['GET','POST'])
def adduser():
if request.method == 'POST':
name = request.form.get('name')
login = request.form.get('login')
clave = request.form.get('clave')
email = request.form.get('email')
APLICACIONES CON FLASK ING. RUBÉN SANABRIA
return redirect(url_for('index'))
@app.route("/borrar/<int:id>")
def delete_user(id):
usu = user.User.query.filter_by(id=id).first()
db.session.delete(usu)
db.session.commit()
usu = user.User.query.all()
return render_template('listausuario.html', usuario=usu)
@app.route("/editar/<id>", methods=["GET","POST"])
def edit_user(id):
usu = user.User.query.filter_by(id=id).first()
if request.method == "POST":
name = request.form.get('name')
login = request.form.get('login')
clave = request.form.get('clave')
email = request.form.get('email')
@app.route("/listauser")
def lista_user():
usuarios = user.User.query.all()
APLICACIONES CON FLASK ING. RUBÉN SANABRIA
Ahora nos adentramos en la vista del proyecto que comprende las carpetas de:
El index.html lo vemos :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<center>
<h1>Index del sistema</h1>
<hr>
<p></p>
<a href="{{url_for('registrar_user')}}">Crud de Usuario</a><br>
<a href="#">Crud de Post</a><br>
<a href="#">Crud de Follow</a><br>
</center>
</body>
</html>
El add_user.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
table, th, td {
border: 1px solid white;
border-collapse: collapse;
}
th, td {
background-color: #96D4D4;
}
</style>
</head>
<body>
<form action="{{url_for('adduser')}}" method="post">
<center>
<h1>CRUD Usuario</h1>
<a href="{{url_for('index')}}">Volver al index</a>
<a href="{{url_for('lista_user')}}">Ver listado</a><br>
<hr>
APLICACIONES CON FLASK ING. RUBÉN SANABRIA
<table >
<tr>
<td>Nombre :</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Login :</td>
<td><input type="text" name="login"></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="text" name="clave"></td>
</tr>
<tr>
<td>Email :</td>
<td><input type="text" name="email"></td>
</tr>
</table>
<input type="submit" value="Registrar">
</center>
</form>
<hr>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
table, th, td {
border: 1px solid white;
border-collapse: collapse;
}
th, td {
background-color: #96D4D4;
}
</style>
</head>
<body>
<h3>Listado de usuarios</h3>
<a href="{{url_for('registrar_user')}}">Crud de Usuario</a><br>
<table style="width:90%">
<tr>
<th>ID</th>
<th>NOMBRE</th>
<th>LOGIN</th>
<th>CLAVE</th>
<th>EMAIL</th>
<th></th>
</tr>
{% for usu in usuario %}
<tr>
<td>{{ usu.id }}</td>
<td>{{ usu.name }}</td>
APLICACIONES CON FLASK ING. RUBÉN SANABRIA
</table>
</body>
</html>
Al darle Editar :
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
table,
th,
td {
APLICACIONES CON FLASK ING. RUBÉN SANABRIA
th,
td {
background-color: #96D4D4;
}
</style>
</head>
<body>
<center>
<h1>Edita Usuario</h1>
<a href="{{url_for('index')}}">Volver al index</a>
<a href="{{url_for('lista_user')}}">Ver listado</a><br>
<form action="#" method="post">
<hr>
<table>
<tr>
<td>Codigo :</td>
<td><input type="text" name="id" value="{{ usu.id }}"
readonly></td>
</tr>
<tr>
<td>Nombre :</td>
<td><input type="text" name="name" value="{{ usu.name }}"></td>
</tr>
<tr>
<td>Login :</td>
<td><input type="text" name="login" value="{{ usu.login }}"></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="text" name="clave" value="{{ usu.clave }}"></td>
</tr>
<tr>
<td>Email :</td>
<td><input type="text" name="email" value="{{ usu.email }}"></td>
</tr>
</table>
<input type="submit" value="Actualizar">
</form>
APLICACIONES CON FLASK ING. RUBÉN SANABRIA
</center>
<hr>
</body>
Le agregamos un
controlador de post
También en template
agregamos una carpeta
para poder ir
ordenandolos
@app.route("/post")
def registrar_post():
return render_template("/post/add_post.html")
@app.route("/agregarpost", methods=['GET','POST'])
def add_post():
if request.method == 'POST':
name = request.form.get('name')
user = request.form.get('id_user')
return redirect(url_for('registrar_post'))
@app.route("/borrarpost/<int:id>")
def delete_post(id):
pst = post.Post.query.filter_by(id=id).first()
db.session.delete(pst)
db.session.commit()
pst = post.Post.query.all()
return render_template('/post/listapost.html', post=pst)
@app.route("/editarpost/<int:id>", methods=["GET","POST"])
def edit_post(id):
pst = post.Post.query.filter_by(id=id).first()
if request.method == "POST":
name = request.form.get('name')
user = request.form.get('id_user')
@app.route("/listapost")
def lista_post():
pst = post.Post.query.all()
return render_template('/post/listapost.html', post=pst)
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///stock.db'
app.config['SQLALCHEMY_TRACKING'] = False
app.config['SECRET_KEY'] = 'micodigosecreto' Aquí se ponen los controllers
que se van agregando
db = SQLAlchemy(app)
db.create_all()
}
</style>
</head>
<body>
<form action="{{url_for('add_post')}}" method="post">
<center>
<h1>Agrega Post</h1>
<a href="{{url_for('index')}}">Volver al index</a>
<a href="{{url_for('lista_post')}}">Ver listado</a><br>
<hr>
<table >
<tr>
<td>Nombre :</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Codigo User :</td>
<td><input type="text" name="id_user"></td>
</tr>
</table>
<input type="submit" value="Registrar">
</center>
</form>
<hr>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
table,
th,
td {
APLICACIONES CON FLASK ING. RUBÉN SANABRIA
th,
td {
background-color: #96D4D4;
}
</style>
</head>
<body>
<center>
<h1>Edita Post</h1>
<a href="{{url_for('index')}}">Volver al index</a>
<a href="{{url_for('lista_post')}}">Ver listado</a><br>
<form action="#" method="post">
<hr>
<table>
<tr>
<td>Codigo :</td>
<td><input type="text" name="id" value="{{ post.id }}"
readonly></td>
</tr>
<tr>
<td>Nombre :</td>
<td><input type="text" name="name" value="{{ post.name
}}"></td>
</tr>
<tr>
<td>Login :</td>
<td><input type="text" name="id_user" value="{{
post.id_user }}"></td>
</tr>
</table>
<input type="submit" value="Actualizar">
</form>
</center>
<hr>
</body>
APLICACIONES CON FLASK ING. RUBÉN SANABRIA
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
table,
th,
td {
border: 1px solid white;
border-collapse: collapse;
}
th,
td {
background-color: #96D4D4;
}
</style>
</head>
<body>
<h3>Listado de Post</h3>
<a href="{{url_for('registrar_post')}}">Crud de Post</a><br>
<table style="width:90%">
<tr>
<th>ID</th>
<th>NOMBRE</th>
<th>USUARIO</th>
<th></th>
</tr>
{% for p in post %}
<tr>
<td>{{ p.id }}</td>
<td>{{ p.name }}</td>
<td>{{ p.id_user }}</td>
<td>
<a href="/borrarpost/{{ p.id }}">Borrar</a>
<a href="/editarpost/{{ p.id }}">Editar</a>
</td>
APLICACIONES CON FLASK ING. RUBÉN SANABRIA
</tr>
{% endfor %}
</table>
</body>
</html>
El resultado sería:
Se ha cambiado el default, y también le hemos agregado elementos de css, con Jinja2, para
encontrar el camino de los archivos staticos.
@app.route("/")
def index():
# return render_template("index.html")
return render_template("login.html")
el login.html:
APLICACIONES CON FLASK ING. RUBÉN SANABRIA
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link type="text/css" rel="stylesheet"
href="{{url_for('static',filename='css/login.css')}}" />
<link type="text/css" rel="stylesheet"
href="{{url_for('static',filename='css/bootstrap.min.css')}}" />
</head>
<body>
<form id="form1">
<section class="form-login">
<h5>Sistema de Inventario</h5><br />
Login :<br />
<div class="input-group">
<span class="input-group-text"></span>
<input type="text" class="form-control" placeholder="ingrese
Login">
</div>
Password : <br />
<div class="input-group">
<span class="input-group-text"></span>
<input type="password" class="form-control"
placeholder="ingrese Password">
</div>
<br />
<button type="button" class="btn btn-primary">Ejecutar</button>
</section>
</form>
</body>
</html>
Podemos observar que utilizamos bootstrap, en el archivo static, u otro archivo css propio
del login. Al ejecutar dicho html, nos muestra..
APLICACIONES CON FLASK ING. RUBÉN SANABRIA