Untitled

mail@pastecode.io avatar
unknown
python
2 years ago
2.9 kB
6
Indexable
Never
# app.py

from flask import render_template
import config
from models import Person
from os.path import join



app = config.connex_app
app.add_api(join(config.basedir,"swagger.yml"))


@app.route("/")
def home():
    people = Person.query.all()
    return render_template("home.html",people=people)

if __name__ == "__main__":
    app.run(host="0.0.0.0",
            port=8000,
            debug=True)
            

# models.py

from datetime import datetime as dt
from config import db, ma
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema


class Person(db.Model):
    __tablename__ = "person"
    id = db.Column(db.Integer, 
                   primary_key=True)

    lname = db.Column(db.String(32),
                      unique=True)

    fname = db.Column(db.String(32))

    timestamp = db.Column(db.DateTime,
                          default=dt.utcnow,
                          onupdate=dt.utcnow)

 
class PersonSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Person
        load_instance = True
        sqla_session = db.session

person_schema = PersonSchema()
people_schema = PersonSchema(many=True)


# people.py

from flask import abort, make_response
from config import db
from models import Person, person_schema, people_schema

def read_all():
    people = Person.query.all()
    return people_schema.dump(people)

def create(person):
    lname = person.get("lname")
    existing_person = Person.query.filter(Person.lname == lname).one_or_none()

    if not existing_person:
        new_person = person_schema.load(person, session=db.session)
        db.session.add(new_person)
        db.session.commit()
        return person_schema.dump(new_person), 201
    else:
        abort(
            406,
            f"Person with last name {lname} already exist",
    )

def read_one(lname):
    person = Person.query.filter(Person.lname == lname).one_or_none()
    if person:
        return person_schema.dump(person)
    else:
        abort(
            404, f"Person with last name {lname} not found."
        )

def update(lname, person):
    existing_person = Person.query.filter(Person.lname == lname).one_or_none()
    if existing_person:
        update_person = person_schema.load(person, session=db.session)
        existing_person.fname = update_person.fname
        db.session.merge(existing_person)
        db.session.commit()
        return person_schema.dump(existing_person), 201
    else:
        abort(
            404, f"Person with last name {lname} not found."
        )

def delete(lname):
    existing_person = Person.query.filter(Person.lname == lname).one_or_none()
    if existing_person:
        db.session.delete(existing_person)
        db.session.commit()
        return make_response(f"Person with last name {lname} successfully deleted", 200)
    else:
        abort(
            404, f"Person with last name {lname} not found."
        )