Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
9d6530e
Create noticiacontroller.py
HenryVQ197 May 15, 2024
774f051
Create noticiamodel.py
HenryVQ197 May 15, 2024
4f68746
Create noticiarouters.py
HenryVQ197 May 15, 2024
9c41002
Create eliminarnoticia.html
HenryVQ197 May 15, 2024
2746807
basura
HenryVQ197 May 15, 2024
6a55435
Update eliminarnoticia.html
HenryVQ197 May 15, 2024
3bf77e5
noticia,py
HenryVQ197 May 15, 2024
da431ae
Update noticiarouters.py
HenryVQ197 May 15, 2024
a254e21
Create schemas.py
HenryVQ197 May 15, 2024
690609b
Create conexionbd.py
HenryVQ197 May 15, 2024
bec9323
Create main.py
HenryVQ197 May 15, 2024
db34648
Update noticiacontroller.py
HenryVQ197 May 15, 2024
c9ab2f4
Update noticiamodel.py
HenryVQ197 May 15, 2024
0eb260c
Update noticiarouters.py
HenryVQ197 May 15, 2024
a82d6d2
Update noticiarouters.py
HenryVQ197 May 15, 2024
e7e72f3
Update noticiarouters.py
HenryVQ197 May 15, 2024
3646e61
Update eliminarnoticia.html
HenryVQ197 May 15, 2024
8bf2acc
Update noticiacontroller.py
HenryVQ197 May 15, 2024
b21a6b7
Update noticiacontroller.py
HenryVQ197 May 15, 2024
966d34b
Update noticiacontroller.py
HenryVQ197 May 15, 2024
759abd5
Update noticiacontroller.py
HenryVQ197 May 15, 2024
2ac5fdc
Update noticiamodel.py
HenryVQ197 May 15, 2024
debf663
Update eliminarnoticia.html
HenryVQ197 May 15, 2024
87f7a6b
Update noticiacontroller.py
HenryVQ197 May 15, 2024
61c2612
Update noticiamodel.py
HenryVQ197 May 15, 2024
332ac3c
Update eliminarnoticia.html
HenryVQ197 May 15, 2024
a4b21c3
Create eliminarnoticia.js
HenryVQ197 May 15, 2024
6d69731
Delete src/views/eliminarnoticia.js
HenryVQ197 May 15, 2024
77d7525
Create eliminarnoticia.js
HenryVQ197 May 15, 2024
f96cbb5
Update main.py
HenryVQ197 May 15, 2024
6a3dfd7
Update main.py
HenryVQ197 May 15, 2024
e567846
Delete conexionbd.py
HenryVQ197 May 24, 2024
1dbeebb
Delete main.py
HenryVQ197 May 24, 2024
2450cb2
Create main.py
HenryVQ197 May 24, 2024
e938ca0
Create conexionbd.py
HenryVQ197 May 24, 2024
50ae1b4
Create scriptver.js
HenryVQ197 May 24, 2024
59682af
Create style.css
HenryVQ197 May 24, 2024
1470528
Create info.txt
HenryVQ197 May 24, 2024
c405e07
Update noticiacontroller.py
HenryVQ197 May 24, 2024
665987b
Update noticia.py
HenryVQ197 May 24, 2024
2455d59
Update noticiamodel.py
HenryVQ197 May 24, 2024
5f5e606
Update schemas.py
HenryVQ197 May 24, 2024
be22fcb
Update noticiarouters.py
HenryVQ197 May 24, 2024
6f23049
Delete src/views/basura.png
HenryVQ197 May 24, 2024
ac7a87a
Delete src/views/eliminarnoticia.html
HenryVQ197 May 24, 2024
215d53c
Delete src/views/eliminarnoticia.js
HenryVQ197 May 24, 2024
e327f31
Create crearnoticia.html
HenryVQ197 May 24, 2024
273eee7
Create noticiaver.html
HenryVQ197 May 24, 2024
cc933a1
a
HenryVQ197 May 24, 2024
9733bff
Update crearnoticia.html
HenryVQ197 May 24, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions conexionbd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from sqlalchemy import create_engine
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base

SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"

engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()
40 changes: 40 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from fastapi import FastAPI, File, UploadFile
from fastapi.staticfiles import StaticFiles
from starlette.responses import FileResponse
from src.routers.noticiarouters import router as noticia_router
from conexionbd import Base, engine
import os

# Crear todas las tablas en la base de datos
Base.metadata.create_all(bind=engine)

# Crear la instancia de la aplicación FastAPI
app = FastAPI()

# Montar directorio estático
app.mount("/static", StaticFiles(directory="static"), name="static")

# Incluir el router de noticias
app.include_router(noticia_router, prefix="/api/v1")

