-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwsgi.py
More file actions
234 lines (206 loc) · 6.35 KB
/
wsgi.py
File metadata and controls
234 lines (206 loc) · 6.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# flake8: noqa
from gevent import monkey
monkey.patch_all()
import json
import threading
from add_extensions import redis_2, redis_4
from core import create_app, socketio, db
from dotenv import load_dotenv
from models import *
from utils import (
get_class_by_tablename,
load_env,
fetch_instance_tag
)
from loguru import logger
from google.cloud import secretmanager
from google import auth
import click
import os
import shlex
import sys
import base64
import firebase_admin
load_dotenv()
logger.remove()
logger.add(sys.stderr, enqueue=False)
ENV = os.getenv('APP_ENV', 'DEV')
app = create_app(ENV.lower() if ENV else 'default')
cred = firebase_admin.credentials.Certificate(app.config['F_KEY_PATH'])
firebase_admin.initialize_app(cred)
# test config
COV = None
if app.config['FLASK_COVERAGE']:
import coverage
COV = coverage.Coverage(
branch=True,
source=[
'core/',
'models/',
'schemas/'
]
)
# COV.
COV.start()
# flask shell
@app.shell_context_processor
def make_shell_context():
return dict(
app=app,
role=Role,
user=User,
artisan=Artisan,
bk_cat=BookingCategory,
db=db
)
# flask cli commands
@app.cli.command()
def create_categories():
"""creates job categories in db"""
print("Creating categories::", end='\n')
BookingCategory.create_categories()
print("Done!")
# purge table
@app.cli.command()
@click.option(
'--table_name',
help="specify name of table to be deleted"
)
def purge(table_name):
"""removes all rows in specified table"""
model = get_class_by_tablename(table_name)
model.query.delete()
db.session.commit()
print("completed purge on table {}".format(table_name))
# create user roles
@app.cli.command()
def create_roles():
print(":: creating roles ::", end="\n")
user_models.Role.insert_roles()
print("completed !")
@app.cli.command()
@click.option(
'--role_name',
help="specify name of role to be updated"
)
@click.option(
'--perm_value',
help="specify value of permission to be added"
)
def update_role_permissions(role, perm):
print(f"To add permission with value {perm} to role {role}")
user_models.Role.updateRolePermissions(role, perm)
print("Completed operation!")
@app.cli.command()
@click.option(
'--coverage/--no-coverage', default=False,
help='Run tests under coverage'
)
def test(coverage):
""" Run the unit tests """
# if not coverage and not app.config['FLASK_COVERAGE']:
# app.config['FLASK_COVERAGE'] = True
# # os.execvp(sys.executable, [sys.executable] + sys.argv)
# return
import unittest
test = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(test)
if COV and coverage:
COV.stop()
COV.save()
print("Coverage Summary: ")
COV.report()
basedir = os.path.abspath(os.path.dirname(__file__))
print(basedir)
covdir = os.path.join(basedir, 'tmp/coverage')
COV.html_report(directory=covdir)
print('HTML version: file://%s/index.html' % covdir)
COV.erase()
@app.cli.command()
def load_config_variables():
"""fetches secrets from GCP secret manager and loads them into .env"""
def gen_pairs(obj):
val = base64.b64decode(obj['payload']['data']).decode('utf-8')
yield f"{shlex.quote(obj['name'].split('/')[-3])}={shlex.quote(val)}"
access_token = None
keys = load_env(gen_pairs)
if keys:
try:
with open('.env', 'w') as file:
for kv in keys:
file.write(kv)
file.write("\n")
print("Written config secrets to .env")
except Exception as e:
print("Something went wrong while writing to .env")
raise e
else:
raise Exception("Something went wrong while trying to fetch secrets")
def redis_dispatch_listener(socketio_instance):
"""
Listens for 'dispatch' messages from the Background Worker
and forwards them to specific SocketIO rooms.
"""
from utils import send_notification
from schemas import NewBookingRequestSchema
from core.api.bookings.utils import parse_str_data
pubsub = redis_2.pubsub()
pubsub.subscribe('socket_server_dispatch')
print("Redis Dispatch Listener Started...")
for message in pubsub.listen():
if message['type'] == 'message':
try:
payload = parse_str_data(message.pop('data'))
schema = NewBookingRequestSchema()
bk_data = payload.pop('data')
customer = bk_data.pop('user')
lat, lon = bk_data.pop('lat'), bk_data.pop('lon')
sid = redis_4.hget(
'user_to_sid',
payload['target_id']
)
data = schema.load(
{
**bk_data,
'userDetails': customer,
'coordinates': {
'lat': lat,
'lon': lon
}
}
)
socketio.emit(
'new_offer',
data,
to=sid,
namespace='/artisan'
)
notification_payload = {
k: json.dumps(v) for k, v in data.items()
}
fcm_token = redis_4.hget("user_to_fcm_token", payload['target_id'])
send_notification(
notification_payload,
fcm_token,
notification_object={
'body': 'A client near you needs your service',
'title': 'New Service Request Alert! 🚨'
}
)
except Exception as e:
logger.exception(e)
print(f"Dispatch Error: {e}")
if __name__ == "__main__":
if os.environ.get("WERKZEUG_RUN_MAIN") == "true" or not app.debug:
print("--> Starting Redis Dispatch Listener (Background)...")
threading.Thread(
target=redis_dispatch_listener,
args=(socketio,)
).start()
socketio.run(
app,
host="0.0.0.0",
port=5000,
debug=True,
use_reloader=True
)