Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A place for simple web applications #478

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
118 changes: 118 additions & 0 deletions flask-connexion-rest-part-4/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# ignore the database
people.db
Empty file.
63 changes: 63 additions & 0 deletions flask-connexion-rest-part-4/build_database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import os
from datetime import datetime
from config import db
from models import Person, Note

# Data to initialize database with
PEOPLE = [
{
"fname": "Doug",
"lname": "Farrell",
"notes": [
("Cool, a mini-blogging application!", "2019-01-06 22:17:54"),
("This could be useful", "2019-01-08 22:17:54"),
("Well, sort of useful", "2019-03-06 22:17:54"),
],
},
{
"fname": "Kent",
"lname": "Brockman",
"notes": [
(
"I'm going to make really profound observations",
"2019-01-07 22:17:54",
),
(
"Maybe they'll be more obvious than I thought",
"2019-02-06 22:17:54",
),
],
},
{
"fname": "Bunny",
"lname": "Easter",
"notes": [
("Has anyone seen my Easter eggs?", "2019-01-07 22:47:54"),
("I'm really late delivering these!", "2019-04-06 22:17:54"),
],
},
]

# Delete database file if it exists currently
if os.path.exists("people.db"):
os.remove("people.db")

# Create the database
db.create_all()

# iterate over the PEOPLE structure and populate the database
for person in PEOPLE:
p = Person(lname=person.get("lname"), fname=person.get("fname"))

# Add the notes for the person
for note in person.get("notes"):
content, timestamp = note
p.notes.append(
Note(
content=content,
timestamp=datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S"),
)
)
db.session.add(p)

db.session.commit()
26 changes: 26 additions & 0 deletions flask-connexion-rest-part-4/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import os
import connexion
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

basedir = os.path.abspath(os.path.dirname(__file__))

# Create the connexion application instance
connex_app = connexion.App(__name__, specification_dir=basedir)

# Get the underlying Flask app instance
app = connex_app.app

# Build the Sqlite ULR for SqlAlchemy
sqlite_url = "sqlite:////" + os.path.join(basedir, "people.db")

# Configure the SqlAlchemy part of the app instance
app.config["SQLALCHEMY_ECHO"] = False
app.config["SQLALCHEMY_DATABASE_URI"] = sqlite_url
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

# Create the SqlAlchemy db instance
db = SQLAlchemy(app)

# Initialize Marshmallow
ma = Marshmallow(app)
80 changes: 80 additions & 0 deletions flask-connexion-rest-part-4/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
from datetime import datetime
from config import db, ma
from marshmallow import fields


class Person(db.Model):
__tablename__ = "person"
person_id = db.Column(db.Integer, primary_key=True)
lname = db.Column(db.String(32))
fname = db.Column(db.String(32))
timestamp = db.Column(
db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow
)
notes = db.relationship(
"Note",
backref="person",
cascade="all, delete, delete-orphan",
single_parent=True,
order_by="desc(Note.timestamp)",
)


class Note(db.Model):
__tablename__ = "note"
note_id = db.Column(db.Integer, primary_key=True)
person_id = db.Column(db.Integer, db.ForeignKey("person.person_id"))
content = db.Column(db.String, nullable=False)
timestamp = db.Column(
db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow
)


class PersonSchema(ma.ModelSchema):
def __init__(self, **kwargs):
super().__init__(strict=True, **kwargs)

class Meta:
model = Person
sqla_session = db.session

notes = fields.Nested("PersonNoteSchema", default=[], many=True)


class PersonNoteSchema(ma.ModelSchema):
"""
This class exists to get around a recursion issue
"""

def __init__(self, **kwargs):
super().__init__(strict=True, **kwargs)

note_id = fields.Int()
person_id = fields.Int()
content = fields.Str()
timestamp = fields.Str()


class NoteSchema(ma.ModelSchema):
def __init__(self, **kwargs):
super().__init__(strict=True, **kwargs)

class Meta:
model = Note
sqla_session = db.session

person = fields.Nested("NotePersonSchema", default=None)


class NotePersonSchema(ma.ModelSchema):
"""
This class exists to get around a recursion issue
"""

def __init__(self, **kwargs):
super().__init__(strict=True, **kwargs)

person_id = fields.Int()
lname = fields.Str()
fname = fields.Str()
timestamp = fields.Str()
Loading