# Endpoint para servir el archivo noticiaver.html
@app.get("/")
async def get_index():
return FileResponse("src/views/noticiaver.html")

# Endpoint para servir el archivo crearnoticia.html
@app.get("/crearnoticia.html")
async def get_create_news():
return FileResponse("src/views/crearnoticia.html")

# Endpoint para manejar la subida de archivos
@app.post("/api/v1/noticias/")
async def create_noticia(titulo: str, cuerpo: str, archivo: UploadFile = File(...)):
# Guarda el archivo
upload_folder = "/static/images"
os.makedirs(upload_folder, exist_ok=True)
file_location = f"{upload_folder}/{archivo.filename}"
with open(file_location, "wb") as file:
file.write(archivo.file.read())

return {"titulo": titulo, "cuerpo": cuerpo, "archivo": f"/static/images/{archivo.filename}"}
14 changes: 14 additions & 0 deletions src/controllers/noticiacontroller.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import sys
import os

# Agregar la ruta del directorio raíz de tu proyecto al sys.path
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from fastapi import APIRouter
from src.models.noticiamodel import get_crearnoticia

router = APIRouter()

@router.get("/")
async def get_index():
return get_crearnoticia()
17 changes: 17 additions & 0 deletions src/models/noticia.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import sys
import os

# Agregar la ruta del directorio raíz de tu proyecto al sys.path
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from sqlalchemy import Column, Integer, String, Date
from conexionbd import Base

class Noticia(Base):
__tablename__ = 'noticias'

id_noticia = Column(Integer, primary_key=True, index=True)
titulo = Column(String, index=True)
cuerpo = Column(String)
archivo = Column(String) # Ruta del archivo
fecha = Column(Date)
40 changes: 40 additions & 0 deletions src/models/noticiamodel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import sys
import os

# Agregar la ruta del directorio raíz de tu proyecto al sys.path
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from sqlalchemy.orm import Session
from fastapi import UploadFile
from src.models.noticia import Noticia
from src.models.schemas import NoticiaCreate
from fastapi.responses import FileResponse
import shutil

