-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
214 lines (166 loc) · 5.8 KB
/
app.py
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
from flask import Flask, Response
from flask_migrate import Migrate
from flask.logging import default_handler
import logging
from logging.handlers import RotatingFileHandler
from click import echo
import sqlalchemy as sa
import views
import settings
from routes import *
from models import db, \
Weather, \
Policy, \
Event, \
Farm, \
Role, \
User
from flask_admin import Admin, AdminIndexView
from flask_admin.contrib.sqla import ModelView
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.exceptions import HTTPException
app = Flask(__name__)
app.secret_key = settings.secret_key
app.config.from_object(settings.configClass)
auth = HTTPBasicAuth()
users = {
settings.admin_user: generate_password_hash(settings.admin_pwd)
}
db.init_app(app)
migrate = Migrate(app, db)
# ------------------------------------------------------
# UTILITY FUNCTIONS TO SUPPORT DEPLOYMENT ON RENDER
# ------------------------------------------------------
def check_db_init():
"""Check if the database needs to be initialized"""
engine = sa.create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
inspector = sa.inspect(engine)
if not inspector.has_table("user"):
with app.app_context():
db.drop_all()
db.create_all()
app.logger.info('Initialized the database!')
else:
app.logger.info('Database already contains the users table.')
def configure_logging():
"""Logging Configuration"""
if app.config['LOG_WITH_GUNICORN']:
gunicorn_error_logger = logging.getLogger('gunicorn.error')
app.logger.handlers.extend(gunicorn_error_logger.handlers)
app.logger.setLevel(logging.DEBUG)
else:
file_handler = RotatingFileHandler('instance/bima.log',
maxBytes=16384,
backupCount=20)
file_formatter = logging.Formatter(
'%(asctime)s %(levelname)s %(threadName)s-%(thread)d: %(message)s [in %(filename)s:%(lineno)d]')
file_handler.setFormatter(file_formatter)
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
# Remove the default logger configured by Flask
app.logger.removeHandler(default_handler)
app.logger.info('Starting the Bima Insurance app...')
def register_cli_commands(app):
@app.cli.command('init_db')
def initialize_database():
"""Initialize the database."""
db.drop_all()
db.create_all()
echo('Initialized the database!')
# ------------------------------------------------------
# ADMIN Portal Views
# ------------------------------------------------------
@auth.verify_password
def verify_password(username, password):
""" Verify admin username and password for the admin page """
if username in users and \
check_password_hash(users.get(username), password):
return username
login_required_view = auth.login_required(lambda: None)
def is_authenticated():
"""Secure admin routes"""
try:
return login_required_view() is None
except HTTPException:
return False
class AuthException(HTTPException):
def __init__(self, message):
super().__init__(message, Response(
"You could not be authenticated.", 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'}))
# class MyModelView(ModelView):
# def is_accessible(self):
# if not is_authenticated():
# raise AuthException('Not authenticated.')
# else:
# return True
class MyAdminIndexView(AdminIndexView):
def is_accessible(self):
if not is_authenticated():
raise AuthException('Not authenticated.')
else:
return True
class PolicyView(ModelView):
column_hide_backrefs = False
# inline_models = (Event,)
can_export = True
column_list = ('name',
'description',
'start_date',
'end_date',
'premium',
'coverage_amount',
'strike_event'
)
class EventView(ModelView):
column_hide_backrefs = False
form_choices = {
'temperature_condition': [
('>', 'Greater Than'),
('<', 'Less Than'),
('=', 'Equal To'),
],
'humidity_condition': [
('>', 'Greater Than'),
('<', 'Less Than'),
('=', 'Equal To'),
],
'soil_moisture_condition': [
('>', 'Greater Than'),
('<', 'Less Than'),
('=', 'Equal To'),
]
}
class UserView(ModelView):
column_hide_backrefs = False
column_list = (
"wallet_address",
"farms",
"roles"
)
class FarmView(ModelView):
column_hide_backrefs = False
class RoleView(ModelView):
column_hide_backrefs = True
admin = Admin(app, name='Bima Admin', template_mode=settings.template_mode, index_view=MyAdminIndexView())
admin.add_view(UserView(model=User, session=db.session))
admin.add_view(RoleView(model=Role, session=db.session))
admin.add_view(FarmView(model=Farm, session=db.session))
admin.add_view(PolicyView(model=Policy, session=db.session))
admin.add_view(EventView(model=Event, session=db.session))
@app.shell_context_processor
def make_shell_context():
return dict(db=db, Weather=Weather)
# ------------------------------------------------------
# FARMER Portal Views
# ------------------------------------------------------
appauth.login_manager.init_app(app)
app.register_blueprint(views.main_bp)
app.register_blueprint(appauth.auth_bp)
app.register_blueprint(data.data_bp)
app.register_blueprint(testing.testing_bp)
configure_logging()
check_db_init()
if __name__ == "__main__":
app.run()