-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.py
More file actions
4156 lines (3665 loc) · 151 KB
/
controller.py
File metadata and controls
4156 lines (3665 loc) · 151 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Physics Derivation Graph
# Ben Payne, 2026
# https://allofphysics.com
# Creative Commons Attribution 4.0 International License
# https://creativecommons.org/licenses/by/4.0/
"""
# convention: every function and class includes a [trace] print
# reason: to help the developer understand functional dependencies and which state the program is in,
# a "trace" is printed to the terminal at the start of each function
# convention: every call to an external module is wrapped in a try/except, with the error message (err) sent to both logger and flash
# reason: any errors returned must be handled otherwise Flask errors and the website crashes
# convention: every call to flash must be either a string or the content must be wrapped in str()
# reason: when content is passed to flash() that cannot be serialized, the Flask error and the website crashes
# convention: every "raise Exception" should be proceeded by a corresponding "logger.error()"
# convention: the conditional "POST" operations should happen before the "GET" operations
# reason: sometimes the "POST" operation changes the data and the page content needs to be updated
# https://runnable.com/docker/python/docker-compose-with-flask-apps
# from redis import Redis
# https://pypi.org/project/rejson/
# from rejson import Client, Path
"""
import os
import sys
import json
import shutil
import time
import random
import copy
# https://docs.python.org/3/library/typing.html
# inspired by https://news.ycombinator.com/item?id=33844117
from typing import NewType, Dict, List
# https://docs.python.org/3/library/sqlite3.html
import sqlite3
# https://docs.python.org/3/howto/logging.html
import logging
# https://gist.github.com/ibeex/3257877
from logging.handlers import RotatingFileHandler
# https://hplgit.github.io/web4sciapps/doc/pub/._web4sa_flask004.html
from flask import (
Flask,
redirect,
render_template,
request,
url_for,
send_from_directory,
flash,
jsonify,
Response,
)
# https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web-forms
# https://nickjanetakis.com/blog/fix-missing-csrf-token-issues-with-flask
from flask_wtf import FlaskForm, CSRFProtect, Form # type: ignore
# https://github.com/TypeError/secure
import secure # type: ignore
# what feature gets added? See https://improveandrepeat.com/2020/10/python-friday-43-add-security-headers-to-your-flask-application/
# https://flask-login.readthedocs.io/en/latest/_modules/flask_login/mixins.html
# https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins
# https://en.wikipedia.org/wiki/Mixin
from flask_login import (
LoginManager,
UserMixin,
login_required,
login_user,
logout_user,
current_user,
) # type: ignore
# https://stackoverflow.com/a/56993644/1164295
from gunicorn import glogging # type: ignore
# https://gist.github.com/lost-theory/4521102
from flask import g
from werkzeug.utils import secure_filename
# removed "Form" from wtforms; see https://stackoverflow.com/a/20577177/1164295
from wtforms import StringField, validators, FieldList, FormField, IntegerField, RadioField, PasswordField, SubmitField, BooleanField # type: ignore
# sign in with Google
# https://developers.google.com/identity/sign-in/web/backend-auth
# https://github.com/allofphysicsgraph/proofofconcept/issues/119
# from google.oauth2 import id_token # type: ignore
# from google.auth.transport import requests # type: ignore
# https://json-schema.org/
from jsonschema import validate # type: ignore
from config import (
Config,
) # https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web-forms
from urllib.parse import urlparse, urljoin
# in support of Google Sign-in
# from https://realpython.com/flask-google-login/
from sql_db import init_db
from user import User
from oauthlib.oauth2 import WebApplicationClient # type: ignore
import requests
# https://realpython.com/flask-google-login/
GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID", None)
GOOGLE_CLIENT_SECRET = os.environ.get("GOOGLE_CLIENT_SECRET", None)
GOOGLE_DISCOVERY_URL = "https://accounts.google.com/.well-known/openid-configuration"
import common_lib as clib # PDG common library
import json_schema # PDG
import compute # PDG
import validate_steps_sympy as vir # PDG
import validate_dimensions_sympy as vdim # PDG
# global proc_timeout
proc_timeout = 30
path_to_db = "pdg.db"
# the following is done once upon program load
clib.json_to_sql("data.json", path_to_db)
# https://flask-login.readthedocs.io/en/latest/#flask_login.LoginManager.user_loader
login_manager = LoginManager()
# https://nickjanetakis.com/blog/fix-missing-csrf-token-issues-with-flask
csrf = CSRFProtect()
# https://secure.readthedocs.io/en/latest/frameworks.html#flask
secure_headers = secure.Secure()
app = Flask(__name__, static_folder="static")
app.config.from_object(
Config
) # https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web-forms
app.config[
"UPLOAD_FOLDER"
] = "/home/appuser/app/uploads" # https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/
app.config[
"SEND_FILE_MAX_AGE_DEFAULT"
] = 0 # https://stackoverflow.com/questions/34066804/disabling-caching-in-flask
app.config["DEBUG"] = True
# https://stackoverflow.com/a/24226084/1164295
app.config["GOOGLE_LOGIN_REDIRECT_SCHEME"] = "https"
# https://flask.palletsprojects.com/en/1.1.x/tutorial/views/
import pdg_api
app.register_blueprint(pdg_api.bp)
# https://flask-login.readthedocs.io/en/latest/#flask_login.LoginManager.user_loader
login_manager.init_app(app)
# https://nickjanetakis.com/blog/fix-missing-csrf-token-issues-with-flask
csrf.init_app(app)
# https://realpython.com/flask-google-login/
# OAuth 2 client setup
client = WebApplicationClient(GOOGLE_CLIENT_ID)
# import pdg_api # PDG API
# https://runnable.com/docker/python/docker-compose-with-flask-apps
# rd = Redis(host='db', port=6379)
# clib.connect_redis()
# https://pypi.org/project/rejson/
# rj = Client(host='db', port=6379, decode_responses=True)
# if __name__ == "__main__":
if True:
# called from flask
# print("called from flask")
# maxBytes=10000 = 10kB
# maxBytes=100000 = 100kB
# maxBytes=1000000 = 1MB
# maxBytes=10000000 = 10MB
log_size = 10000000
# maxBytes=100000000 = 100MB
# https://gist.github.com/ibeex/3257877
handler_debug = RotatingFileHandler(
"logs/flask_critical_and_error_and_warning_and_info_and_debug.log",
maxBytes=log_size,
backupCount=2,
)
handler_debug.setLevel(logging.DEBUG)
handler_info = RotatingFileHandler(
"logs/flask_critical_and_error_and_warning_and_info.log",
maxBytes=log_size,
backupCount=2,
)
handler_info.setLevel(logging.INFO)
handler_warning = RotatingFileHandler(
"logs/flask_critical_and_error_and_warning.log",
maxBytes=log_size,
backupCount=2,
)
handler_warning.setLevel(logging.WARNING)
# https://docs.python.org/3/howto/logging.html
logging.basicConfig(
# either (filename + filemode) XOR handlers
# filename="test.log", # to save entries to file instead of displaying to stderr
# filemode="w", # https://docs.python.org/dev/library/functions.html#filemodes
handlers=[handler_debug, handler_info, handler_warning],
# if the severity level is INFO,
# the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages
# and will ignore DEBUG messages
level=logging.DEBUG,
format="%(asctime)s|%(filename)-13s|%(levelname)-5s|%(lineno)-4d|%(funcName)-20s|%(message)s" # ,
# https://stackoverflow.com/questions/6290739/python-logging-use-milliseconds-in-time-format/7517430#7517430
# datefmt="%m/%d/%Y %I:%M:%S %f %p", # https://strftime.org/
)
# logger = logging.getLogger(__name__)
# https://docs.python.org/3/howto/logging.html
# if the severity level is INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages and will ignore DEBUG messages
# handler.setLevel(logging.INFO)
# handler.setLevel(logging.DEBUG)
logger = logging.getLogger(__name__)
# http://matplotlib.1069221.n5.nabble.com/How-to-turn-off-matplotlib-DEBUG-msgs-td48822.html
# https://github.com/matplotlib/matplotlib/issues/14523
logging.getLogger("matplotlib").setLevel(logging.WARNING)
# logger.addHandler(handler)
# https://stackoverflow.com/questions/41087790/how-to-override-gunicorns-logging-config-to-use-a-custom-formatter
# https://medium.com/@trstringer/logging-flask-and-gunicorn-the-manageable-way-2e6f0b8beb2f
if __name__ != "__main__":
# else:
print("called from gunicorn")
# from https://stackoverflow.com/a/56993644/1164295
# didn't make a difference
# glogging.Logger.error_fmt = '{"AppName": "%(name)s", "logLevel": "%(levelname)s", "Timestamp": "%(created)f", "Class_Name":"%(module)s", "Method_name": "%(funcName)s", "process_id":%(process)d, "message": "%(message)s"}'
# glogging.Logger.datefmt = ""
# glogging.Logger.access_fmt = '{"AppName": "%(name)s", "logLevel": "%(levelname)s", "Timestamp": "%(created)f","Class_Name":"%(module)s", "Method_name": "%(funcName)s", "process_id":%(process)d, "message": "%(message)s"}'
# glogging.Logger.syslog_fmt = '{"AppName": "%(name)s", "logLevel": "%(levelname)s", "Timestamp": "%(created)f","Class_Name":"%(module)s", "Method_name": "%(funcName)s", "process_id":%(process)d, "message": "%(message)s"}'
gunicorn_logger = logging.getLogger("gunicorn.error")
logger.handlers.extend(
gunicorn_logger.handlers
) # https://stackoverflow.com/a/37595908/1164295
# app.logger.handlers = gunicorn_logger.handlers # works but doesn't display PDG logs
# logger.setLevel(gunicorn_logger.level)
# logger = app.logger
# https://wtforms.readthedocs.io/en/stable/crash_course.html
# https://stackoverflow.com/questions/46092054/flask-login-documentation-loginform
# class LoginForm(FlaskForm):
# logger.info("[trace]")
# username = StringField("Username", validators=[validators.DataRequired()])
# password = PasswordField("Password", validators=[validators.DataRequired()])
# submit = SubmitField("sign in")
# # https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web-forms
# remember_me = BooleanField("remember me")
# https://pythonprogramming.net/flask-user-registration-form-tutorial/
# class RegistrationForm(FlaskForm):
# logger.info("[trace]")
# username = StringField("Username", [validators.Length(min=3, max=20)])
# email = StringField("Email Address", [validators.Length(min=4, max=50)])
# password = PasswordField(
# "New Password",
# [
# validators.Required(),
# validators.EqualTo("confirm", message="Passwords must match"),
# ],
# )
# confirm = PasswordField("Repeat Password")
# https://flask-login.readthedocs.io/en/latest/_modules/flask_login/mixins.html
# class User(UserMixin):
# """
# inherits from UserMixin which is defined here
# https://flask-login.readthedocs.io/en/latest/_modules/flask_login/mixins.html#UserMixin
# in order to support required features; see
# https://flask-login.readthedocs.io/en/latest/#your-user-class
#
# https://realpython.com/using-flask-login-for-user-management-with-flask/
# and
# https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database
# """
#
#
# logger.info("[trace]")
#
# def __init__(self, name, id, active=True):
# self.name = name
# self.id = id
# self.active = active
# def is_active(self):
# return self.active
# def __init__(self, user_name, pass_word):
# self.username = user_name
# self.password = pass_word
# def is_authenticated(self):
# return self.authenticated
# def __repr__(self):
# return "<User {}>".format(self.username)
# the following is a hack not meant for publication
# https://gist.github.com/bkdinoop/6698956
# which is linked from
# https://stackoverflow.com/a/12081788/1164295
# USERS = {
# 1: User(u"bp", 1),
# 2: User(u"mg", 2),
# 3: User(u"tl", 3, False),
# }
# USER_NAMES = dict((u.name, u) for u in USERS.values())
class EquationInputForm(FlaskForm):
logger.info("[trace]")
# r = FloatField(validators=[validators.InputRequired()])
# r = FloatField()
latex = StringField(
"LaTeX", validators=[validators.InputRequired(), validators.Length(max=1000)]
)
class NewSymbolForm(FlaskForm):
logger.info("[trace]")
symbol_category = RadioField(
"category",
choices=[
("variable", "variable"),
("constant", "constant"),
],
default="variable",
)
# https://en.wikipedia.org/wiki/List_of_types_of_numbers
# symbol_scope_real = BooleanField(
# label="Real", description="check this", default="checked"
# )
symbol_scope = RadioField(
"scope",
choices=[("real", "real"), ("complex", "complex"), ("integer", "integer")],
default="real",
validators=[validators.InputRequired()],
)
# symbol_scope_complex = BooleanField(label="Complex", description="check this")
# symbol_scope_integer = BooleanField(label="Integer", description="check this")
# domain = input; range = output
symbol_radio_domain = RadioField(
"domain",
choices=[
("any", "any"),
("positive", "positive"),
("negative", "negative"),
("nonnegative", "non-negative"),
],
default="any",
validators=[validators.InputRequired()],
)
symbol_latex = StringField("latex", validators=[validators.InputRequired()])
symbol_name = StringField("name", validators=[validators.InputRequired()])
symbol_reference = StringField("reference")
symbol_value = StringField("value")
symbol_units = StringField("units")
class InferenceRuleForm(FlaskForm):
logger.info("[trace]")
inf_rule_name = StringField(
"inf rule name",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
num_inputs = IntegerField(
"number of inputs",
validators=[validators.InputRequired(), validators.NumberRange(min=0, max=5)],
)
num_feeds = IntegerField(
"number of feeds",
validators=[validators.InputRequired(), validators.NumberRange(min=0, max=5)],
)
num_outputs = IntegerField(
"number of outputs",
validators=[validators.InputRequired(), validators.NumberRange(min=0, max=5)],
)
latex = StringField("LaTeX", validators=[validators.InputRequired()])
notes = StringField("notes")
class RevisedTextForm(FlaskForm):
logger.info("[trace]")
revised_text = StringField(
"revised text",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
class infRuleInputsAndOutputs(FlaskForm):
logger.info("[trace]")
"""
a form with one or more latex entries
source: https://stackoverflow.com/questions/28375565/add-input-fields-dynamically-with-wtforms
https://stackoverflow.com/questions/30121763/how-to-use-a-wtforms-fieldlist-of-formfields
https://gist.github.com/doobeh/5d0f965502b86fee80fe
https://www.rmedgar.com/blog/dynamic_fields_flask_wtf
docs: https://wtforms.readthedocs.io/en/latest/fields.html#field-enclosures
https://wtforms.readthedocs.io/en/latest/fields.html#wtforms.fields.FieldList
https://wtforms.readthedocs.io/en/latest/fields.html#wtforms.fields.FormField
"""
inputs_and_outputs = FieldList(
FormField(EquationInputForm, "late_x"), min_entries=1
)
# inputs_and_outputs = FieldList(EquationInputForm, min_entries=1)
# https://stackoverflow.com/questions/37837682/python-class-input-argument/37837766
# https://wtforms.readthedocs.io/en/stable/validators.html
class LatexIO(FlaskForm):
logger.info("[trace]")
static_feed1 = StringField(
"feed LaTeX 1",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
static_feed2 = StringField(
"feed LaTeX 2",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
static_feed3 = StringField(
"feed LaTeX 3",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
static_feed4 = StringField(
"feed LaTeX 4",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
static_feed5 = StringField(
"feed LaTeX 5",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
static_feed6 = StringField(
"feed LaTeX 6",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
static_feed7 = StringField(
"feed LaTeX 7",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
static_feed8 = StringField(
"feed LaTeX 8",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
static_feed9 = StringField(
"feed LaTeX 9",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
static_feed10 = StringField(
"feed LaTeX 10",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
static_feed11 = StringField(
"feed LaTeX 11",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
static_feed12 = StringField(
"feed LaTeX ",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
static_feed13 = StringField(
"feed LaTeX 13",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
input1 = StringField("input LaTeX 1", validators=[validators.Length(max=1000)])
input1_name = StringField("input name 1", validators=[validators.Length(max=1000)])
input1_note = StringField("input note 1", validators=[validators.Length(max=1000)])
input1_radio = RadioField(
"Label",
choices=[
("latex", "use Latex"),
("local", "use local ID"),
("global", "use global ID"),
],
default="latex",
) # , validators=[validators.InputRequired()])
input2 = StringField("input LaTeX 2", validators=[validators.Length(max=1000)])
input2_name = StringField("input name 2", validators=[validators.Length(max=1000)])
input2_note = StringField("input note 2", validators=[validators.Length(max=1000)])
input2_radio = RadioField(
"Label",
choices=[
("latex", "use Latex"),
("local", "use local ID"),
("global", "use global ID"),
],
default="latex",
) # , validators=[validators.InputRequired()])
input3 = StringField("input LaTeX 3", validators=[validators.Length(max=1000)])
input3_name = StringField("input name 3", validators=[validators.Length(max=1000)])
input3_note = StringField("input note 3", validators=[validators.Length(max=1000)])
input3_radio = RadioField(
"Label",
choices=[
("latex", "use Latex"),
("local", "use local ID"),
("global", "use global ID"),
],
default="latex",
) # , validators=[validators.InputRequired()])
input4 = StringField("input LaTeX 4", validators=[validators.Length(max=1000)])
input4_name = StringField("input name 4", validators=[validators.Length(max=1000)])
input4_note = StringField("input note 4", validators=[validators.Length(max=1000)])
input4_radio = RadioField(
"Label",
choices=[
("latex", "use Latex"),
("local", "use local ID"),
("global", "use global ID"),
],
default="latex",
) # , validators=[validators.InputRequired()])
input5 = StringField("input LaTeX 5", validators=[validators.Length(max=1000)])
input5_name = StringField("input name 5", validators=[validators.Length(max=1000)])
input5_note = StringField("input note 5", validators=[validators.Length(max=1000)])
input5_radio = RadioField(
"Label",
choices=[
("latex", "use Latex"),
("local", "use local ID"),
("global", "use global ID"),
],
default="latex",
) # , validators=[validators.InputRequired()])
input6 = StringField("input LaTeX 6", validators=[validators.Length(max=1000)])
input6_name = StringField("input name 6", validators=[validators.Length(max=1000)])
input6_note = StringField("input note 6", validators=[validators.Length(max=1000)])
input6_radio = RadioField(
"Label",
choices=[
("latex", "use Latex"),
("local", "use local ID"),
("global", "use global ID"),
],
default="latex",
) # , validators=[validators.InputRequired()])
input7 = StringField("input LaTeX 7", validators=[validators.Length(max=1000)])
input7_name = StringField("input name 7", validators=[validators.Length(max=1000)])
input7_note = StringField("input note 7", validators=[validators.Length(max=1000)])
input7_radio = RadioField(
"Label",
choices=[
("latex", "use Latex"),
("local", "use local ID"),
("global", "use global ID"),
],
default="latex",
) # , validators=[validators.InputRequired()])
output1 = StringField("output LaTeX 1", validators=[validators.Length(max=1000)])
output1_name = StringField(
"output name 1", validators=[validators.Length(max=1000)]
)
output1_note = StringField(
"output note 1", validators=[validators.Length(max=1000)]
)
output1_radio = RadioField(
"Label",
choices=[
("latex", "use Latex"),
("local", "use local ID"),
("global", "use global ID"),
],
default="latex",
)
output2 = StringField("output LaTeX 2", validators=[validators.Length(max=1000)])
output2_name = StringField(
"output name 2", validators=[validators.Length(max=1000)]
)
output2_note = StringField(
"output note 2", validators=[validators.Length(max=1000)]
)
output2_radio = RadioField(
"Label",
choices=[
("latex", "use Latex"),
("local", "use local ID"),
("global", "use global ID"),
],
default="latex",
) # , validators=[validators.InputRequired()])
output3 = StringField("output LaTeX 3", validators=[validators.Length(max=1000)])
output3_name = StringField(
"output name 3", validators=[validators.Length(max=1000)]
)
output3_note = StringField(
"output note 3", validators=[validators.Length(max=1000)]
)
output3_radio = RadioField(
"Label",
choices=[
("latex", "use Latex"),
("local", "use local ID"),
("global", "use global ID"),
],
default="latex",
) # , validators=[validators.InputRequired()])
step_note = StringField("step note")
class SymbolEntry(FlaskForm):
logger.info("[trace]")
symbol_radio = RadioField(
"Label",
choices=[
("opt 1", "opt 1"),
("opt 2", "opt 2"),
("opt 3", "opt 3"),
("opt 4", "opt 4"),
("opt 5", "opt 5"),
("opt 6", "opt 6"),
("opt 7", "opt 7"),
("opt 8", "opt 8"),
("opt 9", "opt 9"),
("opt 10", "opt 10"),
("opt 11", "opt 11"),
("use_existing", "use existing"),
("create_new", "create new"),
],
default="already_exists",
)
class NameOfDerivationInputForm(FlaskForm):
logger.info("[trace]")
name_of_derivation = StringField(
"name of derivation",
validators=[validators.InputRequired(), validators.Length(max=1000)],
)
notes = StringField("notes")
@app.after_request
def set_secure_headers(response):
"""
https://github.com/allofphysicsgraph/proofofconcept/issues/157
https://secure.readthedocs.io/en/latest/frameworks.html#flask
"""
# logger.info("[trace]")
secure_headers.framework.flask(response)
#secure_headers.flask(response)
# logger.debug(str(response))
return response
# goal is to prevent cached responses;
# see https://stackoverflow.com/questions/47376744/how-to-prevent-cached-response-flask-server-using-chrome
# The following doesn't work; instead use "F12 > Network > Disable cache"
# @app.after_request
# def add_header(r):
# """
# Add headers to both force latest IE rendering engine or Chrome Frame,
# and also to cache the rendered page for 10 minutes.
# """
# logger.info('[trace] add_header')
# r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
# r.headers["Pragma"] = "no-cache"
# r.headers["Expires"] = "0"
# r.headers['Cache-Control'] = 'public, max-age=0'
# return r
@app.errorhandler(404)
def page_not_found(er):
"""
https://flask.palletsprojects.com/en/1.1.x/patterns/errorpages/
404 = page not found
"""
logger.info("[trace] page_not_found")
logger.debug(er)
logger.debug(
"request.url: " + str(request.url)
) # https://stackoverflow.com/a/46176337/1164295
flash("error 404" + str(er))
return redirect(url_for("index"))
# @app.errorhandler(500)
# def server_error():
# """Internal server error.
# TODO: for error=500, send an email to the site administrator
# """
@app.before_request
def before_request():
"""
Note: this function need to be before almost all other functions
tutorial: https://pythonise.com/series/learning-flask/python-before-after-request
https://stackoverflow.com/questions/12273889/calculate-execution-time-for-every-page-in-pythons-flask
actually, https://gist.github.com/lost-theory/4521102
>>> before_request():
"""
g.start = time.time()
g.request_start_time = time.time()
elapsed_time = lambda: "%.5f seconds" % (time.time() - g.request_start_time)
# logger.debug("created elapsed_time function")
g.request_time = elapsed_time
return
@app.after_request
def after_request(response):
"""
https://stackoverflow.com/questions/12273889/calculate-execution-time-for-every-page-in-pythons-flask
I don't know how to access this measure
>>> after_request()
"""
try:
diff = time.time() - g.start
except AttributeError as err:
flash("after_request:" + str(err))
# logger.error(str(err))
diff = 0
if (
(response.response)
and (200 <= response.status_code < 300)
and (response.content_type.startswith("text/html"))
):
response.set_data(
response.get_data().replace(
b"__EXECUTION_TIME__", bytes(str(diff), "utf-8")
)
)
# logger.debug("response = " + str(response))
return response
def get_google_provider_cfg():
"""
https://realpython.com/flask-google-login/
"""
logger.info("[trace]")
url_json = requests.get(GOOGLE_DISCOVERY_URL).json()
logger.debug(url_json)
return url_json
@login_manager.unauthorized_handler
def unauthorized():
"""
https://flask-login.readthedocs.io/en/latest/
>>>
"""
logger.info("[trace]")
return redirect(url_for("login", referrer="unauthorized"))
@login_manager.user_loader
def load_user(user_id):
"""
https://flask-login.readthedocs.io/en/latest/
also https://realpython.com/using-flask-login-for-user-management-with-flask/
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins
"""
logger.info("[trace]")
logger.debug(user_id)
# return USERS.get(int(user_id))
# https://realpython.com/flask-google-login/
return User.get(user_id)
# def is_safe_url(target):
# """
# https://github.com/fengsp/flask-snippets/blob/master/security/redirect_back.py
# """
# logger.info("[trace]")
# ref_url = urlparse(request.host_url)
# test_url = urlparse(urljoin(request.host_url, target))
# return test_url.scheme in ("http", "https") and ref_url.netloc == test_url.netloc
@app.route("/login")
def login():
"""
https://realpython.com/flask-google-login/
"""
logger.info("[trace]")
if "db" not in g:
logger.debug("db not in g")
init_db()
else:
logger.debug("db is in g")
# Find out what URL to hit for Google login
google_provider_cfg = get_google_provider_cfg()
authorization_endpoint = google_provider_cfg["authorization_endpoint"]
# Use library to construct the request for Google login and provide
# scopes that let you retrieve user's profile from Google
request_uri = client.prepare_request_uri(
authorization_endpoint,
redirect_uri=request.base_url + "/callback",
scope=["openid", "email", "profile"],
)
return redirect(request_uri)
@app.route("/login/callback")
def callback():
"""
https://realpython.com/flask-google-login/
"""
trace_id = str(random.randint(1000000, 9999999))
logger.info("[trace page start " + trace_id + "]")
# Get authorization code Google sent back to you
code = request.args.get("code")
# Find out what URL to hit to get tokens that allow you to ask for
# things on behalf of a user
google_provider_cfg = get_google_provider_cfg()
token_endpoint = google_provider_cfg["token_endpoint"]
# Prepare and send a request to get tokens
token_url, headers, body = client.prepare_token_request(
token_endpoint,
authorization_response=request.url,
redirect_url=request.base_url,
code=code,
)
token_response = requests.post(
token_url,
headers=headers,
data=body,
auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
)
# Parse the tokens
client.parse_request_body_response(json.dumps(token_response.json()))
# Now that you have tokens (yay) let's find and hit the URL
# from Google that gives you the user's profile information,
# including their Google profile image and email
userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
uri, headers, body = client.add_token(userinfo_endpoint)
userinfo_response = requests.get(uri, headers=headers, data=body)
# You want to make sure their email is verified.
# The user authenticated with Google, authorized your
# app, and now you've verified their email through Google!
if userinfo_response.json().get("email_verified"):
unique_id = userinfo_response.json()["sub"]
users_email = userinfo_response.json()["email"]
picture = userinfo_response.json()["picture"]
users_name = userinfo_response.json()["given_name"]
else:
return "User email not available or not verified by Google.", 400
logger.debug(users_name)
logger.debug(users_email)
# Create a user in your db with the information provided
# by Google
user = User(id_=unique_id, name=users_name, email=users_email, profile_pic=picture)
# Doesn't exist? Add it to the database.
if not User.get(unique_id):
logger.debug(users_name + " does not appear in database; creating it")
User.create(unique_id, users_name, users_email, picture)
logger.debug("created user in database")
# Begin user session by logging the user in
login_user(user)
# logger.debug(str(current_user))
logger.debug(str(current_user.name))
logger.debug(str(current_user.email))
flash("logged in")
# Send user back to homepage
logger.info("[trace page end " + trace_id + "]")
return redirect(url_for("navigation", referrer="login"))
# @app.route("/login_OLD", methods=["GET", "POST"])
# def login_OLD():
# """
# https://github.com/allofphysicsgraph/proofofconcept/issues/110
#
# from https://flask-login.readthedocs.io/en/latest/
# and https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins
#
# Here we use a class of some kind to represent and validate our
# client-side form data. For example, WTForms is a library that will
# handle this for us, and we use a custom LoginForm to validate.
# """
# form = LoginForm()
#
# logger.debug(str(request.form))
#
# # request.referrer = "http://localhost:5000/login"
#
# if form.validate_on_submit():
# # Login and validate the user.
# # user should be an instance of your `User` class
#
# # the following is what the person entered into the form
# logger.debug("username= %s", form.username.data)
# # user = User()
# # if user is None: # or not user.check_password(form.password.data):
# username = form.username.data
#
# # logger.debug('next =' + str(request.args.get("next")))
#
# # https://stackoverflow.com/a/28593313/1164295
# # logger.debug(request.headers.get("Referer")) = "http://localhost:5000/login"
#
# # https://gist.github.com/bkdinoop/6698956
# if username in USER_NAMES:
# remember = request.form.get("remember", "no") == "yes"
# if login_user(USER_NAMES[username], remember=remember):
# flash("logged in")
# current_user.username = username
# return redirect(url_for("navigation", referrer="login"))
# else:
# flash("Invalid password; sleeping for 3 seconds")
# time.sleep(3)
# logger.debug("invalid password")
# return redirect(url_for("login", referrer="login"))
# else:
# flash("invalid username; sleeping for 3 seconds")
# time.sleep(3)
# logger.debug("invalid username")
# return redirect(url_for("create_new_account", referrer="login"))
# # https://flask-login.readthedocs.io/en/latest/#flask_login.login_user
# # login_user(user, remember=form.remember_me.data)
# # logger.debug("user logged in")
# # flash("Logged in successfully.")
#
# # next = request.args.get("next")
# # is_safe_url should check if the url is safe for redirects.
# # See http://flask.pocoo.org/snippets/62/ for an example.
# # if not is_safe_url(next):
# # return abort(400)
#
# logger.error("Should not reach this condition")
#
# return redirect(url_for("index", referrer="login"))
#
# # intentionally delay the responsiveness of the login page to limit brute force attacks
# time.sleep(2)
# return render_template("login.html", webform=form, title="Login")
@app.route("/logout", methods=["GET", "POST"])
@login_required
def logout():
"""
https://flask-login.readthedocs.io/en/latest/#login-example
>>>