def subject_init(row): subject = Subject() num = Subject.query.filter_by(name=row['Nom']).count() if num > 0: Subject.query.delete() study = Study.query.filter_by(name=row['Etude']).first() subject.name = row['Nom'] subject.description = row['Description'] subject.study = study return subject
def addSubject(): form = SubjectForm() message = '' if form.validate_on_submit(): name = form.name.data db.session.add(Subject(name=name)) db.session.commit() message = '添加成功' return render_template('ques/addSubject.html', form=form, message=message)
def test_follow_subject_by_user(self): user = User(email='*****@*****.**', password='******') subject = Subject('Test') db.session.add(user) db.session.add(subject) db.session.commit() self.assertEqual(list(user.subjects), []) self.assertEqual(list(subject.users), []) models_conf_classes.UserConf.add_to_subject(user.id, subject.id) self.assertTrue(subject in user.subjects) self.assertTrue(user in subject.users)
def create_subject(data): if not data['title']: return jsonify({'msg': 'Can not create subject with empty title'}), 400 if Subject.query.filter_by(title=data['title']).first(): return jsonify( {'msg': f'Subject with current title {data["title"]} exists'}), 409 subject = Subject(**data) db.session.add(subject) db.session.commit() return jsonify({'msg': f'Subject crested', 'item_id': subject.id}), 201
def test_to_dict_method(self): teacher = User(email='*****@*****.**') subject = Subject("Test") teacher.is_teacher = True db.session.add(teacher) db.session.add(subject) db.session.commit() db.session.commit() tch_dict = teacher.to_dict() sub_dict = subject.to_dict() self.assertIsInstance(tch_dict, dict) self.assertIsInstance(sub_dict, dict)
def add(): form = SubjectForm() form.study.choices = [(c.id, c.name) for c in Study.query.all()] if form.validate_on_submit(): subject = Subject(study_id=form.study.data, name=form.name.data, description=form.description.data) db.session.add(subject) db.session.commit() flash(_('Nouvelle thématique ajouté avec succèss!')) return redirect(url_for('subject.detail', id=subject.id)) return render_template('subject/form.html', form=form)
def add_subject(): if request.method == 'POST': sub_name = request.form['sub_name'] admin_id = current_user.id subject = Subject(sub_name=sub_name, admin_id=admin_id) db.session.add(subject) db.session.commit() flash('{} subject is successfully added!'.format(sub_name)) return redirect(url_for('list_of_subject')) return render_template('administrator/add_subject.html', title='Add Subject', subjects=None)
def setup2(): if len(Settings.query.all()) == 0: form = SetupPasswords() if form.validate_on_submit(): db.session.add( User(username='******', password_hash=generate_password_hash( form.newPassword.data))) db.session.add(Settings(name='color1', value='007bff')) db.session.add(Settings(name='color2', value='6c757d')) db.session.add(Settings(name='colorBG', value='c0c0c0')) db.session.add( Settings(name='institutionName', value='Institution Name')) db.session.add( Settings(name='institutionAbbrev', value='Institution Abbreviation')) db.session.add(Settings(name='siteName', value='Site Name')) db.session.add(Settings(name='closed', value='1')) db.session.add( Subject(name="Not Applicable", code="N/A", teachers='0')) db.session.add(Subject(name="English", code="ELA", teachers='0')) db.session.add( Subject(name="Social Studies", code="SST", teachers='0')) db.session.add(Subject(name="Math", code="MAT", teachers='0')) db.session.add(Subject(name="Science", code="SCN", teachers='0')) db.session.add(Subject(name="Languages", code="LNG", teachers='0')) db.session.commit() return redirect(url_for('adminSettings')) else: return redirect(url_for('public')) return render_template('setup2.html', form=form)
def add_visitor(): params = request.form or request.get_json() try: name = params['name'] photo = request.files.get('photo') purpose = params.get('purpose') interviewee = params.get('interviewee') come_from = params.get('come_from') phone = params.get('phone') remark = params.get('remark') company_id = g.user.company_id start_time = int(params.get('start_time', 0)) end_time = int(params.get('end_time', 0)) vip = bool(int(params.get('vip', False))) subject_type = int(params.get('subject_type', 1)) description = params.get('description') except: import traceback print traceback.format_exc() return error_result(ErrorCode.ERROR_INVALID_PARAM) if not start_time or not end_time: start_time = g.TIMESTAMP - 5 * 60 end_time = g.TIMESTAMP + 2 * 3600 if vip: subject_type = SubjectType.TYPE_VIP subject = Subject(company_id=company_id, name=name, subject_type=subject_type, description=description, remark=remark, start_time=start_time, end_time=end_time, purpose=purpose, interviewee=interviewee, come_from=come_from, phone=phone, password='******') db.session.add(subject) db.session.commit() if photo: photo, error = create_user_photo(photo, company_id) if error: return error subject.photos.append(photo) update_company_data_version(g.user.company, subject.id) return success_result(subject.get_json())
def addSubject(): add_subject_form = SubjectsAdd() users = User.query.all() if add_subject_form.validate_on_submit() and request.method == 'POST': user = User.query.filter_by( username=request.form.get('Teacher')).first() subject = Subject(name=add_subject_form.subject_name.data, teacher=user) db.session.add(subject) db.session.commit() return redirect(url_for('main.getSubjects')) return render_template('admin/subjects_add.html', add_subject_form=add_subject_form, users=users)
def subject_import_photo(): try: photo = request.files['photo'] name = photo.filename.rsplit('.', 1)[0] except: return error_result(ErrorCode.ERROR_INVALID_PARAM) photo, error = create_user_photo(photo, g.user.company_id) if error: return error subject = Subject(company_id=g.user.company_id, subject_type=SubjectType.TYPE_EMPLOYEE, name=name, create_time=g.TIMESTAMP) subject.photos.append(photo) db.session.add(subject) db.session.commit() update_company_data_version(g.user.company, subject.id) return success_result(subject.get_json(with_photos=True))
def setModular(): name = request.values.get('name', type=str) identity = request.values.get('id', type=int) registered_time = getCurrentDateTime() founder = current_user.get_id() introduction = request.values.get('introduction', type=str) majorType = request.values.get('type', type=int) father_id = request.values.get('father_id', type=int) file_url = savePhotoRequestFile(value='picture') if majorType is 0: column = Major(name=name, identity=identity, time=registered_time, founder=founder, introduction=introduction, picture=file_url, url='') elif majorType is 1: column = Subject(name=name, identity=identity, time=registered_time, founder=founder, introduction=introduction, picture=file_url, father_id=father_id, url='') elif majorType is 3: column = Description(name=name, identity=identity, time=registered_time, founder=founder, introduction=introduction, picture=file_url, father_id=father_id, url='') elif majorType is 2: column = Orientation(name=name, identity=identity, time=registered_time, founder=founder, introduction=introduction, picture=file_url, url='') db.session.add(column) db.session.commit() return json.dumps(sendData(True, "提交成功", "OK"))
def add_association(self, username, subject_name, group_id): tutor = self.find_tutor_by_username(username) if tutor.tgs.filter_by(subject_name=subject_name, group_id=group_id).first(): raise AssociationExist(subject_name=subject_name, group_id=group_id) subject = Subject.find_by_name(subject_name) if subject is None: subject = Subject(name=subject_name) subject.add_to_db() group = Group.find_by_id(group_id) if group is None: group = Group(id=group_id) group.add_to_db() association = AssociationTGS() association.subject = subject association.group = group tutor.tgs.append(association) db.session.commit()
def addsubject(): if request.method == 'POST': sub_id=request.form.get('subid') sub_name=request.form.get('subname') batch_id=request.form.get('batchid') subject_det = Subject(subjectid=sub_id,subjectname=sub_name,batchid=batch_id,author=current_user) db.session.add(subject_det) db.session.commit() students=Student_User.query.all() for student in students: if(student.batchid==batch_id): student_subject_det=Student_Subject(subjectid=sub_id,subjectname=sub_name,batchid=batch_id,author=student) db.session.add(student_subject_det) db.session.commit() user = User.query.filter_by(id=current_user.id).first_or_404() subjects = Subject.query.filter_by(user_id=user.id).all() return render_template('subject.html',subjects=subjects)
def query(request): query_string = request.POST.get('query', '') subject = get_subject_by_query_string(query_string=query_string) if subject and subject.requested_recently(): subject.request_time = timezone.now() subject.save(update_fields=['request_time']) else: data = fetch_data( url='https://rmsp.nalog.ru/search-proc.json', query_string=query_string, ) if data: subject = Subject(**data) subject.save() subject.query_set.create(query_string=query_string) return HttpResponseRedirect(reverse('app:index'))
def admin_encode_student_grades(user_id): form = EncodeSubjectForm() user = User.query.filter_by(id=user_id).first_or_404() if form.validate_on_submit(): subject = Subject( subject_name=form.subject_name.data, units=form.units.data, year=form.year.data, semester=form.semester.data, final_grade=form.final_grade.data, user=user ) db.session.add(subject) db.session.commit() flash('Added subject') return redirect(url_for('admin_student_grades', user_id=user.id)) return render_template('admin_templates/encode_subject.html', title='Grades', user=user, form=form)
def init_subjects(): for sg in list(C_SubjectGroup): saved_subject_group = SubjectGroup.query.filter_by(type=sg.name).first() if saved_subject_group is None: add_subject_group = SubjectGroup() add_subject_group.type = sg.name add_subject_group.name = sg.value db.session.add(add_subject_group) db.session.flush() saved_subject_group = add_subject_group for subj in C_SubjectGroup.get_subjects(saved_subject_group.type): saved_subject = Subject.query.filter_by(type=subj.name).first() if saved_subject is None: add_subject = Subject() add_subject.type = subj.name add_subject.name = subj.value add_subject.subject_group_id = saved_subject_group.id db.session.add(add_subject) db.session.commit()
def subject_add_text(request, book_id): if not request.session.get('is_login', None): return render(request, 'login.html') check_book = Book.objects.filter(id=book_id) if not check_book: Info = {'info': '该书单不存在'} return render(request, 'public/error.html', Info) if request.method == 'POST': content = request.POST.get('content', None) number = request.POST.get('number', None) book = Book.objects.get(id=book_id) if content and number: Subject(content=content, type=1, book=book, number=number).save() Info = {'info': '题目添加成功'} return render(request, 'public/success.html', Info) else: info = {'info': '编号和内容不能为空'} return render(request, 'public/error.html', info) return render(request, 'book/addSubject.html')
def subject_add_image(request, book_id): if not request.session.get('is_login', None): return render(request, 'login.html') check_book = Book.objects.filter(id=book_id) if not check_book: Info = {'info': '该书单不存在'} return render(request, 'public/error.html', Info) if request.method == 'POST': number = request.POST.get('number', None) img = request.FILES.get('img', None) if number and img: book = Book.objects.get(id=book_id) Subject(book=book, number=number, img_url=img, type=0).save() Info = {'info': '题目上传成功'} return render(request, 'public/success.html', Info) else: info = {'info': '编号和图片不能为空'} return render(request, 'public/error.html', info) return render(request, 'book/addSubjectImg.html')
def tutor_home(user): tutor = Tutor.query.filter_by(user_id=user.id).first() if request.method == 'GET': associations = tutor.tgs.all() return jsonify(AssociationTGS.serialize_list(associations)) if request.method == 'POST': data = request.get_json() subject = Subject.query.get(data.get('subject_name')) if subject is None: subject = Subject(name=data.get('subject_name')) db.session.add(subject) group = Group.query.get(data.get('group_id')) if group is None: group = Group(id=data.get('group_id')) db.session.add(group) association = AssociationTGS() association.subject = subject association.group = group tutor.tgs.append(association) db.session.commit() return jsonify({"message": "success"}), 200
def test_failing_scraped_article_serialization(): missing_date_article = ScrapedArticle( article=Article( id='a-id', url='target-url', title='a-title', body='a-body', keywords=[ 'k-0', 'k-1' ], date=None), subjects=[ Subject( id='s-id', symbol='symbol', name='name', score=0.0, article_id='a-id') ], referer=Referer( id='r-id', external_id='e-id', follower_count=100, article_id='a-id') ) with pytest.raises(AttributeError): missing_date_article.asdict() with pytest.raises(TypeError): ScrapedArticle( article=Article( id='a-id', url='target-url', title='a-title', body='a-body', keywords=[ 'k-0', 'k-1' ], date=datetime.utcnow()) )
def test_scheduling_creating(self): teacher = User(email='*****@*****.**') student = User(email='*****@*****.**') subject = Subject("Test") teacher.is_teacher = True student.is_teacher = False db.session.add(teacher) db.session.add(student) db.session.add(subject) db.session.commit() self.assertEqual(Scheduling.query.all(), []) resp = models_conf_classes.SchedulingConf.add_scheduling( subject_id=subject.id, data=datetime.now(), users=[teacher.id, student.id] ) self.assertEqual(resp[1], 201) sch = Scheduling.query.first() self.assertEqual(sch.id, 1) self.assertEqual(sch.subject_id, subject.id) self.assertTrue(teacher in sch.users) self.assertTrue(student in sch.users) self.assertTrue(sch in teacher.lesson_date) self.assertTrue(sch in student.lesson_date)
def add(): data = request.json or request.data or request.form res_code = 200 res = dict(status="fail") name = data.get("name") branch_id = data.get("branch_id") for key in ("name", "branch_id"): val = data.get(key) if not val: res["statusText"] = errs.BLANK_VALUES_FOR_REQUIRED_FIELDS.text res["statusData"] = errs.BLANK_VALUES_FOR_REQUIRED_FIELDS.type( [key]) return jsonify(res), res_code subject = Subject.query.filter_by(name=name).first() if subject: res["error"] = "Subject with this name already present" return jsonify(res), res_code subject = Subject(name=name, branch_id=branch_id) db.session.add(subject) db.session.commit() res["status"] = "success" res["subject"] = subject.serialize() return jsonify(res), res_code
def init_subjects(): import os from os.path import isfile, join, isdir from app import app, db from app.models import Subject, Update for subject in Subject.query.all(): db.session.delete(subject) subjectList = [ {'display_name': 'IB Biology', 'path': '/notes/ib/biology', 'id_name': 'ib-biology'}, {'display_name': 'IB Business', 'path': '/notes/ib/business', 'id_name': 'ib-business'}, {'display_name': 'IB Chemistry SL', 'path': '/notes/ib/chemistry', 'id_name': 'ib-chemistry'}, {'display_name': 'IB Economics', 'path': '/notes/ib/economics', 'id_name': 'ib-economics'}, {'display_name': 'IB English Language and Literature', 'path': '/notes/ib/eng-langlit-sl', 'id_name': 'ib-eng-langlit-sl'}, {'display_name': 'IB French B', 'path': '/notes/ib/french-b', 'id_name': 'ib-french-b'}, {'display_name': 'IB Mandarin AB', 'path': '/notes/ib/mandarin-ab', 'id_name': 'ib-mandarin-ab'}, {'display_name': 'IB Mathematics Analysis and Approaches', 'path': '/notes/ib/math-aa-hl', 'id_name': 'ib-math-aa-hl'}, {'display_name': 'IB Physics', 'path': '/notes/ib/physics', 'id_name': 'ib-physics'}, {'display_name': 'IB Psychology', 'path': '/notes/ib/psychology', 'id_name': 'ib-psychology'}, {'display_name': 'IB Spanish AB', 'path': '/notes/ib/spanish-ab', 'id_name': 'ib-spanish-ab'}, {'display_name': 'IB Spanish B', 'path': '/notes/ib/spanish-b', 'id_name': 'ib-spanish-b'}, {'display_name': 'ToK', 'path': '/notes/ib/tok', 'id_name': 'ib-tok'}, {'display_name': 'IG Additional Mathematics', 'path': '/notes/ig/addmath', 'id_name': 'ig-addmath'}, {'display_name': 'IG Biology', 'path': '/notes/ig/biology', 'id_name': 'ig-biology'}, {'display_name': 'IG Economics', 'path': '/notes/ig/economics', 'id_name': 'ig-economics'}, {'display_name': 'IG Global Perspectives', 'path': '/notes/ig/gp', 'id_name': 'ig-gp'}, {'display_name': 'IG English Literature', 'path': '/notes/ig/englit', 'id_name': 'ig-englit'}, {'display_name': 'IG Physics', 'path': '/notes/ig/physics', 'id_name': 'ig-physics'} ] for subject in subjectList: s = Subject(display_name = subject['display_name'], path = subject['path'], id_name = subject['id_name']) db.session.add(s) db.session.commit()
def test_get_subject_by_id_func(self): subject = Subject('Test') db.session.add(subject) db.session.commit() subject_data = models_conf_classes.SubjectConf.get_obj_dict_or_404(Subject, subject.id) self.assertEqual(subject.to_dict(), subject_data[0].json['item'])
from app import app from app import db from app.models import Subject app.config.from_object('config.LoadResultsConfig') subjects = [ Subject(name='Тест по математике', grade=7, max_score=14, always_count=True), Subject(name='Математика', grade=7, max_score=20), Subject(name='Филология', grade=7, max_score=20), Subject(name='История', grade=7, max_score=20), Subject(name='Биология', grade=7, max_score=20), Subject(name='Химия', grade=7, max_score=20), Subject(name='География', grade=7, max_score=20), Subject(name='Тест по математике', grade=8, max_score=20, always_count=True), Subject(name='Математика', grade=8, max_score=20), Subject(name='Филология', grade=8, max_score=20), Subject(name='История', grade=8, max_score=20), Subject(name='Биология', grade=8, max_score=20), Subject(name='Химия', grade=8, max_score=20), Subject(name='География', grade=8, max_score=20), Subject(name='Английский язык', grade=8, max_score=20), ] db.session.add_all(subjects) db.session.commit()
from app import db from app.models import User, Role, Subject, Question db.create_all() Role.insert_roles() subject = Subject(name='dataStructure') question = Question(context='单链表是一种随机存储结构', answer='1', degree='1', question_type='choice', appeareace=0, point=1) User.role = Role.query.filter_by(default=1).first() pro = User(email='*****@*****.**', username='******', password_hash='pro') pro.role = Role.query.filter_by(permission=0x04).first()
def initial_import(export_file): """ Imports data from a CSV file generated by the 'Export study reports' script in the FileMaker DB. Includes previously submitted reports which are not exported when you just dump the tables to file. Parameters ---------- export_file : str Path to the output file of the 'Export study reports' script """ if not op.exists(export_file): raise Exception("Could not find an FileMaker export file at {}".format( export_file)) imported = [] previous = [] skipped = [] # Get previous reporters nick_ferris = User.query.filter_by( email='*****@*****.**').one() paul_beech = User.query.filter_by(email='*****@*****.**').one() axis = User.query.filter_by(email='*****@*****.**').one() with xnat.connect(server=app.config['SOURCE_XNAT_URL'], user=app.config['SOURCE_XNAT_USER'], password=app.config['SOURCE_XNAT_PASSWORD']) as mbi_xnat: with open(export_file) as f: rows = list(csv.DictReader(f)) for row in tqdm(rows): data_status = PRESENT # Check to see if the project ID is one of the valid types mbi_project_id = row['ProjectID'] if mbi_project_id is None or not mbi_project_id: mbi_project_id = '' data_status = INVALID_LABEL else: mbi_project_id = mbi_project_id.strip() if mbi_project_id[:3] not in ('MRH', 'MMH', 'CLF'): print("skipping {} from {}".format( row['StudyID'], mbi_project_id)) skipped.append(row) continue try: project = Project.query.filter_by( mbi_id=mbi_project_id).one() except orm.exc.NoResultFound: project = Project(mbi_project_id) db.session.add(project) # pylint: disable=no-member db.session.commit() # pylint: disable=no-member # Extract subject information from CSV row mbi_subject_id = (row['SubjectID'].strip() if row['SubjectID'] is not None else '') study_id = (row['StudyID'].strip() if row['StudyID'] is not None else '') first_name = (row['FirstName'].strip() if row['FirstName'] is not None else '') last_name = (row['LastName'].strip() if row['LastName'] is not None else '') try: dob = (datetime.strptime(row['DOB'].replace('.', '/'), '%d/%m/%Y') if row['DOB'] is not None else datetime(1, 1, 1)) except ValueError: raise Exception( "Could not parse date of birth of {} ({})".format( study_id, row['DOB'])) # Check to see if subject is present in database already # otherwise add them try: subject = Subject.query.filter_by( mbi_id=mbi_subject_id).one() except orm.exc.NoResultFound: subject = Subject(mbi_subject_id, first_name, last_name, dob) db.session.add(subject) # pylint: disable=no-member # Check to see whether imaging session has previously been # reported or not if ImgSession.query.get(study_id) is None: # Parse scan date try: scan_date = datetime.strptime( row['ScanDate'].replace('.', '/'), '%d/%m/%Y') except ValueError: raise Exception( "Could not parse scan date for {} ({})".format( study_id, row['ScanDate'])) # Extract subject and visit ID from DARIS ID or explicit # fields if row['DarisID']: match = daris_id_re.match(row['DarisID']) if match is not None: _, subject_id, visit_id = match.groups() if visit_id is None: visit_id = '1' else: subject_id = visit_id = '' if row['DarisID'].startswith('1.5.'): data_status = UNIMELB_DARIS else: data_status = INVALID_LABEL else: try: subject_id = row['XnatSubjectID'].strip() except (KeyError, AttributeError): subject_id = '' try: visit_id = visit_id = row['XnatVisitID'].strip() except (KeyError, AttributeError): visit_id = '' if not subject_id or not visit_id: data_status = INVALID_LABEL try: subject_id = int(subject_id) except ValueError: pass else: subject_id = '{:03}'.format(subject_id) # Determine whether there are outstanding report(s) for # this session or not and what the XNAT session prefix is all_reports_submitted = bool(row['MrReport']) if mbi_project_id.startswith('MMH'): visit_prefix = 'MRPT' all_reports_submitted &= bool(row['PetReport']) else: visit_prefix = 'MR' # Get the visit part of the XNAT ID try: numeral, suffix = re.match(r'(\d+)(.*)', visit_id).groups() visit_id = '{}{:02}{}'.format( visit_prefix, int(numeral), (suffix if suffix is not None else '')) except (ValueError, TypeError, AttributeError): data_status = INVALID_LABEL xnat_id = '_'.join( (mbi_project_id, subject_id, visit_id)).upper() # If the session hasn't been reported on check XNAT for # matching session so we can export appropriate scans to # the alfred scan_ids = [] if all_reports_submitted: data_status = NOT_CHECKED elif data_status not in (INVALID_LABEL, UNIMELB_DARIS): try: exp = mbi_xnat.experiments[xnat_id] # noqa pylint: disable=no-member except KeyError: data_status = NOT_FOUND else: try: for scan in exp.scans.values(): scan_ids.append((scan.id, scan.type)) except XNATResponseError as e: raise Exception( "Problem reading scans of {} ({}):\n{}". format(study_id, xnat_id, str(e))) session = ImgSession(study_id, project, subject, xnat_id, scan_date, data_status, priority=LOW) db.session.add(session) # pylint: disable=no-member # Add scans to session for scan_id, scan_type in scan_ids: try: scan_type = ScanType.query.filter_by( name=scan_type).one() except orm.exc.NoResultFound: scan_type = ScanType(scan_type) db.session.add(scan_type) # noqa pylint: disable=no-member db.session.add(Scan(scan_id, session, scan_type)) # noqa pylint: disable=no-member # Add dummy reports if existing report was stored in FM if row['MrReport'] is not None and row['MrReport'].strip(): if 'MSH' in row['MrReport']: reporter = axis else: reporter = nick_ferris db.session.add( Report( # noqa pylint: disable=no-member session.id, reporter.id, '', NOT_RECORDED, [], MRI, date=scan_date, dummy=True)) if (row['PetReport'] is not None and row['PetReport'].strip()): db.session.add( Report( # noqa pylint: disable=no-member session.id, paul_beech.id, '', NOT_RECORDED, [], PET, date=scan_date, dummy=True)) # noqa pylint: disable=no-member db.session.commit() # pylint: disable=no-member imported.append(study_id) else: previous.append(study_id)
student = Student(assigned_id=student_id, year=2017) db.session.add(student) for subject_name in subjects_names: score = row[subject_name] if pd.isnull(score): continue subject = db.session.query(Subject).filter_by(name=subject_name, grade=grade).first() if not subject: print(f'Предмета "{subject_name}" нет') subject = Subject(name=subject_name, max_score=20, grade=grade) db.session.add(subject) try: score = float(score) result = Result(student=student, score=score, subject=subject, grade=grade) except ValueError: score = str(score) result = Result(student=student, score_string=score, subject=subject, grade=grade)
def init(password=None): db_path = app.config['SQLALCHEMY_DATABASE_URI'][10:] if op.exists(db_path): if app.config.get('TEST', False): os.remove(db_path) else: raise DatabaseAlreadyInitialisedError( "Database has already been initialised at {}".format(db_path)) else: os.makedirs(op.dirname(db_path), exist_ok=True) db.create_all() admin_role = Role(ADMIN_ROLE, 'Administrator') reporter_role = Role(REPORTER_ROLE, 'Reporter') db.session.add(admin_role) # noqa pylint: disable=no-member db.session.add(reporter_role) # noqa pylint: disable=no-member if not app.config.get('TEST', False): if password is None: raise Exception("Admin password needs to be provided for " "production database") # Add administrator db.session.add( User( 'Administrator', 'Account', # noqa pylint: disable=no-member app.config['ADMIN_EMAIL'], generate_password_hash(password), roles=[admin_role], active=True)) # Add dummy data to test with else: scan_types = [ ScanType('Head_t1_mprage'), ScanType('Head_t2_space_sag_p2_iso'), ScanType('t1_mprage_sag_p3_iso_1_ADNI'), ScanType('t2_space_sag_p2_iso'), ScanType('Head_No MT fl3d_axial_p2_iso'), ScanType('Shouldnt_be_shown') ] db.session.add_all(( # noqa pylint: disable=no-member User('Thomas', 'Close', '*****@*****.**', suffixes='PHD', title='Dr.', password=generate_password_hash('password'), middle_name='G.', roles=[reporter_role, admin_role], active=True), User('Parisa', 'Zakavi', '*****@*****.**', generate_password_hash('password'), roles=[reporter_role, admin_role], active=True))) subjects = [] for mbi_id, dob, first_name, last_name in [ ('MSH103138', '12/03/1952', 'Bob', 'Brown'), ('MSH223132', '05/12/1951', 'Sami', 'Shah'), ('MSH892342', '24/08/1980', 'Bill', 'Bryson'), ('MSH234234', '21/09/1993', 'Jesse', 'Jackson'), ('MSH623177', '15/12/1967', 'Robert', 'Redford'), ('MSH823056', '27/06/2001', 'Danny', 'DeVito'), ('MSH097334', '12/03/1972', 'Boris', 'Becker'), ('MSH097335', '12/03/1972', 'Charlie', 'Chaplin'), ('MSH097336', '12/03/1972', 'Emilio', 'Estevez') ]: subj = Subject(mbi_id, first_name, last_name, datetime.strptime(dob, '%d/%m/%Y')) # noqa pylint: disable=no-member subjects.append(subj) db.session.add(subj) # pylint: disable=no-member img_sessions = {} for subj_id, study_id, xnat_id, scan_date, priority, status in [ (0, 1231, 'MRH100_124_MR02', '10/04/2017', LOW, PRESENT), (1, 1244, 'SHOULD_NOT_BE_SHOWN_NEWER_SESSION', '11/02/2018', LOW, PRESENT), (1, 1254, 'SHOULD_NOT_BE_SHOWN_AS_NOT_FOUND', '12/02/2018', LOW, NOT_FOUND), (2, 1366, 'MRH999_999_MR01', '11/10/2017', LOW, PRESENT), (2, 1500, 'SHOULD_NOT_BE_SHOWN_PREV_REPORT', '11/5/2018', LOW, PRESENT), (2, 1600, 'MRH999_999_MR99', '11/1/2019', HIGH, PRESENT), (3, 3413, 'MRH088_065_MR01', '13/01/2019', MEDIUM, PRESENT), (4, 4500, 'MRH112_002_MR01', '11/02/2019', LOW, PRESENT), (5, 5003, 'MRH100_025_MR01', '1/08/2017', MEDIUM, PRESENT), (6, 9834, 'SHOULD_NOT_BE_SHOWN_AS_NOT_EXPORTED', '10/11/2018', LOW, PRESENT), (7, 9835, 'SHOULD_NOT_BE_SHOWN_AS_INVALID', '10/12/2018', LOW, INVALID_LABEL), (8, 9836, 'SHOULD_NOT_BE_SHOWN_AS_NOT_PRESENT', '10/10/2018', LOW, NOT_FOUND) ]: project_id = xnat_id.split('_')[0] try: project = Project.query.filter_by(mbi_id=project_id).one() except orm.exc.NoResultFound: project = Project(project_id) img_session = img_sessions[study_id] = ImgSession( study_id, project, subjects[subj_id], xnat_id, datetime.strptime(scan_date, '%d/%m/%Y'), data_status=status, priority=priority) db.session.add(img_session) # noqa pylint: disable=no-member for i, scan_type in enumerate( random.sample(scan_types, random.randint(1, len(scan_types) - 1))): db.session.add( Scan( i, img_session, scan_type, # noqa pylint: disable=no-member exported=scan_type.clinical)) db.session.commit() # noqa pylint: disable=no-member # Add report for 1366 img_session = img_sessions[1366] db.session.add( Report( img_session.id, 1, "Nothing to report", 0, # noqa pylint: disable=no-member used_scans=img_session.scans, modality=MRI)) # Set the final scan of the final session to be not-exported, so it # shouldn't show up img_sessions[9834].scans[-1].exported = False db.session.commit() # noqa pylint: disable=no-member # Add historial reporters for previously reported records db.session.add_all(( # noqa pylint: disable=no-member User('Nicholas', 'Ferris', '*****@*****.**', generate_password_hash(''.join( random.choices(string.printable, k=50))), suffixes='MBBS FRANZCR', title='Dr.', roles=[reporter_role], active=False), User('Paul', 'Beech', '*****@*****.**', generate_password_hash(''.join( random.choices(string.printable, k=50))), suffixes='MBBS FRANZCR', title='Dr.', roles=[reporter_role], active=False), User('AXIS', 'Reporting', '*****@*****.**', generate_password_hash(''.join( random.choices(string.printable, k=50))), roles=[reporter_role], active=False))) db.session.commit() # noqa pylint: disable=no-member return db_path