Skip to content

Commit

Permalink
Formatting.
Browse files Browse the repository at this point in the history
  • Loading branch information
toddbirchard committed Oct 23, 2020
1 parent f54c58a commit 70feaba
Show file tree
Hide file tree
Showing 14 changed files with 295 additions and 146 deletions.
32 changes: 16 additions & 16 deletions config.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
"""Flask app configuration."""
from os import environ, path

from dotenv import load_dotenv

basedir = path.abspath(path.dirname(__file__))
load_dotenv(path.join(basedir, '.env'))
load_dotenv(path.join(basedir, ".env"))


class Config:
"""Global configuration variables."""

# General Config
SECRET_KEY = environ.get('SECRET_KEY')
FLASK_APP = environ.get('FLASK_APP')
FLASK_ENV = environ.get('FLASK_ENV')
SECRET_KEY = environ.get("SECRET_KEY")
FLASK_APP = environ.get("FLASK_APP")
FLASK_ENV = environ.get("FLASK_ENV")

# Database
SQLALCHEMY_DATABASE_URI = environ.get('SQLALCHEMY_DATABASE_URI')
SQLALCHEMY_DATABASE_URI = environ.get("SQLALCHEMY_DATABASE_URI")
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_HOST = 'hackers-data-do-user-1142484-0.db.ondigitalocean.com'
SQLALCHEMY_DATABASE_TABLE = 'commands'
SQLALCHEMY_DATABASE_NAME = environ.get('SQLALCHEMY_DATABASE_NAME')
SQLALCHEMY_CONNECT_ARGS = {'ssl': {'ca': './creds/ca-certificate.crt'}}
SQLALCHEMY_DATABASE_HOST = "hackers-data-do-user-1142484-0.db.ondigitalocean.com"
SQLALCHEMY_DATABASE_TABLE = "commands"
SQLALCHEMY_DATABASE_NAME = environ.get("SQLALCHEMY_DATABASE_NAME")
SQLALCHEMY_CONNECT_ARGS = {"ssl": {"ca": "./creds/ca-certificate.crt"}}

# Flask-Assets
LESS_BIN = environ.get('LESS_BIN')
ASSETS_DEBUG = environ.get('ASSETS_DEBUG')
LESS_RUN_IN_DEBUG = environ.get('LESS_RUN_IN_DEBUG')
LESS_BIN = environ.get("LESS_BIN")
ASSETS_DEBUG = environ.get("ASSETS_DEBUG")
LESS_RUN_IN_DEBUG = environ.get("LESS_RUN_IN_DEBUG")

# Static Assets
STATIC_FOLDER = 'static'
TEMPLATES_FOLDER = 'templates'
COMPRESSOR_DEBUG = environ.get('COMPRESSOR_DEBUG')

STATIC_FOLDER = "static"
TEMPLATES_FOLDER = "templates"
COMPRESSOR_DEBUG = environ.get("COMPRESSOR_DEBUG")
4 changes: 2 additions & 2 deletions deploy.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

if [ -d ".venv" ]
then
source .venv/bin/activate
. .venv/bin/activate
pip install -r requirements.txt
python3 wsgi.py
else
python3 -m venv .venv
source .venv/bin/activate
. .venv/bin/activate
python3 -m pip install --upgrade pip
pip install -r requirements.txt
python3 wsgi.py
Expand Down
164 changes: 163 additions & 1 deletion poetry.lock

Large diffs are not rendered by default.

12 changes: 7 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,15 @@ Pytest = "*"
Lesscpy = "*"
Cssmin = "*"
Jsmin = "*"

