def read_students_csv(filename, course_id): """ Reads in a csv file and creates a user if the there is no user yet with the gived id. Adds the user to the specified course if its not yet active. This will probably be removed when the integration with lti works. If not, add some better error handeling and exiting. """ f = open(filename, 'r') reader = csv.reader(f, delimiter=',') course = Course.query.get(course_id) if course is None: f.close() return False for row in reader: if len(row) != 3: continue stud_id = int(row[0]) user = User.query.get(stud_id) if user is None: user = User(id=int(row[0]), name=row[1], email=row[2]) if not database.addItemSafelyToDB(user): continue if user not in course.student_courses: print("APPENDING USER") course.student_courses.append(user) database.get_db().session.commit() f.close() return True
def read_tas_csv(filename, course_id): """ Add teaching assistants from uploaded file. """ f = open(filename, 'r') reader = csv.reader(f, delimiter=',') course = Course.query.get(course_id) if course is None: f.close() return False for row in reader: if len(row) != 3: continue stud_id = int(row[0]) user = User.query.get(stud_id) if user is None: user = User(id=int(row[0]), name=row[1], email=row[2]) if not database.addItemSafelyToDB(user): continue if user not in course.ta_courses: print("ADDING TA") course.ta_courses.append(user) database.get_db().session.commit() f.close() return True
def index(): conn = get_db() if request.method == 'POST': date = request.form['date'] conn.execute('insert into log_date (entry_date) values (?)', [date]) conn.commit() results = conn.execute( 'select * from log_date order by entry_date desc').fetchall() totals_per_day = {} for day in results: totals_per_day[day['entry_date']] = {} food_in_that_day = conn.execute( 'select * from food where id in \ (select food_id from food_log_date where food_log_date.log_date_id = ?)', [day['id']]).fetchall() totals_per_day[day['entry_date']]['protein'] = reduce( (lambda x, y: x + y), map(lambda x: x['protein'], food_in_that_day), 0) totals_per_day[day['entry_date']]['carbs'] = reduce( (lambda x, y: x + y), map(lambda x: x['carbohydrates'], food_in_that_day), 0) totals_per_day[day['entry_date']]['fat'] = reduce( (lambda x, y: x + y), map(lambda x: x['fat'], food_in_that_day), 0) totals_per_day[day['entry_date']]['calories'] = reduce( (lambda x, y: x + y), map(lambda x: x['calories'], food_in_that_day), 0) return render_template('home.html', dates=get_dates(results), totals_per_day=totals_per_day)
def load_logged_in_user(): user_id = session.get('user_id') if user_id is None: g.user = None else: g.user = get_db().execute('SELECT * FROM user WHERE id = ?', (user_id, )).fetchone()
def ensure_user_coupled_to_course(self): """ Function that ensures a user is linked to the course with the right role. """ course = self.cache['course'] user = self.cache['user'] if course is None or user is None: return if self.lti_instance.is_student_in_course(): if user not in course.student_courses: course.student_courses.append(user) if self.lti_instance.is_teacher_in_course(): if user not in course.supervisors: course.supervisors.append(user) if self.lti_instance.is_teaching_assistant_in_course(): if user not in course.ta_courses: course.ta_courses.append(user) # Wrap this into a safe commit. database.get_db().session.commit()
def create_view(): error = None # Error: Not a post request if request.method != "POST": return create_error("Not a POST") user_conf = request.form #print(request.files) # Error: They didn't upload a ROM if "ROM" not in request.files: return create_error("No ROM") rom = request.files["ROM"] # Error: They didn't give the ROM a filename if rom.filename == "": return create_error("No ROM Filename") # Error: The ROM has a bad extension if not allowed_file(rom.filename, ROM_EXTENSIONS): return create_error("Bad ROM Extension") # Check the number of threads db = get_db() n_folders = db.execute( "SELECT value FROM requests WHERE key = \"n\"").fetchone() print("N Folders: {}".format(int(n_folders[0]))) # Error: Too many threads currently sleeping if int(n_folders[0]) >= current_app.config["MAX_FOLDERS"]: return create_error("Server is too busy") n_threads = db.execute( "SELECT value FROM requests WHERE key = \"k\"").fetchone() print("N Threads: {}".format(int(n_threads[0]))) if int(n_threads[0]) >= current_app.config["MAX_THREADS"]: return create_error("Server is too busy") # If we get here, no errors #print(request.form) # First, set up the folder where we will process this request save_folder, save_name = rom_interact.setup_valid_rom(rom, request.form) #print(save_folder) # Now, spawn a new process to do the randomization and manage the files rpath = current_app.config["RANDO_PATH"] rel_path = current_app.config["REL_PATH"] work_t = current_app.config["WORK_TIME"] wait_t = current_app.config["WAIT_TIME"] err_t = current_app.config["ERR_TIME"] p = multiprocessing.Process(target=rom_interact.handle_valid_rom, args=(rpath, rel_path, request.form, save_folder, save_name, db, work_t, wait_t, err_t)) p.start() wait_m = wait_t // 60 # Finally, render the template r = render_template("create.html", folder=os.path.basename(save_folder), link_time=wait_m) return r
def get_post(id, check_author=True): post = get_db().execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id, )).fetchone() if post is None: abort(404, "Post id {0} doesn't exist.".format(id)) if check_author and post['author_id'] != g.user['id']: abort(403) return post
def init_catalog(): db = get_db() query = Query(db) processor = Processor() if request.method == 'POST': ''' Initialize the database with default catalog provided by input ''' catalogs = processor.validate_json(request, catalog_validate_schema) success = query.load_all_catalogs(catalogs) response = processor.format_success_response(success) return response else: catalogs = query.read_all_catalogs() response = processor.format_success_response(catalogs) return response
def update_plugin(label_id, plugin_id): """ Change the assignment id of this plugin for this label. """ label = Label.query.get_or_404(label_id) plugin = label.get_plugin(plugin_id) if not plugin: return Iresponse.create_response({"error": "plugin not found"}, 200) plugin.assignment_id = request.get_json()['assignment_id'] try: db = database.get_db() db.session.commit() return Iresponse.create_response({"status": "success"}, 200) except Exception as e: print(e) return Iresponse.create_response({"status": "failure"}, 500)
def process_restock(): db = get_db() query = Query(db) processor = Processor() process_order = Orders() if request.method == 'POST': stocks = processor.validate_json(request, restock_validate_schema) success = query.update_stocks(stocks) process_order.process_backlog_queue() response = processor.format_success_response(success) return response else: stocks = query.read_all_stocks() response = processor.format_success_response(stocks) return response
def deactivate_plugin(label_id, plugin_id): """ Remove this plugin-label combination from the database to deactivate it. Note that dis also removes the assignment id which is stored in the pivot table. """ label = Label.query.get_or_404(label_id) plugin = label.get_plugin(plugin_id) if not plugin: return Iresponse.create_response({"error": "plugin not found"}, 200) try: db = database.get_db() db.session.delete(plugin) db.session.commit() return Iresponse.create_response({"status": "success"}, 200) except Exception as e: print(e) return Iresponse.create_response({"status": "failure"}, 500)
def view(date): conn = get_db() date_result = conn.execute( 'select id, entry_date from log_date where entry_date = ?', [date]).fetchone() if request.method == 'POST': if 'cancel' in request.form.keys(): conn.execute('delete from food_log_date where food_id=?', [request.form['cancel']]) conn.commit() else: conn.execute( 'insert into food_log_date (food_id, log_date_id) values (?, ?)', [request.form['food-select'], date_result['id']]) conn.commit() food_results = conn.execute('select id, name from food').fetchall() date_food_results = conn.execute( 'select * from food where id in \ (select food_id from food_log_date inner join log_date on food_log_date.log_date_id=?)', [date_result['id']]).fetchall() total_proteins = reduce((lambda x, y: x + y), map(lambda x: x['protein'], date_food_results), 0) total_carbs = reduce((lambda x, y: x + y), map(lambda x: x['carbohydrates'], date_food_results), 0) total_fat = reduce((lambda x, y: x + y), map(lambda x: x['fat'], date_food_results), 0) total_calories = reduce((lambda x, y: x + y), map(lambda x: x['calories'], date_food_results), 0) return render_template('day.html', dates=get_dates(date_result), food_list=food_results, date_food_list=date_food_results, total_proteins=total_proteins, total_calories=total_calories, total_carbs=total_carbs, total_fat=total_fat)
def app(): db_fd, db_path = tempfile.mkstemp() print("db_path: {}".format(db_path)) app = create_app({ 'TESTING': True, 'SQLALCHEMY_DATABASE_URI': 'sqlite:///' + db_path, }) db = get_db() # Create database and load test data # Create a new session for every test. with app.app_context(): init_db() yield app db.session.remove() db.drop_all() # Close the db data. os.close(db_fd) os.unlink(db_path)
def create(): if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_db() db.execute( 'INSERT INTO post (title, body, author_id)' ' VALUES (?, ?, ?)', (title, body, g.user['id'])) db.commit() return redirect(url_for('blog.index')) return render_template('blog/create.html')
def update(id): post = get_post(id) if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_db() db.execute('UPDATE post SET title = ?, body = ?' ' WHERE id = ?', (title, body, id)) db.commit() return redirect(url_for('blog.index')) return render_template('blog/update.html', post=post)
def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None user = db.execute('SELECT * FROM user WHERE username = ?', (username, )).fetchone() if user is None: error = 'Incorrect username.' elif not check_password_hash(user['password'], password): error = 'Incorrect password.' if error is None: session.clear() session['user_id'] = user['id'] return redirect(url_for('index')) flash(error) return render_template('auth/login.html')
def food(): conn = get_db() if request.method == 'POST': if request.form['submit'] == "Add": name = request.form['food-name'] proteins = int(request.form['protein-value']) carbs = int(request.form['carbs-value']) fat = int(request.form['fat-value']) calories = proteins * 4 + carbs * 4 + fat * 9 conn.execute( 'insert into food (name, protein, carbohydrates, fat, calories) values (?, ?, ?, ?, ?)', [name, proteins, carbs, fat, calories]) conn.commit() else: conn.execute('delete from food where id = ?', [request.form['submit']]) conn.commit() results = conn.execute('select * from food').fetchall() return render_template('add_food.html', food_list=results)
def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None if not username: error = 'Username is required.' elif not password: error = 'Password is required.' elif db.execute('SELECT id FROM user WHERE username = ?', (username, )).fetchone() is not None: error = 'User {} is already registered.'.format(username) if error is None: db.execute('INSERT INTO user (username, password) VALUES (?, ?)', (username, generate_password_hash(password))) db.commit() return redirect(url_for('auth.login')) flash(error) return render_template('auth/register.html')
def __init__(self): self._cutoff_mass = 1800 db = get_db() self._query = Query(db)
def delete(id): get_post(id) db = get_db() db.execute('DELETE FROM post WHERE id = ?', (id, )) db.commit() return redirect(url_for('blog.index'))
def index(): db = get_db() posts = db.execute('SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' ORDER BY created DESC').fetchall() return render_template('blog/index.html', posts=posts)