-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
server.py
181 lines (144 loc) · 6 KB
/
server.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
"""
Copyright (c) 2016-2022, Vanessa Sochat
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from expfactory.experiment import get_experiments, make_lookup, get_selection
from expfactory.database import *
from flask import Flask
from flask_wtf.csrf import CSRFProtect, generate_csrf
from expfactory.variables import generate_runtime_vars
from flask_cors import CORS
from expfactory.logger import bot
from expfactory.defaults import *
import random
import sys
import os
# SERVER CONFIGURATION #########################################################
class EFServer(Flask):
def __init__(self, *args, **kwargs):
super(EFServer, self).__init__(*args, **kwargs)
self.setup()
self.initdb()
def initdb(self):
"""initdb will check for writability of the data folder, meaning
that it is bound to the local machine. If the folder isn't bound,
expfactory runs in demo mode (not saving data)
"""
self.database = EXPFACTORY_DATABASE
bot.info("DATABASE: %s" % self.database)
# Supported database options
valid = ("sqlite", "postgres", "mysql", "filesystem")
if not self.database.startswith(valid):
bot.warning(
"%s is not yet a supported type, saving to filesystem." % self.database
)
self.database = "filesystem"
# Add functions specific to database type
self.init_db() # uses url in self.database
bot.log("Data base: %s" % self.database)
def setup(self):
"""obtain database and filesystem preferences from defaults,
and compare with selection in container.
"""
self.selection = EXPFACTORY_EXPERIMENTS
self.ordered = len(EXPFACTORY_EXPERIMENTS) > 0
self.data_base = EXPFACTORY_DATA
self.study_id = EXPFACTORY_SUBID
self.base = EXPFACTORY_BASE
self.randomize = EXPFACTORY_RANDOMIZE
self.headless = EXPFACTORY_HEADLESS
# Generate variables, if they exist
self.vars = generate_runtime_vars() or None
available = get_experiments("%s" % self.base)
self.experiments = get_selection(available, self.selection)
self.logger.debug(self.experiments)
self.lookup = make_lookup(self.experiments)
final = "\n".join(list(self.lookup.keys()))
bot.log("Headless mode: %s" % self.headless)
bot.log("User has selected: %s" % self.selection)
bot.log("Experiments Available: %s" % "\n".join(available))
bot.log("Randomize: %s" % self.randomize)
bot.log("Final Set \n%s" % final)
def get_next(self, session):
"""return the name of the next experiment, depending on the user's
choice to randomize. We don't remove any experiments here, that is
done on finish, in the case the user doesn't submit data (and
thus finish). A return of None means the user has completed the
battery of experiments.
"""
next = None
experiments = session.get("experiments", [])
if len(experiments) > 0:
if app.randomize is True:
next = random.choice(range(0, len(experiments)))
next = experiments[next]
else:
next = experiments[0]
return next
def finish_experiment(self, session, exp_id):
"""remove an experiment from the list after completion."""
self.logger.debug("Finishing %s" % exp_id)
experiments = session.get("experiments", [])
experiments = [x for x in experiments if x != exp_id]
session["experiments"] = experiments
return experiments
EFServer.init_db = init_db
EFServer.save_data = save_data
EFServer.generate_subid = generate_subid
EFServer.generate_user = generate_user
# Tokens
EFServer.validate_token = validate_token
EFServer.refresh_token = refresh_token
EFServer.revoke_token = revoke_token
# User Actions
EFServer.list_users = list_users
EFServer.print_user = print_user
EFServer.finish_user = finish_user
EFServer.restart_user = restart_user
app = EFServer(__name__)
app.config.from_object("expfactory.config")
# EXPERIMENTS #################################################################
# Cors
cors = CORS(
app,
origins="http://127.0.0.1",
allow_headers=[
"Content-Type",
"Authorization",
"X-Requested-With",
"Access-Control-Allow-Credentials",
],
supports_credentials=True,
)
app.config["CORS_HEADERS"] = "Content-Type"
# 3 hours. Set to None for life of session
time_limit = os.environ.get("EXPFACTORY_WTF_CSRF_TIME_LIMIT")
if time_limit:
try:
time_limit = int(time_limit)
except:
bot.warning(
"time_limit setting %s cannot be parsed, will use default" % time_limit
)
app.config["WTF_CSRF_TIME_LIMIT"] = time_limit or 10800
csrf = CSRFProtect(app)
import expfactory.views
import expfactory.api
# This is how the command line version will run
def start(port=5000, debug=False):
bot.info("Nobody ever comes in... nobody ever comes out...")
app.run(host="localhost", debug=debug, port=port)