Skip to content

Commit

Permalink
Merge pull request #391 from MESH-Research/cassie-branch
Browse files Browse the repository at this point in the history
beginning of flask work and token fix
  • Loading branch information
cassandralem-msu authored Jan 18, 2024
2 parents 35ee48a + 704d40f commit b94437d
Show file tree
Hide file tree
Showing 19 changed files with 1,537 additions and 3 deletions.
932 changes: 932 additions & 0 deletions scripts/stats-CLI/flask-stats/APIclient.py

Large diffs are not rendered by default.

Empty file.
39 changes: 39 additions & 0 deletions scripts/stats-CLI/flask-stats/flaskr-stats/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import os

from flask import Flask

def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
"""
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
"""

# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, World!'

# from . import db
# db.init_app(app)

from . import stats
app.register_blueprint(stats.bp)

return app
20 changes: 20 additions & 0 deletions scripts/stats-CLI/flask-stats/flaskr-stats/stats.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import functools
import subprocess
import stats_CLI

from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)

bp = Blueprint('stats', __name__, url_prefix='/')

@bp.route('/')
def stats():
# send command line request to get total no. of deposits
get_no_deposits = subprocess.Popen(["total_deposits", "--json-output"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,)
stdout_gnd, stderr_gnd = get_no_deposits.communicate()

# return render_template('/stats.html')
39 changes: 39 additions & 0 deletions scripts/stats-CLI/flask-stats/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
[project]
name = "flaskr-stats"
version = "1.0.0"
description = "The basic blog app built in the Flask tutorial."
readme = "README.rst"
license = {text = "BSD-3-Clause"}
maintainers = [{name = "Cassie Lem", email = "[email protected]"}]
dependencies = [
"flask",
]

[project.urls]
Documentation = "https://flask.palletsprojects.com/tutorial/"

[project.optional-dependencies]
test = ["pytest"]

[build-system]
requires = ["flit_core<4"]
build-backend = "flit_core.buildapi"

[tool.flit.module]
name = "flaskr-stats"

[tool.flit.sdist]
include = [
"tests/",
]

[tool.pytest.ini_options]
testpaths = ["tests"]
filterwarnings = ["error"]

[tool.coverage.run]
branch = true
source = ["flaskr", "tests"]

[tool.ruff]
src = ["src"]
213 changes: 213 additions & 0 deletions scripts/stats-CLI/flask-stats/stats_CLI.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
import click
import numpy as np
import json
from APIclient import APIclient
import os

token = os.environ['CLI_TOKEN']

@click.group()
def cli():
pass

@cli.command(name='total_deposits')
@click.argument('freq', default=None, required=False)
@click.option('--json-output/--no-json', default=False, required=False)
def request_total_deposits(freq, json_output):
client = APIclient(token)
no_deposits = client.total_deposits(freq)
if json_output:
if freq == None:
click.echo(json.dumps({"Total number of deposits": no_deposits}))
else:
json_str = json.dumps({"Total deposits " + freq: no_deposits})
click.echo(json_str)
else:
if freq == None:
click.echo(f"Total number of deposits: {no_deposits}!")
else:
click.echo(f"Total number of deposits {freq}:")
for key in no_deposits:
click.echo(f"{key}: {no_deposits[key]}")


@cli.command(name='num_views')
@click.argument('id', default='all')
@click.argument('version', default='current', required=False) # options: current or all
@click.argument('start_date', default=None, required=False) # if a freq option is specified, can only have start
# and end dates within the same calendar year
@click.argument('end_date', default=None, required=False)
@click.argument('freq', default=None, required=False) # options: monthly, weekly, daily
@click.option('--unique/--not-unique', default=False, required=False)
@click.option('--json-output/--no-json', default=False, required=False)
def request_num_views(id, version, start_date, end_date, freq, unique, json_output):
client = APIclient(token)
no_views = client.total_views(id, version, start_date, end_date, freq, unique)
if id.lower() == 'all':
if json_output:
click.echo(json.dumps({"Total number of " + ("unique" if unique else "") + " views by deposit "
+ ("(current versions)" if version.lower() == "current" else "(all versions)"): no_views}))
else:
click.echo("Total number of " + ("unique " if unique else "") + "views of "
+ ("current version" if version.lower() == "current" else "all versions") + " of each deposit:")
for key in no_views:
click.echo(f"Deposit {key}: {no_views[key]}")
else:
if json_output:
if start_date is None and end_date is None:
click.echo(json.dumps({"Total number of " + ("unique " if unique else "") + "views of deposit "
+ id + (" (current version)" if version.lower() == "current" else " (all versions)"): no_views}))
elif freq != None:
click.echo(json.dumps({"Numbers of " + ("unique " if unique else "") + freq + " views of deposit "
+ id + (" (current version)" if version.lower() == "current" else " (all versions)")
+ " from " + start_date + " to " + end_date: no_views}))
else:
click.echo(json.dumps({"Total number of " + ("unique " if unique else "") + "views of deposit "
+ id + (" (current version)" if version.lower() == "current" else " (all versions)")
+ " from " + start_date + " to " + end_date: no_views}))
else:
if start_date is None and end_date is None:
click.echo("Total number of " + ("unique " if unique else "") + f"views of deposit {id} " +
("(current version): " if version.lower() == "current" else "(all versions): ") + f"{no_views}!")
elif freq != None:
click.echo("Numbers of " + ("unique " if unique else "") + freq + f" views of deposit {id} " +
("(current version)" if version.lower() == "current" else "(all versions)") + " from "
+ start_date + " to " + end_date + ":")
for key in no_views:
click.echo(str(key) + ": " + str(no_views[key]))
else:
click.echo("Total number of " + ("unique " if unique else "") + f"views of deposit {id} " +
("(current version)" if version.lower() == "current" else "(all versions)") + " from "
+ start_date + " to " + end_date + f": {no_views}!")


@cli.command(name='avg_views')
@click.argument('version', default='current')
@click.argument('start_date', default=None, required=False)
@click.argument('end_date', default=None, required=False)
@click.argument('freq', default=None, required=False)
@click.option('--unique/--not-unique', default=False)
@click.option('--json-output/--no-json', default=False, required=False)
def request_avg_views(version, start_date, end_date, freq, unique, json_output):
client = APIclient(token)
avg = client.avg_views(version, start_date, end_date, freq, unique)
if freq is None:
if json_output:
click.echo(json.dumps({"Average number of " + ("unique " if unique else "") + "views per deposit, taken from "
+ ("current version" if version == "current" else "all versions")
+ (" over " + start_date + " to " + end_date if start_date != None and end_date != None else ""): avg}))
else:
click.echo("Average number of " + ("unique " if unique else "") + "views per deposit, taken from "
+ ("current versions" if version == "current" else "all versions")
+ (" over " + start_date + " to " + end_date if start_date != None and end_date != None else "") + f": {avg}")

elif freq != None and start_date != None and end_date != None:
if json_output:
click.echo(json.dumps({"Average " + freq + ("unique " if unique else "") + "views per deposit, taken from "
+ ("current versions" if version.lower() == "current" else "all versions")
+ " over " + start_date + " to " + end_date: avg}))
else:
click.echo("Average " + freq + " numbers of " + ("unique " if unique else "") + "views per deposit, taken from "
+ ("current versions" if version.lower() == "current" else "all versions") + " over "
+ start_date + " to " + end_date + ":")
for key in avg:
click.echo(str(key) + ": " + str(avg[key]))


@cli.command(name='num_downloads')
@click.argument('id', default='all')
@click.argument('version', default='current', required=False)
@click.argument('start_date', default=None, required=False)
@click.argument('end_date', default=None, required=False)
@click.argument('freq', default=None, required=False) # options: monthly, weekly, daily
@click.option('--unique/--not-unique', default=False, required=False)
@click.option('--json-output/--no-json', default=False, required=False)
def request_num_downloads(id, version, start_date, end_date, freq, unique, json_output):
client = APIclient(token)
no_downloads = client.total_downloads(id, version, start_date, end_date, freq, unique)
if id.lower() == 'all':
if json_output:
click.echo(json.dumps({"Total number of " + ("unique" if unique else "") + " downloads by deposit "
+ ("(current versions)" if version.lower() == "current" else "(all versions)"): no_downloads}))
else:
click.echo("Total number of " + ("unique " if unique else "") + "downloads of "
+ ("current version" if version.lower() == "current" else "all versions") + " of each deposit:")
for key in no_downloads:
click.echo(f"Deposit {key}: {no_downloads[key]}")
else:
if json_output:
if start_date is None and end_date is None:
click.echo(json.dumps({"Total number of " + ("unique " if unique else "") + "downloads of deposit "
+ id + (" (current version)" if version.lower() == "current" else " (all versions)"): no_downloads}))
elif freq != None:
click.echo(json.dumps({"Numbers of " + ("unique " if unique else "") + freq + " downloads of deposit "
+ id + (" (current version)" if version.lower() == "current" else " (all versions)")
+ " from " + start_date + " to " + end_date: no_downloads}))
else:
click.echo(json.dumps({"Total number of " + ("unique " if unique else "") + "downloads of deposit "
+ id + (" (current version)" if version.lower() == "current" else " (all versions)")
+ " from " + start_date + " to " + end_date: no_downloads}))
else:
if start_date is None and end_date is None:
click.echo("Total number of " + ("unique " if unique else "") + f"downloads of deposit {id} " +
("(current version): " if version.lower() == "current" else "(all versions): ") + f"{no_downloads}!")
elif freq != None:
click.echo("Numbers of " + ("unique " if unique else "") + freq + f" downloads of deposit {id} " +
("(current version)" if version.lower() == "current" else "(all versions)") + " from "
+ start_date + " to " + end_date + ":")
for key in no_downloads:
click.echo(str(key) + ": " + str(no_downloads[key]))
else:
click.echo("Total number of " + ("unique " if unique else "") + f"downloads of deposit {id} " +
("(current version)" if version.lower() == "current" else "(all versions)") + " from "
+ start_date + " to " + end_date + f": {no_downloads}!")


@cli.command(name='avg_downloads')
@click.argument('version', default='current')
@click.argument('start_date', default=None, required=False)
@click.argument('end_date', default=None, required=False)
@click.argument('freq', default=None, required=False)
@click.option('--unique/--not-unique', default=False)
@click.option('--json-output/--no-json', default=False, required=False)
def request_avg_downloads(version, start_date, end_date, freq, unique, json_output):
client = APIclient(token)
avg = client.avg_downloads(version, start_date, end_date, freq, unique)
if freq is None:
if json_output:
click.echo(json.dumps({"Average number of " + ("unique " if unique else "") + "downloads per deposit, taken from "
+ ("current version" if version == "current" else "all versions")
+ (" over " + start_date + " to " + end_date if start_date != None and end_date != None else ""): avg}))
else:
click.echo("Average number of " + ("unique " if unique else "") + "downloads per deposit, taken from "
+ ("current versions" if version == "current" else "all versions")
+ (" over " + start_date + " to " + end_date if start_date != None and end_date != None else "") + f": {avg}")

elif freq != None and start_date != None and end_date != None:
if json_output:
click.echo(json.dumps({"Average " + freq + ("unique " if unique else "") + "downloads per deposit, taken from "
+ ("current versions" if version.lower() == "current" else "all versions")
+ " over " + start_date + " to " + end_date: avg}))
else:
click.echo("Average " + freq + " numbers of " + ("unique " if unique else "") + "downloads per deposit, taken from "
+ ("current versions" if version.lower() == "current" else "all versions") + " over "
+ start_date + " to " + end_date + ":")
for key in avg:
click.echo(str(key) + ": " + str(avg[key]))


@cli.command(name='top_downloads')
@click.argument('num', default=3)
def request_top_downloads(num):
client = APIclient(token)
sorted_downloads = client.top_downloads()
click.echo(f"Top {num} deposits by number of downloads:")
index = -1
for i in range(0, num):
key = list(sorted_downloads)[index]
click.echo(f"Deposit {key}: {sorted_downloads[key]} downloads")
index += 1


if __name__ == '__main__':
cli()
Empty file.
7 changes: 7 additions & 0 deletions scripts/stats-CLI/flask-tutorial/flask_tutorial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
38 changes: 38 additions & 0 deletions scripts/stats-CLI/flask-tutorial/flaskr/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import os

from flask import Flask


def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)

if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)

# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass

# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, World!'

from . import db
db.init_app(app)

from . import auth
app.register_blueprint(auth.bp)

return app
Loading

0 comments on commit b94437d

Please sign in to comment.