[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
black = "^20.8b1"
isort = "^5.6.4"

[tool.poetry.scripts]
run = "wsgi:app"

[tool.poetry.urls]
issues = "https://github.com/toddbirchard/pythonmyadmin/issues"
issues = "https://github.com/toddbirchard/pythonmyadmin/issues"

[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
5 changes: 4 additions & 1 deletion pythonmyadmin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
def create_app():
"""Construct the core application."""
app = Flask(__name__, instance_relative_config=False)
app.config.from_object('config.Config')
app.config.from_object("config.Config")
db.init_app(app)

with app.app_context():
Expand All @@ -17,14 +17,17 @@ def create_app():

# Construct the data set
from . import routes

app.register_blueprint(routes.main_bp)

# Compile assets
from .assets import compile_assets

compile_assets(app)

# Dash view
from table import tableview

app = tableview.create_dash_view(app)

return app
22 changes: 9 additions & 13 deletions pythonmyadmin/assets.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""Build static assets."""
from flask_assets import Environment, Bundle
from flask_assets import Bundle, Environment


def compile_assets(app):
Expand All @@ -8,18 +8,14 @@ def compile_assets(app):
Environment.auto_build = True
Environment.debug = False
less_bundle = Bundle(
'less/main.less',
filters='less,cssmin',
output='dist/css/style.css',
extra={'rel': 'stylesheet/less'}
"less/main.less",
filters="less,cssmin",
output="dist/css/style.css",
extra={"rel": "stylesheet/less"},
)
js_bundle = Bundle(
'js/*.js',
filters='jsmin',
output='dist/js/main.js'
)
assets.register('less_all', less_bundle)
assets.register('js_all', js_bundle)
if app.config['FLASK_ENV'] != 'production':
js_bundle = Bundle("js/*.js", filters="jsmin", output="dist/js/main.js")
assets.register("less_all", less_bundle)
assets.register("js_all", js_bundle)
if app.config["FLASK_ENV"] != "production":
less_bundle.build(force=True)
js_bundle.build()
42 changes: 14 additions & 28 deletions pythonmyadmin/forms.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,32 @@
"""Form classes."""
from wtforms import (
Form,
StringField,
PasswordField,
SubmitField,
SelectField
)
from wtforms import Form, PasswordField, SelectField, StringField, SubmitField
from wtforms.validators import DataRequired, Length, Optional


class DatabaseForm(Form):
"""Database connection Form."""

flavor = SelectField(
'Database Flavor',
validators=[DataRequired(message='Select a type of database.')],
choices=['MySQL', 'Postgres', 'SQLLite']
)
host = StringField(
'Email',
validators=[DataRequired(message='Enter a hostname.')]
"Database Flavor",
validators=[DataRequired(message="Select a type of database.")],
choices=["MySQL", "Postgres", "SQLLite"],
)
host = StringField("Email", validators=[DataRequired(message="Enter a hostname.")])
port = StringField(
'Port',
"Port",
validators=[
DataRequired(message='Enter a port.'),
Length(min=4, message='Enter a valid port.')]
DataRequired(message="Enter a port."),
Length(min=4, message="Enter a valid port."),
],
)
user = StringField(
'Username',
validators=[Length(min=6, message='Enter a valid email address.')]
"Username", validators=[Length(min=6, message="Enter a valid email address.")]
)
password = PasswordField(
'DB Password',
validators=[DataRequired(message='Enter a password.')]
"DB Password", validators=[DataRequired(message="Enter a password.")]
)
database = StringField(
'Website',
validators=[DataRequired(message='Enter a database name.')]
)
schema = StringField(
'Schema',
validators=[Optional()]
"Website", validators=[DataRequired(message="Enter a database name.")]
)
submit = SubmitField('Connect')
schema = StringField("Schema", validators=[Optional()])
submit = SubmitField("Connect")
9 changes: 5 additions & 4 deletions pythonmyadmin/models.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
"""Data models."""
from . import db
from flask import current_app as app

from . import db


class Command(db.Model):
"""Chatbot command table."""

__tablename__ = app.config['SQLALCHEMY_DATABASE_TABLE']
__table_args__ = {'extend_existing': True}
__tablename__ = app.config["SQLALCHEMY_DATABASE_TABLE"]
__table_args__ = {"extend_existing": True}

# Columns
id = db.Column(db.Integer, primary_key=True)
Expand All @@ -17,4 +18,4 @@ class Command(db.Model):
created_at = db.Column(db.DateTime)

def __repr__(self):
return '<Command {}>'.format(self.__tablename__)
return "<Command {}>".format(self.__tablename__)
53 changes: 26 additions & 27 deletions pythonmyadmin/routes.py
Original file line number Diff line number Diff line change
@@ -1,61 +1,60 @@
"""Core route declaration."""
from flask import Blueprint, render_template
from flask import Blueprint
from flask import current_app as app
from . import db
from flask import render_template

from . import db

# Create Blueprint
main_bp = Blueprint(
'main_bp', __name__,
template_folder='templates',
static_folder='static'
"main_bp", __name__, template_folder="templates", static_folder="static"
)


@main_bp.route('/')
@main_bp.route("/")
def home():
"""Database Table Selection Page."""
tables = db.engine.table_names()
host = app.config['SQLALCHEMY_DATABASE_HOST']
db_name = app.config['SQLALCHEMY_DATABASE_NAME']
host = app.config["SQLALCHEMY_DATABASE_HOST"]
db_name = app.config["SQLALCHEMY_DATABASE_NAME"]
return render_template(
'index.html',
"index.html",
tables=tables,
title='Database Tables.',
template='home-template',
title="Database Tables.",
template="home-template",
host_name=host,
table_summary=f'Displaying {len(tables)} tables found in database {db_name}:'
table_summary=f"Displaying {len(tables)} tables found in database {db_name}:",
)


@main_bp.route('/database')
@main_bp.route("/database")
def database():
"""Database Configuration Page."""
return render_template(
'index.html',
title='Connect a Database',
template='database-template',
body="This is an example homepage, served with Flask."
"index.html",
title="Connect a Database",
template="database-template",
body="This is an example homepage, served with Flask.",
)


@main_bp.route('/users')
@main_bp.route("/users")
def users():
"""Users Page."""
return render_template(
'index.html',
title='Users',
template='users-template',
body="This is an example homepage, served with Flask."
"index.html",
title="Users",
template="users-template",
body="This is an example homepage, served with Flask.",
)


@main_bp.route('/settings')
@main_bp.route("/settings")
def settings():
"""Settings Page."""
return render_template(
'index.html',
title='Settings',
template='settings-template',
body="This is an example homepage, served with Flask."
"index.html",
title="Settings",
template="settings-template",
body="This is an example homepage, served with Flask.",
)
4 changes: 2 additions & 2 deletions table/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def update_output(n_clicks, value):
)'''


'''@dash_app.callback(
"""@dash_app.callback(
Output('callback-container', 'children'),
[Input('database-table', 'row_update'),
Input('database-table', 'rows')]
Expand All @@ -68,4 +68,4 @@ def update_database(row_update, rows):
html.Code('rows'),
html.Pre(json.dumps(rows, indent=2))
], className='six columns'),
])'''
])"""
27 changes: 13 additions & 14 deletions table/data.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"""Fetch a database table."""
import pandas as pd
from sqlalchemy.types import Text, String
from sqlalchemy import create_engine
from sqlalchemy.types import String, Text

from config import Config

# Database connection engine
engine = create_engine(
Config.SQLALCHEMY_DATABASE_URI,
connect_args=Config.SQLALCHEMY_CONNECT_ARGS
Config.SQLALCHEMY_DATABASE_URI, connect_args=Config.SQLALCHEMY_CONNECT_ARGS
)


Expand All @@ -16,17 +16,19 @@ def get_table_data():
table_df = pd.read_sql_table(
Config.SQLALCHEMY_DATABASE_TABLE,
con=engine,
index_col='id',
parse_dates='created_at'
index_col="id",
parse_dates="created_at",
)
table_df.sort_values('created_at', ascending=False, inplace=True)
table_df['created_at'] = table_df['created_at'].dt.strftime('%m/%d/%Y')
table_df.sort_values("created_at", ascending=False, inplace=True)
table_df["created_at"] = table_df["created_at"].dt.strftime("%m/%d/%Y")
return table_df


def column_dist_chart(table_df: pd.DataFrame, column):
"""Aggregate column values"""
grouped_column = table_df.groupby(column).count().sort_values(column, ascending=False)
grouped_column = (
table_df.groupby(column).count().sort_values(column, ascending=False)
)
return grouped_column


Expand All @@ -35,12 +37,9 @@ def upload_dataframe(df: pd.DataFrame):
df.to_sql(
Config.SQLALCHEMY_DATABASE_TABLE,
engine,
if_exists='append',
if_exists="append",
index=True,
dtype={
"command": String(255),
"response": Text
}
dtype={"command": String(255), "response": Text},
)
response = f'Successfully uploaded {str(df.count)} rows.'
response = f"Successfully uploaded {str(df.count)} rows."
return response
Loading

0 comments on commit 70feaba

Please sign in to comment.