def post(self, username): if username != auth.current_user().username: abort(401) args = self.reqparse.parse_args() try: user = auth.current_user() course = Course(name=args['name'], user_id=user.id) user.courses.append(course) db.session.add(course) db.session.commit() return course.to_dict() except SQLAlchemyError as e: abort(422)
def create_course(username): user = User.query.filter_by(username=username).first() if user is None: abort(404) if not request.json or not 'name' in request.json: abort(400) try: course = Course(name=request.json['name'], user_id=user.id) user.courses.append(course) db.session.add(course) db.session.commit() except SQLAlchemyError as e: abort(422) response = course.to_dict() status = 201 return jsonify(response), status
def admin_api(function): if function == 'participants': parts = list(Participant.select().dicts()) return make_response(jsonify({'participants': parts}), 200) elif function == 'degrees': degrees = list(Degree.select().dicts()) return make_response(jsonify({'degrees': degrees}), 200) elif function == 'chairs': chairs = list(Chair.select().dicts()) return make_response(jsonify({'chairs': chairs}), 200) elif function == 'courses': courses = list(Course.select().dicts()) return make_response(jsonify({'courses': courses}), 200) elif function == 'toggle_registration': if registration_active(): open('./reg_inactive', 'a').close() else: os.remove('./reg_inactive') return make_response( jsonify({ 'status': 'success', 'registration': registration_active() }), 200 ) elif function == 'stats': degrees = Degree.select() degree_counts = { d.name: d.count for d in Degree.select( Degree, fn.Count(Participant.id).alias('count') ).join(Participant).group_by(Degree) } degree_guests = { d.name: d.guests for d in Degree.select( Degree, fn.Count(Participant.guests).alias('guests') ).join(Participant).group_by(Degree) } stats = { 'degree_counts': degree_counts, 'degree_guests': degree_guests, 'participant_count': Participant.select().count(), 'guest_count': (Participant .select(fn.SUM(Participant.guests)) .scalar()) } return make_response( jsonify(stats) ) abort(404)
def course(cls, capacity, hour, credit, code, name, department_name): course = get.course(code=code) if not course: course = Course( capacity=capacity, hour=hour, credit=credit, code=code, name=name, prerequisite='null', department_id=add.department(department_name).id, ) cls._all(course) return course
def post(self, course_id): "Add a course (admin)" self.check_admin() if self.db.query(Course).filter(Course.id == course_id).one_or_none(): self.json_error(409, "Course already exists") try: instructors = [] for i in json.loads(self.get_argument("instructors", "[]")): instructors.append(self.find_or_create_user(i)) except json.decoder.JSONDecodeError: self.json_error(400, "Instructors cannot be JSON decoded") course = Course(course_id, instructors) self.db.add(course) self.db.commit() self.json_success()
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database import Course, Student # Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance engine = create_engine('sqlite:///database.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() # Insert Courses in course tables newCourse = Course(title="", semester="") session.add(newCourse) session.commit() # Insert Student in student tables newStudent = Student(id="") session.add(newStudent) session.commit()
def api(function=None): if not function: if not registration_active(): return make_response( jsonify(errormessage='Registration disabled.'), 401 ) try: participant = Participant(**request.get_json(force=True)) if not request.get_json(force=True).get('validDate'): return make_response( jsonify(errormessage='Error'), 400 ) participant.email = participant.email.lower() if int(participant.guests) > parsapp.config['MAXIMUM_GUESTS']: return make_response('Guests exceeding maximum.', 400) participant.save() response = make_response( jsonify(message='Success', token=participant.token), 200 ) try: sendmail(participant) except: if not parsapp.config['DEBUG']: response = make_response( jsonify(errormessage='Error while mailing.'), 500 ) else: raise except IntegrityError: response = make_response( jsonify(errormessage='User already in Database.'), 400 ) return response else: if function == 'config': degrees = {str(d.id): {'id': d.id, 'name': d.name} for d in Degree.select()} chairs = {str(c.id): {'id': c.id, 'name': c.name} for c in Chair.select()} courses = {str(c.id): {'id': c.id, 'name': c.name} for c in Course.select()} configObj = { 'degrees': degrees, 'chairs': chairs, 'courses': courses, 'allowed_mail': parsapp.config['ALLOWED_MAIL_SERVER'], 'maximum_guests': parsapp.config['MAXIMUM_GUESTS'], 'registration_is_active': registration_active() } return jsonify(configObj) if function == 'participant': if not registration_active(): return make_response( jsonify(errormessage='Registration disabled.'), 401 ) p = Participant.get(id=request.args.get('participant_id')) if p.token == request.args.get('token'): pObj = { 'firstname': p.firstname, 'lastname': p.lastname, 'guests': p.guests, 'degree': p.degree.id, 'email': p.email, 'title': p.title, 'token': p.token, 'chair': p.chair.id, 'course': p.course.id, 'allow_email_contact': p.allow_email_contact, } return jsonify(pObj) else: return make_response( jsonify(errormessage='No access!'), 401 ) if function == 'resend': try: p = ( Participant .select() .where(Participant.email == request.args.get('email').lower()) .get() ) sendmail(p) except: if not parsapp.config['DEBUG']: return(jsonify(errormessage='Fail'), 500) else: raise return(jsonify(message='Success'), 200) if function == 'update': p = Participant.get(id=request.args.get('participant_id')) if p.token == request.args.get('token'): data = request.get_json(force=True) p.firstname = data['firstname'] p.lastname = data['lastname'] p.degree = data['degree'] p.chair = data['chair'] p.course = data['course'] p.title = data['title'] p.guests = data['guests'] p.allow_email_contact = data['allow_email_contact'] p.save() return make_response(jsonify(message='Success'), 200) else: return make_response( jsonify(errormessage='No access!'), 401 ) abort(404)
def get_courses(): '''Navigates to Premain Gets all courses ''' session = Session() r = s.get('https://edux.pjwstk.edu.pl/Premain.aspx') r.raise_for_status() new_announcements = [] for i, (course_id, name, url) in enumerate(extract_courses(r.content)): course = session.query(Course). \ filter_by(course_id=course_id). \ first() if course is None: print u'Add new course "{}"'.format(name) course = Course( course_id=course_id, title=name) session.add(course) print course.title # Get inside the course r = s.get(url) r.raise_for_status() session.expunge(course) course_content = r.content if 'Announcements.aspx' in course_content: print 'There are announcements' # Get announcement for this course for (timestamp, announcement) in get_announcements(course, url): new_announcements.append((course.title, timestamp, announcement)) if 'Quiz.aspx' in course_content: print 'There are quizes' get_quiz(course) if 'Folder.aspx' in course_content: print 'There are folders' get_folders(course) # Prepare email stuff from gathered data subject = 'You have {0} new announcements on EDUX'.format( len(new_announcements)) body = u'' # Sort new announcements so highest date (newer) will be on top sorted_announcements = sorted(new_announcements, key=operator.itemgetter(1), reverse=True) # TODO: Use some templating here for i, (course, timestamp, announcement) in enumerate(sorted_announcements, 1): body += u'{0}. {1} at {2}\n{3}\n\n'.format( i, timestamp, course, announcement) # Cant send empty body because mailgun throws HTTP400s. send_notify(subject, body) session.commit()
if os.path.isfile(DBPATH): if input('Do you want to create a backup? [y]/N: ') in ['y', '']: shutil.copyfile( DBPATH, os.path.splitext(DBPATH)[0] + '-backup-' + str(date.today()) + '.sqlite') if input('File already existing, ' 'do you want to overwrite it? [y]/N: ') in ['y', '']: os.remove(DBPATH) else: sys.exit(0) db = SqliteDatabase(DBPATH) db.connect() db.create_tables([Participant, Degree, Chair, Course], safe=True) for d in ['Bachelor', 'Master', 'Doktor']: Degree.create(name=d) for c in ['Physik', 'Medizinphysik', 'Lehramt']: Course.create(name=c) for c in [ 'E1', 'E2', 'E3', 'E4', 'E5', 'E6', 'T1', 'T2', 'T3', 'T4', 'BP', 'Extern' ]: Chair.create(name=c) db.close()
def insertData(): Course() db.create_all() courses = data.load_data() res = insertCoursesIntoDatabase(courses) return jsonify(res)
def insert_data(evaluations): for evaluation in evaluations: evaluation_data = {} now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # course info located in first row, first td row = evaluation.xpath('.//tr/td')[0] evaluation_data["source"] = parser.get_data_source(evaluation) evaluation_data["instructor"] = parser.get_instructor_name(row) evaluation_data["course_name"] = parser.get_course_name(row) evaluation_data["semester_full"] = parser.get_full_semester(row) evaluation_data["semester"] = parser.get_semester( evaluation_data["semester_full"]) evaluation_data["year"] = parser.get_year( evaluation_data["semester_full"]) evaluation_data["reg_index"] = parser.get_reg_index(row) evaluation_data["course_code"] = parser.get_course_code(row) evaluation_data['school'] = parser.get_school( evaluation_data["course_code"]) evaluation_data['department'] = parser.get_department( evaluation_data["course_code"]) evaluation_data['course'] = parser.get_course( evaluation_data["course_code"]) evaluation_data['section'] = parser.get_section( evaluation_data["course_code"]) evaluation_data["enrollments"] = parser.get_num_enrollments(row) evaluation_data["responses"] = parser.get_num_responses(row) evals = parser.get_eval_rows(evaluation) parser.get_school(evaluation_data["course_code"]) course_session = session() course = Course(course_name=evaluation_data["course_name"], year=evaluation_data["year"], semester=evaluation_data["semester"], school=evaluation_data['school'], department=evaluation_data['department'], course=evaluation_data['course'], section=evaluation_data['section'], regindex=evaluation_data["reg_index"], source=evaluation_data['source'], enrollments=evaluation_data['enrollments'], responses=evaluation_data['responses'], instructor=evaluation_data["instructor"], created_at=now) course_session.close() course_id = add_course(course_session, course) if course_id == -1: print("Skipping course [{}] - {} - {}".format( course_id, evaluation_data["course_name"], evaluation_data["instructor"])) else: print("Added course [{}] - {} - {}".format( course_id, evaluation_data["course_name"], evaluation_data["instructor"])) evaluation_data["questions"] = evals #print("Instructor {} : {}".format(evaluation_data["instructor"], evals)) evals_json = json.dumps(evaluation_data) evals_json = json.loads(evals_json) for e in evals_json['questions']: #print(evals_json['questions'][e]) q_text = evals_json['questions'][e]['question_text'] q_type = evals_json['questions'][e]['question_type'] responses = evals_json['questions'][e]['response'] question_session = session() question = Question(question_text=bytearray(q_text, 'utf-8'), question_type=q_type, created_at=now) q_id = add_question(question_session, question) question_session.close() answer_session = session() rate_1, rate_2, rate_3, rate_4, rate_5, blank = 0, 0, 0, 0, 0, 0 responses = OrderedDict(sorted(responses.items())) for indx, inc in enumerate(responses): if indx == 0: rate_1 = responses[inc] elif indx == 1: rate_2 = responses[inc] elif indx == 2: rate_3 = responses[inc] elif indx == 3: rate_4 = responses[inc] elif indx == 4: rate_5 = responses[inc] elif indx == 5: blank = responses[inc] answer = Answer(course_id=course_id, question_id=q_id, rating_1=rate_1, rating_2=rate_2, rating_3=rate_3, rating_4=rate_4, rating_5=rate_5, blank=blank, created_at=now) add_answer(answer_session, answer) answer_session.close()