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

Update backend deps #83

Open
wants to merge 2 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
8 changes: 5 additions & 3 deletions backend/admin/admin.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
from flask_admin import Admin
from .mongoview import MyAdminIndexView
from .mongoview import MyAdminIndexView, MyModelView

# from database.db import db, session
# from database.models import User, Snippet, Collection, TokenBlocklist

admin = Admin(
name="Cheat-Hub Backend",
index_view=MyAdminIndexView(),
endpoint="admin",
url="/admin",
template_mode="bootstrap4",
template_mode="bootstrap3",
)


Expand All @@ -23,5 +25,5 @@ def initialize_admin(app):
The admin object that is created by the init_app function

"""
admin.init_app(app)
app.config["FLASK_ADMIN_SWATCH"] = "cerulean"
admin.init_app(app)
8 changes: 7 additions & 1 deletion backend/admin/basicauth.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import os
from flask_basicauth import BasicAuth

if not os.path.exists("env.py"):
pass
else:
import env

basic_auth = BasicAuth()


Expand All @@ -15,6 +20,7 @@ def initialize_basicauth(app):
Returns:
The app and the user name and password
"""
basic_auth.init_app(app)
app.config["BASIC_AUTH_USERNAME"] = os.environ.get("BASIC_AUTH_USERNAME")
app.config["BASIC_AUTH_PASSWORD"] = os.environ.get("BASIC_AUTH_PASSWORD")
app.config["BASIC_AUTH_REALM"] = os.environ.get("BASIC_AUTH_REALM")
basic_auth.init_app(app)
164 changes: 164 additions & 0 deletions backend/admin/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
import logging
from pymongo import monitoring


log = logging.getLogger()
log.setLevel(logging.DEBUG)
logging.basicConfig(level=logging.DEBUG)


class CommandLogger(monitoring.CommandListener):
def started(self, event):
logging.info(
"Command {0.command_name} with request id "
"{0.request_id} started on server "
"{0.connection_id}".format(event)
)

def succeeded(self, event):
logging.info(
"Command {0.command_name} with request id "
"{0.request_id} on server {0.connection_id} "
"succeeded in {0.duration_micros} "
"microseconds".format(event)
)

def failed(self, event):
logging.info(
"Command {0.command_name} with request id "
"{0.request_id} on server {0.connection_id} "
"failed in {0.duration_micros} "
"microseconds".format(event)
)


class ServerLogger(monitoring.ServerListener):
def opened(self, event):
logging.info(
"Server {0.server_address} added to topology "
"{0.topology_id}".format(event)
)

def description_changed(self, event):
previous_server_type = event.previous_description.server_type
new_server_type = event.new_description.server_type
if new_server_type != previous_server_type:
# server_type_name was added in PyMongo 3.4
logging.info(
"Server {0.server_address} changed type from "
"{0.previous_description.server_type_name} to "
"{0.new_description.server_type_name}".format(event)
)

def closed(self, event):
logging.warning(
"Server {0.server_address} removed from topology "
"{0.topology_id}".format(event)
)


class HeartbeatLogger(monitoring.ServerHeartbeatListener):
def started(self, event):
logging.info("Heartbeat sent to server " "{0.connection_id}".format(event))

def succeeded(self, event):
# The reply.document attribute was added in PyMongo 3.4.
logging.info(
"Heartbeat to server {0.connection_id} "
"succeeded with reply "
"{0.reply.document}".format(event)
)

def failed(self, event):
logging.warning(
"Heartbeat to server {0.connection_id} "
"failed with error {0.reply}".format(event)
)


class TopologyLogger(monitoring.TopologyListener):
def opened(self, event):
logging.info("Topology with id {0.topology_id} " "opened".format(event))

def description_changed(self, event):
logging.info(
"Topology description updated for "
"topology id {0.topology_id}".format(event)
)
previous_topology_type = event.previous_description.topology_type
new_topology_type = event.new_description.topology_type
if new_topology_type != previous_topology_type:
# topology_type_name was added in PyMongo 3.4
logging.info(
"Topology {0.topology_id} changed type from "
"{0.previous_description.topology_type_name} to "
"{0.new_description.topology_type_name}".format(event)
)
# The has_writable_server and has_readable_server methods
# were added in PyMongo 3.4.
if not event.new_description.has_writable_server():
logging.warning("No writable servers available.")
if not event.new_description.has_readable_server():
logging.warning("No readable servers available.")

def closed(self, event):
logging.info("Topology with id {0.topology_id} " "closed".format(event))


class ConnectionPoolLogger(monitoring.ConnectionPoolListener):
def pool_created(self, event):
logging.info("[pool {0.address}] pool created".format(event))

def pool_cleared(self, event):
logging.info("[pool {0.address}] pool cleared".format(event))

def pool_closed(self, event):
logging.info("[pool {0.address}] pool closed".format(event))

def connection_created(self, event):
logging.info(
"[pool {0.address}][conn #{0.connection_id}] "
"connection created".format(event)
)

def connection_ready(self, event):
logging.info(
"[pool {0.address}][conn #{0.connection_id}] "
"connection setup succeeded".format(event)
)

def connection_closed(self, event):
logging.info(
"[pool {0.address}][conn #{0.connection_id}] "
"connection closed, reason: "
"{0.reason}".format(event)
)

def connection_check_out_started(self, event):
logging.info("[pool {0.address}] connection check out " "started".format(event))

def connection_check_out_failed(self, event):
logging.info(
"[pool {0.address}] connection check out "
"failed, reason: {0.reason}".format(event)
)

def connection_checked_out(self, event):
logging.info(
"[pool {0.address}][conn #{0.connection_id}] "
"connection checked out of pool".format(event)
)

def connection_checked_in(self, event):
logging.info(
"[pool {0.address}][conn #{0.connection_id}] "
"connection checked into pool".format(event)
)


def initialize_logger():
monitoring.register(CommandLogger())
monitoring.register(ServerLogger())
monitoring.register(HeartbeatLogger())
monitoring.register(TopologyLogger())
monitoring.register(ConnectionPoolLogger())
2 changes: 1 addition & 1 deletion backend/admin/mail.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ def initialize_mail(app):
Returns:
A configured flask mail object
"""
mail.init_app(app)
app.config["MAIL_SERVER"] = os.environ.get("MAIL_SERVER")
app.config["MAIL_PORT"] = int(os.environ.get("MAIL_PORT"))
app.config["MAIL_USERNAME"] = os.environ.get("MAIL_USERNAME")
app.config["MAIL_PASSWORD"] = os.environ.get("MAIL_PASSWORD")
app.config["MAIL_DEFAULT_SENDER"] = os.environ.get("MAIL_DEFAULT_SENDER")
app.config["MAIL_USE_SSL"] = True
mail.init_app(app)

# MAIL_SERVER : default ‘localhost’
# MAIL_PORT : default 25
Expand Down
3 changes: 2 additions & 1 deletion backend/admin/mongoview.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from flask import Response, redirect
from flask import redirect, Response
from flask_admin import AdminIndexView, expose
from flask_admin.contrib.mongoengine.view import ModelView
from werkzeug.exceptions import HTTPException

from .basicauth import basic_auth

"""
Expand Down
21 changes: 21 additions & 0 deletions backend/admin/toolbar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from flask_debugtoolbar import DebugToolbarExtension

toolbar = DebugToolbarExtension()


def initialize_toolbar(app):
app.config["DEBUG_TB_PANELS"] = (
"flask_debugtoolbar.panels.versions.VersionDebugPanel",
"flask_debugtoolbar.panels.timer.TimerDebugPanel",
"flask_debugtoolbar.panels.headers.HeaderDebugPanel",
"flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel",
"flask_debugtoolbar.panels.config_vars.ConfigVarsDebugPanel",
"flask_debugtoolbar.panels.template.TemplateDebugPanel",
"flask_debugtoolbar.panels.logger.LoggingPanel",
"flask_debugtoolbar.panels.route_list.RouteListDebugPanel",
"flask_debugtoolbar.panels.profiler.ProfilerDebugPanel",
"flask_debugtoolbar.panels.g.GDebugPanel",
"flask_mongoengine.panels.MongoDebugPanel",
)
app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False
toolbar.init_app(app)
23 changes: 8 additions & 15 deletions backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from flask_jwt_extended import JWTManager
from flask_mail import Mail

from admin.basicauth import initialize_basicauth
from admin.admin import initialize_admin
from admin.mail import initialize_mail
from admin.views import initialize_views
from admin.toolbar import initialize_toolbar
from admin.logger import initialize_logger

from database.db import initialize_db
from flask_restful import Api
Expand All @@ -27,28 +29,19 @@
# Initializes app and packages by order of dependency requirements
# ===========================================================================

# Logger before app
initialize_logger()

app = Flask(__name__)

app.config["MAIL_SERVER"] = os.environ.get("MAIL_SERVER")
app.config["MAIL_PORT"] = int(os.environ.get("MAIL_PORT"))
app.config["MAIL_USERNAME"] = os.environ.get("MAIL_USERNAME")
app.config["MAIL_PASSWORD"] = os.environ.get("MAIL_PASSWORD")
app.config["MAIL_DEFAULT_SENDER"] = os.environ.get("MAIL_DEFAULT_SENDER")
app.config["MAIL_USE_TLS"] = True

mail = Mail(app)

# initialize_mail(app)
initialize_mail(app)
from resources.routes import initialize_routes

api = Api(app, errors=errors)
bcrypt = Bcrypt(app)
jwt = JWTManager(app)
CORS(app, supports_credentials=True)

app.config["MONGODB_HOST"] = os.environ.get("MONGODB_HOST")
app.config["MONGODB_PORT"] = int(os.environ.get("MONGODB_PORT"))
app.secret_key = os.environ.get("SECRET_KEY")
app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY")
app.config["DEBUG_TB_ENABLED"] = True
Expand All @@ -60,8 +53,8 @@

initialize_basicauth(app)
initialize_admin(app)
initialize_toolbar(app)
initialize_views()


if __name__ == "__main__":
app.run()
app.run(debug=True)
18 changes: 16 additions & 2 deletions backend/database/db.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import os
from flask_mongoengine import MongoEngine, MongoEngineSessionInterface
from flask_mongoengine.json import MongoEngineJSONEncoder


if not os.path.exists("env.py"):
pass
else:
import env


# ===========================================================================
# * Initialize Database
Expand All @@ -7,7 +16,6 @@
# Requires connection string, set in environment vars and Heroku settings.
# ===========================================================================

# Creating a MongoEngine object.
db = MongoEngine()


Expand All @@ -22,6 +30,12 @@ def initialize_db(app):
Returns:
A flask application object
"""
app.config["MONGODB_HOST"] = os.environ.get("MONGODB_HOST")
app.config["MONGODB_PORT"] = int(os.environ.get("MONGODB_PORT"))
app.config["MONGODB_DB"] = os.environ.get("MONGODB_DB")
app.config["MONGODB_USERNAME"] = os.environ.get("MONGODB_USERNAME")
app.config["MONGODB_PASSWORD"] = os.environ.get("MONGODB_PASSWORD")

app.session_interface = MongoEngineSessionInterface(db)
app.json_encoder = MongoEngineJSONEncoder
db.init_app(app)
app.session_interface = MongoEngineSessionInterface(db)
Loading