ciclos

commit 7119af33520057bd0e03d1695e899eee87091dbf

Author: Pedro Lucas Porcellis <pedrolucasporcellis@gmail.com>

[WIP] Basic database handling

Still need to work more on generalize into a Base model, and use
correct configuration etc

 .gitignore | 1 
 requirements.txt | 8 +++
 src/__init__.py | 13 ++++++
 src/alembic.ini.sample | 85 ++++++++++++++++++++++++++++++++++++++++
 src/alembic/README | 1 
 src/alembic/env.py | 77 ++++++++++++++++++++++++++++++++++++
 src/alembic/script.py.mako | 24 +++++++++++
 src/blueprints/auth.py | 13 ++++++
 src/types/__init__.py | 3 +
 src/types/user.py | 13 ++++++


diff --git a/.gitignore b/.gitignore
index 3b72af06f63e14ea65f6aac0929f38aa57590d94..b4a3fb67bfae3bc661448bf07c3075c4935388ef 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
+src/alembic.ini
 .env
 __pycache__




diff --git a/requirements.txt b/requirements.txt
index a6d2d3aa72c4bdee56fd194eb81fb43bf2e95e6b..c9cd11f2cad819cf2383292ffe17217aa18b252c 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,6 +1,14 @@
+alembic==1.3.1
 Click==7.0
 Flask==1.1.1
+Flask-SQLAlchemy==2.4.1
 itsdangerous==1.1.0
 Jinja2==2.10.3
+Mako==1.1.0
 MarkupSafe==1.1.1
+mysqlclient==1.4.6
+python-dateutil==2.8.1
+python-editor==1.0.4
+six==1.13.0
+SQLAlchemy==1.3.11
 Werkzeug==0.16.0




diff --git a/src/__init__.py b/src/__init__.py
index 425f9edb677440bd7e025853e487dcadd99c9a92..dc94a10d80692f62c5796298a8052a87368417b3 100644
--- a/src/__init__.py
+++ b/src/__init__.py
@@ -1,9 +1,22 @@
 from flask import Flask, render_template
+from flask_sqlalchemy import SQLAlchemy
 
 def create_app():
     app = Flask(__name__)
+
+    # Database
+    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/ciclos_dev'
     
+    from .types import db
+    db.init_app(app)
+
+    # Blueprints
     from .blueprints.basic import basic
+    from .blueprints.auth import auth
     app.register_blueprint(basic)
+    app.register_blueprint(auth)
+
+    with app.app_context():
+        db.create_all()
 
     return app




diff --git a/src/alembic/README b/src/alembic/README
new file mode 100644
index 0000000000000000000000000000000000000000..98e4f9c44effe479ed38c66ba922e7bcc672916f
--- /dev/null
+++ b/src/alembic/README
@@ -0,0 +1 @@
+Generic single-database configuration.
\ No newline at end of file




diff --git a/src/alembic/env.py b/src/alembic/env.py
new file mode 100644
index 0000000000000000000000000000000000000000..70518a2eef734a8fffcd787cfa397309469f8e76
--- /dev/null
+++ b/src/alembic/env.py
@@ -0,0 +1,77 @@
+from logging.config import fileConfig
+
+from sqlalchemy import engine_from_config
+from sqlalchemy import pool
+
+from alembic import context
+
+# this is the Alembic Config object, which provides
+# access to the values within the .ini file in use.
+config = context.config
+
+# Interpret the config file for Python logging.
+# This line sets up loggers basically.
+fileConfig(config.config_file_name)
+
+# add your model's MetaData object here
+# for 'autogenerate' support
+# from myapp import mymodel
+# target_metadata = mymodel.Base.metadata
+target_metadata = None
+
+# other values from the config, defined by the needs of env.py,
+# can be acquired:
+# my_important_option = config.get_main_option("my_important_option")
+# ... etc.
+
+
+def run_migrations_offline():
+    """Run migrations in 'offline' mode.
+
+    This configures the context with just a URL
+    and not an Engine, though an Engine is acceptable
+    here as well.  By skipping the Engine creation
+    we don't even need a DBAPI to be available.
+
+    Calls to context.execute() here emit the given string to the
+    script output.
+
+    """
+    url = config.get_main_option("sqlalchemy.url")
+    context.configure(
+        url=url,
+        target_metadata=target_metadata,
+        literal_binds=True,
+        dialect_opts={"paramstyle": "named"},
+    )
+
+    with context.begin_transaction():
+        context.run_migrations()
+
+
+def run_migrations_online():
+    """Run migrations in 'online' mode.
+
+    In this scenario we need to create an Engine
+    and associate a connection with the context.
+
+    """
+    connectable = engine_from_config(
+        config.get_section(config.config_ini_section),
+        prefix="sqlalchemy.",
+        poolclass=pool.NullPool,
+    )
+
+    with connectable.connect() as connection:
+        context.configure(
+            connection=connection, target_metadata=target_metadata
+        )
+
+        with context.begin_transaction():
+            context.run_migrations()
+
+
+if context.is_offline_mode():
+    run_migrations_offline()
+else:
+    run_migrations_online()