def save_file(file: UploadFile, destination: str):
with open(destination, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
return destination

def get_crearnoticia():
return FileResponse("src/views/crearnoticia.html")

def create_noticia(db: Session, noticia: NoticiaCreate, file: UploadFile):
file_path = save_file(file, f"static/images/{file.filename}")
db_noticia = Noticia(id_noticia=noticia.id_noticia, titulo=noticia.titulo, cuerpo=noticia.cuerpo,
archivo=file_path, fecha=noticia.fecha)
db.add(db_noticia)
db.commit()
db.refresh(db_noticia)
return db_noticia

def get_noticias(db: Session):
return db.query(Noticia).all()

def get_noticia(db: Session, noticia_id: int):
return db.query(Noticia).filter(Noticia.id_noticia == noticia_id).first()

def delete_noticia(db: Session, noticia_id: int):
db.query(Noticia).filter(Noticia.id_noticia == noticia_id).delete()
db.commit()

21 changes: 21 additions & 0 deletions src/models/schemas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from pydantic import BaseModel
from datetime import date

# Actúa como una clase base, reduciendo la duplicación de código y asegurando que los campos comunes estén centralizados.
class NoticiaBase(BaseModel):
titulo: str
cuerpo: str
archivo: str
fecha: date

# Extiende NoticiaBase y añade campos específicos necesarios solo para la creación.
class NoticiaCreate(NoticiaBase):
id_noticia: int

# Extiende NoticiaBase y añade campos necesarios para la respuesta de la API,
# junto con configuraciones específicas para la interoperabilidad con SQLAlchemy.
class NoticiaSchema(NoticiaBase):
id_noticia: int

class Config:
from_attributes = True
81 changes: 81 additions & 0 deletions src/routers/noticiarouters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import sys
import os
import shutil
from fastapi import HTTPException, Depends, APIRouter, UploadFile, Form
from sqlalchemy.orm import Session
from fastapi.responses import JSONResponse
from fastapi import File

# Agregar la ruta del directorio raíz de tu proyecto al sys.path
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from conexionbd import SessionLocal
from src.models.noticiamodel import create_noticia as create_noticia_db, get_noticias as get_noticias_db, get_noticia as get_noticia_db, delete_noticia as delete_noticia_db
from src.models.schemas import NoticiaCreate, NoticiaSchema
from src.models.noticia import Noticia

router = APIRouter()

def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

def get_next_noticia_id(db: Session) -> int:
"""Obtiene el próximo ID disponible para una nueva noticia."""
last_noticia = db.query(Noticia).order_by(Noticia.id_noticia.desc()).first()
if last_noticia:
return last_noticia.id_noticia + 1
else:
return 1

@router.post("/noticias/", response_model=NoticiaSchema)
def create_noticia(
titulo: str = Form(...),
cuerpo: str = Form(...),
fecha: str = Form(...),
archivo: UploadFile = File(...),
db: Session = Depends(get_db)
):
# Obtener el próximo ID disponible
id_noticia = get_next_noticia_id(db)

# Crear el directorio de imágenes si no existe
upload_folder = "static/images"
os.makedirs(upload_folder, exist_ok=True)

# Guardar el archivo en el directorio y obtener su ruta
file_path = os.path.join(upload_folder, archivo.filename)
with open(file_path, "wb") as file_object:
shutil.copyfileobj(archivo.file, file_object)

# Crear el objeto NoticiaCreate
noticia_data = NoticiaCreate(id_noticia=id_noticia, titulo=titulo, cuerpo=cuerpo, archivo=file_path, fecha=fecha)
return create_noticia_db(db, noticia_data, archivo)

@router.get("/noticias/", response_model=list[NoticiaSchema])
def read_noticias(db: Session = Depends(get_db)):
return get_noticias_db(db)

@router.get("/noticias/{noticia_id}", response_model=NoticiaSchema)
def read_publicacion(noticia_id: int, db: Session = Depends(get_db)):
db_noticia = get_noticia_db(db, noticia_id)
if db_noticia is None:
raise HTTPException(status_code=404, detail="Publicación no encontrada")
return db_noticia

@router.delete("/noticias/{noticia_id}", response_model=dict)
def delete_noticia(noticia_id: int, db: Session = Depends(get_db)):
db_noticia = get_noticia_db(db, noticia_id)
if db_noticia is None:
raise HTTPException(status_code=404, detail="Publicación no encontrada")
delete_noticia_db(db, noticia_id)
return {"detail": "Noticia eliminada"}

@router.get("/noticias/buscar/", response_model=list[NoticiaSchema])
def search_noticias(query: str, db: Session = Depends(get_db)):
noticias = db.query(Noticia).filter(Noticia.titulo.ilike(f"%{query}%")).all()
return noticias

65 changes: 65 additions & 0 deletions src/views/crearnoticia.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crear Noticia</title>
<!-- Incluir estilos CSS -->
<link rel="stylesheet" href="/static/style.css">
<style>
.button-container {
display: flex;
gap: 10px; /* Espacio entre los botones */
}
</style>
</head>
<body>
<div class="container">
<h1>Crear Noticia</h1>
<form id="noticia-form" action="/api/v1/noticias/" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="titulo">Título:</label>
<input type="text" id="titulo" name="titulo" required> <br><br>
</div>
<div class="form-group">
<label for="cuerpo">Cuerpo:</label>
<textarea id="cuerpo" name="cuerpo" rows="4" required></textarea> <br><br>
</div>
<div class="form-group">
<label for="archivo">Archivo:</label>
<input type="file" id="archivo" name="archivo" accept="image/*" required> <br><br>
</div>
<div class="form-group">
<label for="fecha">Fecha:</label>
<input type="date" id="fecha" name="fecha" required> <br><br>
</div>
<button type="submit">PUBLICAR!</button>
<button type="button" onclick="redirectToNewsPage()">Volver</button>
</form>
</div>
<script>
function redirectToNewsPage() {
window.location.href = "/";
}

document.getElementById('imagen').addEventListener('change', function() {
const preview = document.getElementById('imagen-preview');
const file = this.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
preview.src = e.target.result;
preview.style.display = 'block';
};
reader.readAsDataURL(file);
} else {
preview.src = '#';
preview.style.display = 'none';
}
});
</script>
<script src="/static/scriptver.js"></script>
</body>
</html>


30 changes: 30 additions & 0 deletions src/views/noticiaver.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Noticias</title>
<link rel="stylesheet" href="/static/style.css">
<script src="/static/scriptver.js" defer></script>
</head>
<body>
<div class="container">
<header>
<h1>Hola [Name], aquí están las noticias más relevantes</h1>
<div>
<input type="text" id="search" placeholder="Buscar noticias...">
<button id="search-button">Buscar</button>
</div>
<button onclick="redirectToCreateNewsPage()" class="create-news-btn">Crear Noticia</button>
<script>
function redirectToCreateNewsPage() {
window.location.href = "/crearnoticia.html";
}
</script>
<main id="noticias-list">
<!-- Las noticias se cargarán aquí dinámicamente -->
</main>
</div>
</body>
</html>

Binary file added static/images/bell-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions static/images/info.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**aqui van las imagenes que se cargan en las noticias**
Binary file added static/images/trash-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading