Skip to content

Commit

Permalink
feat: web socket implmentation with flask-socketio
Browse files Browse the repository at this point in the history
Signed-off-by: Akiff Manji <amanji@petridish.dev>
  • Loading branch information
amanji committed Oct 25, 2023
1 parent 2e75d5f commit 79a2631
Show file tree
Hide file tree
Showing 7 changed files with 40 additions and 68 deletions.
5 changes: 4 additions & 1 deletion legal-api/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,10 @@ tag: push ## tag image
# COMMANDS - Local #
#################################################################################
run: ## Run the project in local
. venv/bin/activate && python -m flask run -p 5000
. venv/bin/activate && python -m flask run -p 5050

run-websockets: ## Run the project in local with websockets
. venv/bin/activate && python -m gunicorn --threads 100 --bind :5050 wsgi

#################################################################################
# Self Documenting Commands #
Expand Down
14 changes: 7 additions & 7 deletions legal-api/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,16 @@ Flask-Moment==0.11.0
Flask-Pydantic==0.8.0
Flask-SQLAlchemy==2.5.1
Flask-Script==2.0.6
Flask-SocketIO==5.3.6
Flask==1.1.2
Jinja2==2.11.3
Mako==1.1.4
MarkupSafe==1.1.1
PyPDF2==1.26.0
SQLAlchemy-Continuum==1.3.13
SQLAlchemy-Utils==0.37.8
SQLAlchemy==1.4.44
Werkzeug==1.0.1
nest_asyncio
alembic==1.7.5
aniso8601==9.0.1
asyncio-nats-client==0.11.4
Expand All @@ -31,11 +32,15 @@ ecdsa==0.14.1
expiringdict==1.1.4
flask-jwt-oidc==0.3.0
flask-restx==0.3.0
git+https://github.com/bcgov/business-schemas.git@2.18.10#egg=registry_schemas
gunicorn==20.1.0
html-sanitizer==1.9.3
idna==2.10
itsdangerous==1.1.0
jsonschema==4.19.0
launchdarkly-server-sdk==7.1.0
minio==7.0.2
nest_asyncio
protobuf==3.15.8
psycopg2-binary==2.8.6
pyRFC3339==1.1
Expand All @@ -48,16 +53,11 @@ python-dotenv==0.17.1
python-editor==1.0.4
python-jose==3.2.0
pytz==2021.1
reportlab==3.6.12
requests==2.25.1
rsa==4.7.2
semver==2.13.0
sentry-sdk==1.20.0
six==1.15.0
strict-rfc3339==0.7
urllib3==1.26.11
minio==7.0.2
PyPDF2==1.26.0
reportlab==3.6.12
html-sanitizer==1.9.3
git+https://github.com/bcgov/business-schemas.git@2.18.13#egg=registry_schemas

52 changes: 0 additions & 52 deletions legal-api/requirements.txt.1

This file was deleted.

3 changes: 3 additions & 0 deletions legal-api/src/legal_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from legal_api.utils.auth import jwt
from legal_api.utils.logging import setup_logging
from legal_api.utils.run_version import get_run_version
from legal_api.extensions import socketio
# noqa: I003; the sentry import creates a bad line count in isort

setup_logging(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'logging.conf')) # important to do this first
Expand Down Expand Up @@ -67,6 +68,8 @@ def create_app(run_mode=os.getenv('FLASK_ENV', 'production')):

register_shellcontext(app)

socketio.init_app(app, cors_allowed_origins='*')

return app


Expand Down
9 changes: 9 additions & 0 deletions legal-api/src/legal_api/extensions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from flask import current_app
from flask_socketio import SocketIO

socketio = SocketIO()


@socketio.on('connect')
def on_connect():
current_app.logger.debug(f"Socket connected to client")
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,18 @@
# limitations under the License.

"""API endpoints for managing an Digital Credentials resource."""
import json
from datetime import datetime
from http import HTTPStatus

from flask import Blueprint, current_app, jsonify, request
from flask_cors import cross_origin
from flask_socketio import emit

from legal_api.models import Business, DCConnection, DCDefinition, DCIssuedCredential
from legal_api.services import digital_credentials
from legal_api.utils.auth import jwt
from legal_api.extensions import socketio

from .bp import bp

Expand Down Expand Up @@ -60,23 +63,26 @@ def create_invitation(identifier):
)
connection.save()

return jsonify({'invitationUrl': connection.invitation_url}), HTTPStatus.OK
return jsonify(connection.json), HTTPStatus.OK


@bp.route('/<string:identifier>/digitalCredentials/connection', methods=['GET', 'OPTIONS'], strict_slashes=False)
@bp.route('/<string:identifier>/digitalCredentials/connections', methods=['GET', 'OPTIONS'], strict_slashes=False)
@cross_origin(origin='*')
@jwt.requires_auth
def get_active_connection(identifier):
def get_connections(identifier):
"""Get active connection for this business."""
business = Business.find_by_identifier(identifier)
if not business:
return jsonify({'message': f'{identifier} not found.'}), HTTPStatus.NOT_FOUND

connection = DCConnection.find_active_by(business_id=business.id)
if not connection:
return jsonify({'message': 'No active connection found.'}), HTTPStatus.NOT_FOUND
connections = DCConnection.find_by(business_id=business.id)
if len(connections) == 0:
return jsonify({'connections': []}), HTTPStatus.OK

return jsonify(connection.json), HTTPStatus.OK
response = []
for connection in connections:
response.append(connection.json)
return jsonify({'connections': response}), HTTPStatus.OK


@bp.route('/<string:identifier>/digitalCredentials', methods=['GET', 'OPTIONS'], strict_slashes=False)
Expand Down Expand Up @@ -210,12 +216,14 @@ def webhook_notification(topic_name: str):
connection.connection_state = json_input['state']
connection.is_active = True
connection.save()
socketio.emit('connections', connection.json)
elif topic_name == 'issue_credential_v2_0':
issued_credential = DCIssuedCredential.find_by_credential_exchange_id(json_input['cred_ex_id'])
if issued_credential and json_input['state'] in ('credential-issued', 'done'):
issued_credential.date_of_issue = datetime.utcnow()
issued_credential.is_issued = True
issued_credential.save()
socketio.emit('issue_credential_v2_0', issued_credential.json)
except Exception as err:
current_app.logger.error(err)
raise err
Expand Down
3 changes: 2 additions & 1 deletion legal-api/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@
import os

from legal_api import create_app
from legal_api.extensions import socketio

# Openshift s2i expects a lower case name of application
application = create_app() # pylint: disable=invalid-name

if __name__ == "__main__":
server_port = os.environ.get('PORT', '8080')
application.run(debug=False, port=server_port, host='0.0.0.0')
socketio.run(application, port=server_port, host='0.0.0.0')

0 comments on commit 79a2631

Please sign in to comment.