diff --git a/src/alembic/script.py.mako b/src/alembic/script.py.mako
new file mode 100644
index 0000000000000000000000000000000000000000..2c0156303a8df3ffdc9de87765bf801bf6bea4a5
--- /dev/null
+++ b/src/alembic/script.py.mako
@@ -0,0 +1,24 @@
+"""${message}
+
+Revision ID: ${up_revision}
+Revises: ${down_revision | comma,n}
+Create Date: ${create_date}
+
+"""
+from alembic import op
+import sqlalchemy as sa
+${imports if imports else ""}
+
+# revision identifiers, used by Alembic.
+revision = ${repr(up_revision)}
+down_revision = ${repr(down_revision)}
+branch_labels = ${repr(branch_labels)}
+depends_on = ${repr(depends_on)}
+
+
+def upgrade():
+    ${upgrades if upgrades else "pass"}
+
+
+def downgrade():
+    ${downgrades if downgrades else "pass"}




diff --git a/src/alembic.ini.sample b/src/alembic.ini.sample
new file mode 100644
index 0000000000000000000000000000000000000000..36bc1c10fb6e1243d320912cffd3f25dec9be77c
--- /dev/null
+++ b/src/alembic.ini.sample
@@ -0,0 +1,85 @@
+# A generic, single database configuration.
+
+[alembic]
+# path to migration scripts
+script_location = alembic
+
+# template used to generate migration files
+# file_template = %%(rev)s_%%(slug)s
+
+# timezone to use when rendering the date
+# within the migration file as well as the filename.
+# string value is passed to dateutil.tz.gettz()
+# leave blank for localtime
+# timezone =
+
+# max length of characters to apply to the
+# "slug" field
+# truncate_slug_length = 40
+
+# set to 'true' to run the environment during
+# the 'revision' command, regardless of autogenerate
+# revision_environment = false
+
+# set to 'true' to allow .pyc and .pyo files without
+# a source .py file to be detected as revisions in the
+# versions/ directory
+# sourceless = false
+
+# version location specification; this defaults
+# to alembic/versions.  When using multiple version
+# directories, initial revisions must be specified with --version-path
+# version_locations = %(here)s/bar %(here)s/bat alembic/versions
+
+# the output encoding used when revision files
+# are written from script.py.mako
+# output_encoding = utf-8
+
+sqlalchemy.url = mysql://<username>:<password>@localhost/ciclos_dev
+
+
+[post_write_hooks]
+# post_write_hooks defines scripts or Python functions that are run
+# on newly generated revision scripts.  See the documentation for further
+# detail and examples
+
+# format using "black" - use the console_scripts runner, against the "black" entrypoint
+# hooks=black
+# black.type=console_scripts
+# black.entrypoint=black
+# black.options=-l 79
+
+# Logging configuration
+[loggers]
+keys = root,sqlalchemy,alembic
+
+[handlers]
+keys = console
+
+[formatters]
+keys = generic
+
+[logger_root]
+level = WARN
+handlers = console
+qualname =
+
+[logger_sqlalchemy]
+level = WARN
+handlers =
+qualname = sqlalchemy.engine
+
+[logger_alembic]
+level = INFO
+handlers =
+qualname = alembic
+
+[handler_console]
+class = StreamHandler
+args = (sys.stderr,)
+level = NOTSET
+formatter = generic
+
+[formatter_generic]
+format = %(levelname)-5.5s [%(name)s] %(message)s
+datefmt = %H:%M:%S




diff --git a/src/blueprints/auth.py b/src/blueprints/auth.py
new file mode 100644
index 0000000000000000000000000000000000000000..66327d4ff1a44976d6c4389fa590827174e19f24
--- /dev/null
+++ b/src/blueprints/auth.py
@@ -0,0 +1,13 @@
+from flask import Blueprint, render_template, jsonify
+from ..types.user import User
+
+auth = Blueprint('auth', __name__, url_prefix = "/auth")
+
+@auth.route('/')
+def index():
+    us = User.query.all()
+    users = []
+    for usr in us:
+        users.append(usr.as_dict())
+
+    return jsonify(users)




diff --git a/src/types/__init__.py b/src/types/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0b13d6f2a9e2ae530f20551b37f3fe890ed8823
--- /dev/null
+++ b/src/types/__init__.py
@@ -0,0 +1,3 @@
+from flask_sqlalchemy import SQLAlchemy
+
+db = SQLAlchemy()




diff --git a/src/types/user.py b/src/types/user.py
new file mode 100644
index 0000000000000000000000000000000000000000..67b6198629dd331d79b169de4da8a89fc34dba2d
--- /dev/null
+++ b/src/types/user.py
@@ -0,0 +1,13 @@
+from . import db
+
+class User(db.Model):
+    __tablename__ = "users"
+    id = db.Column(db.Integer, primary_key = True)
+    username = db.Column(db.String(80), unique = True, nullable = False)
+    email = db.Column(db.String(120), unique = True, nullable = False)
+
+    def as_dict(self):
+        return {c.name: getattr(self, c.name) for c in self.__table__.columns}
+
+    def __repr__(self):
+        return "User <id: {}:>".format(self.id)