def addCourse(): ''' Add a new course to the course dashboard. ''' if 'username' not in login_session: return redirect(url_for('welcome')) form = CourseForm() if form.validate_on_submit(): title = form.title.data user_id = login_session['user_id'] description = form.description.data provider = form.provider.data website = form.website.data #If user uploaded an image file, ensure the filename is secure, #then save the file to the filesystem and create a path #to the file in the database. #http://flask.pocoo.org/docs/0.10/patterns/fileuploads/ file = form.image.data if file: filename = secure_filename(file.filename) if file and allowed_file(filename): newCourse = Course(title = request.form['title'], user_id = login_session['user_id'], description = request.form['description'], provider = request.form['provider'], website = request.form['website']) session.add(newCourse) session.commit() #The purpose of this line is to ensure that newCourse.id is #accessable - need it to name the image file on filesystem #http://stackoverflow.com/questions/1316952/sqlalchemy-flush-and-get-inserted-id session.refresh(newCourse) image_destination = 'static/course_images/%s_%s.%s' % (user_id, newCourse.id, get_file_extension(filename)) file.save(dst = image_destination) newCourse.image = image_destination session.commit() else: newCourse = Course(title = request.form['title'], user_id = login_session['user_id'], description = request.form['description'], provider = request.form['provider'], website = request.form['website'], image = None) session.add(newCourse) session.commit() flash('New course %s added!' % newCourse.title) return redirect(url_for('fullCourseList')) else: return render_template('newcourse.html', form = form)
def seed_database(fixture_filename='fixtures.json'): """ seed route, used to populate an empty database, this should only have to run the first time. """ providers, _ = base_query() if len(providers) != 0: pass else: import json with open(fixture_filename, 'rb') as f: fixtures = json.load(f) seed_providers = fixtures['providers'] for p in seed_providers: provider = Provider(name=p['name'], homepage_url=p['homepage_url']) db_session.add(provider) seed_courses = fixtures['courses'] for c in seed_courses: course = Course(name=c['name'], course_url=c['course_url'], thumbnail_url=c['thumbnail_url'], course_number=c['course_number'], description=c['description'], start_date=datetime.strptime( c['start_date'], '%Y-%m-%d'), featured=c['featured'], provider_id=c['provider_id']) db_session.add(course) try: db_session.commit() flash('Database seeded with fixture data.', 'warning') except Exception as e: flash('Something imploded. {}'.format(e), 'danger') return redirect(url_for('index'))
def new_course(): """Create a new course""" user = get_user_info(login_session) if request.method == 'POST': name = request.form['name'] description = request.form['description'] course_name_list = [] # Check if user input name and description if name and description: courses = session.query(Course).order_by(asc(Course.name)) for c in courses: lowcase_name = c.name.lower() course_name_list.append(lowcase_name) # Check if the name of the course already exist in the database if name.lower() in course_name_list: flash("The %s course is already exists" % name) return render_template('newCourse.html', description=description, name=name) else: created_course = Course(name=name, description=description, user_id=user.id, created_by=user.name) session.add(created_course) session.commit() flash('New Course %s Successfully Created' % created_course.name) return redirect(url_for('show_courses')) else: flash("We need both name and description") return render_template('newCourse.html') else: return render_template('newCourse.html')
def parse_course_form(form): """ returns a new Course object from submitted form data POST requests """ form = dict(form) if form['course-thumbnail-url'][0] == "": form['course-thumbnail-url'][ 0] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/b/b8/MOOC_-_Massive_Open_Online_Course_logo.svg/799px-MOOC_-_Massive_Open_Online_Course_logo.svg.png' if not form.has_key('course-featured'): form['course-featured'] = [False] else: form['course-featured'] = [True] try: start_date = datetime.strptime(form['course-start-date'][0], '%Y-%m-%d') except ValueError as e: start_date = datetime.now() flash( 'You didn\'t enter a valid date (how\'d you manage that, anyway?). I picked today. Yay!', 'warning') course = Course(name=form['course-name'][0], course_url=form['course-url'][0], thumbnail_url=form['course-thumbnail-url'][0], course_number=form['course-number'][0], description=form['course-description'][0], start_date=start_date, featured=form['course-featured'][0], provider_id=form['course-provider'][0]) return course
def newCourse(): if request.method == 'POST': newCourse = Course(name = request.form['name']) session.add(newCourse) session.commit() flash("New Course created!") return redirect(url_for('showCourses')) else: return render_template('new_course.html')
def newCourse(): if request.method == 'POST': newCourse = Course(name=request.form['name']) session.add(newCourse) session.commit() flash("A New Course Has Been Created", "success") return redirect(url_for('listCourse')) else: return render_template('newcourse.html')
def newCourse(): if request.method == 'POST': newCourse = Course( name=request.form['name'], user_id=login_session['user_id']) session.add(newCourse) flash('New Course is %s Created Successfully' % newCourse.name) session.commit() return redirect(url_for('showCourses')) else: return render_template('newCourse.html')
def newCourse(name): """Create new menu item course""" session = connect() # Save the new menu item course newCourse = Course(name=name) session.add(newCourse) session.commit() closeConnection(session)
def showCourses(): if 'username' not in login_session: return redirect('/login') if request.method == 'POST': user = session.query(UserTable).filter_by( email=login_session['email']).one() newCourse = Course(name=request.form['newCourseName'], user_id=user.id) session.add(newCourse) # flash('New Course %s Successfully Created' % newCourse.name) session.commit() courses = session.query(Course).order_by(asc(Course.name)) return render_template('courses.html', courses=courses)
def newCourse(): if checkAuth('New'): this_user = db.query(User).filter_by(id=session['user_id']).first() if request.method == 'POST': file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename).split(".") cloudinary.uploader.upload(request.files['file'], public_id=filename[0]) thisCourse = Course(name=request.form['name'], description=request.form['description'], category=request.form['category'], picture_name=filename[0], user_id=this_user.id) else: thisCourse = Course(name=request.form['name'], description=request.form['description'], category=request.form['category'], user_id=this_user.id) db.add(thisCourse) db.commit() flash("New Course Created", "success") return redirect(url_for('courses')) else: return render_template('new_course.html') else: flash("Please Log In", "danger") return redirect(url_for('courses'))
def newCourse(inst_id): if 'username' not in login_session: return redirect('/login') if request.method == 'POST': new_course = Course(name=request.form['name'], description=request.form['description'], institute_id=inst_id, user_id=login_session['user_id']) session.add(new_course) session.commit() return redirect(url_for('showCourses', inst_id=inst_id)) else: return render_template('newcourse.html', inst_id=inst_id)
def newCourse(subject_id): if 'username' not in login_session: return redirect('/login') subject = session.query(Subject).filter_by(id=subject_id).one() if request.method == 'POST': user = getUserID(login_session['email']) newCourse = Course(name=request.form['name'], summary=request.form['summary'], subject_id=subject_id, user_id=user) session.add(newCourse) session.commit() flash('New Course %s Successfully Created!' % (newCourse.name)) return redirect(url_for('showCourses', subject_id=subject_id)) else: return render_template('newCourse.html', subject_id=subject_id)
def newCourse(): """Creates a new course""" if request.method == 'POST': level = session.query(Level).filter_by( name=request.form['level']).one() newCourse = Course(name=request.form['name'], provider=request.form['provider'], review=request.form['review'], link=request.form['link'], description=request.form['description'], user_id=login_session['user_id'], level_id=level.id) session.add(newCourse) session.commit() flash('New Course %s Successfully Created' % newCourse.name) return redirect(url_for('showLevel', level_name=level.name)) else: return render_template('new_course.html')
def new_course(): format_date = "%Y-%m-%d" if all(item in request.json.keys() for item in ["title", "start_date", "end_date", "amount"]): try: new_course_item = Course(title=request.json['title'], start_date=datetime.datetime.strptime(request.json['start_date'], format_date), end_date=datetime.datetime.strptime(request.json['end_date'], format_date), amount=request.json['amount']) session.add(new_course_item) session.commit() courses = session.query(Course).all() result = courses_schema.dump(courses) return jsonify(result) except exc.SQLAlchemyError: return {"error": "Incorrect value. Please try another"} else: return {"error": "Not all values are present"}
def parse_course_form(form): """ returns a new Course object from submitted form data POST requests """ form = dict(form) if form['course-thumbnail-url'][0] == "": form['course-thumbnail-url'][ 0] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/b/b8/MOOC_-_Massive_Open_Online_Course_logo.svg/799px-MOOC_-_Massive_Open_Online_Course_logo.svg.png' if not form.has_key('course-featured'): form['course-featured'] = [False] else: form['course-featured'] = [True] course = Course(name=form['course-name'][0], course_url=form['course-url'][0], thumbnail_url=form['course-thumbnail-url'][0], course_number=form['course-number'][0], description=form['course-description'][0], start_date=datetime.strptime(form['course-start-date'][0], '%Y-%m-%d'), featured=form['course-featured'][0], provider_id=form['course-provider'][0]) return course
def new_course(): """ Allow logged users to create a course """ if request.method == 'POST': thumbnail_url = str(request.form['thumbnail_url']) if thumbnail_url == "": thumbnail_url = "https://placehold.it/300x200" course = Course(name=request.form['name'], description=request.form['description'], number=request.form['number'], url=request.form['url'], thumbnail_url=thumbnail_url, category_id=request.form['category_id'], user=getUserInfo(login_session['user_id'])) session.add(course) try: session.commit() flash('New course created!', 'success') return redirect(url_for('view_course', course_id=course.id)) except Exception as e: flash('Something went wrong. {}'.format(e), 'danger') return redirect(url_for('index')) else: categories = session.query(Category).all() course = { 'id': None, 'name': "", 'description': "", 'number': "", 'url': "", 'thumbnail_url': "", 'category_id': None, } return render_template('edit_course.html', categories=categories, course=course, form_action=url_for('new_course'))
session = DBSession() # add to database: student1 = Student(name="Sam Wilson") session.add(student1) student2 = Student(name="Alicia Carter") session.add(student2) student3 = Student(name="Michael Fox") session.add(student3) student4 = Student(name="Anna Smith") session.add(student4) course1 = Course(name="Algebra I", teacher="Mr. Alberts") course1.students.append(student1) course1.students.append(student2) course1.students.append(student3) course1.students.append(student4) course1 = Course(name="Algebra II", teacher="Mr. Wu") course2 = Course(name="Calculus", teacher="Mr. Graham") course3 = Course(name="Geometry", teacher="Mrs. Stein") course4 = Course(name="Chemistry", teacher="Mr. Dalton") course4.students.append(student1) course5 = Course(name="Spanish I", teacher="Mrs. Ramirez")
from sqlalchemy.sql import exists engine = create_engine('sqlite:///restaurant.db') Base.metadata.create_all(engine) DBSession = sessionmaker(bind=engine) session = DBSession() C_1 = Restaurant(name='1st_restaurant') C_2 = Restaurant(name='2nd_restaurant') C_3 = Restaurant(name='3rd_restaurant') SC_11 = Course(name='London', restaurant_id='1') SC_12 = Course(name='Paris', restaurant_id='1') SC_21 = Course(name='Water', restaurant_id='2') SC_22 = Course(name='Earth', restaurant_id='2') SC_31= Course(name='Panda', restaurant_id='3') SC_32 = Course(name='Tiger', restaurant_id='3') session.add(C_1) session.commit() session.add(C_2) session.commit() session.add(C_3) session.commit() session.add(SC_11) session.commit() session.add(SC_12)
# 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() session = DBSession() # User user1 = User(name="Marco Pires", email="*****@*****.**", picture="marco.jpg", password="******") session.add(user1) session.commit() # Courses course1 = Course(name="Entree") session.add(course1) session.commit() course2 = Course(name="Appetizer") session.add(course2) session.commit() course3 = Course(name="Dessert") session.add(course3) session.commit() course4 = Course(name="Beverage")
# Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # 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() session = DBSession() # Establishing Meals course1 = Course(name="Breakfast") session.add(course1) session.commit() food1 = FoodItem(name="Pancakes", description="A fluffy circular sweet bread.", course=course1) session.add(food1) session.commit() course2 = Course(name="Lunch") session.add(course2) session.commit() food2 = FoodItem(name="Chicken sandwich",
User1 = User(name="Dr Strange", email="*****@*****.**", picture="https://cnet1.cbsistatic.com/img/OKR2sNNACWPsltN4y5i13tk" "9biw=/936x527/2016/10/24/4c7b8f36-6f0e-427b-9884-59e1f72" "09591/strange1.jpg") session.add(User1) session.commit() subject1 = Subject(user_id=1, name="Physics") session.add(subject1) session.commit() course1 = Course(user_id=1, name="Algebra-Baed Physics 1", summary="Newtonian mechanics and waves.", subject=subject1) session.add(course1) session.commit() course2 = Course(user_id=1, name="Algebra-Based Physics 2", summary="Electricity, magnetism, and light", subject=subject1) session.add(course2) session.commit() course3 = Course(user_id=1, name="Calculus-Based Physics 1",
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()""" session = DBSession() """Create First User""" User1 = User(name="Ravi Teja", email="*****@*****.**", picture='https://lh3.googleusercontent.com/' '-ktSKbvcydmA/AAAAAAAAAAI/' 'AAAAAAAAY78/1Hr7lhAKhTg/s60-p-rw-no-il/photo.jpg') session.add(User1) session.commit() """Menu for Java""" course1 = Course(user_id=1, name="Java") session.add(course1) session.commit() menuItem1 = MenuItem(user_id=1, name="Core Java", description='''Our core Java programming tutorial ' 'is designed for students and working professionals.' 'Java is an object-oriented, class-based, concurrent,' 'secured and general-purpose ' 'computer-programming language.' ' It is a widely used robust technology.''', price="1000", picture="https://tinyurl.com/yyqe24ld", course=course1) session.add(menuItem1) session.commit()
engine = create_engine('sqlite:///usr/local/WB/data/course-collection.db') # Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. session = DBSession() one_weeks = datetime.now() + timedelta(days=7) two_weeks = datetime.now() + timedelta(days=14) bookOne = Course(title="Math", start_date=datetime.now(), end_date=one_weeks, amount=45) bookTwo = Course(title="Literature", start_date=datetime.now(), end_date=one_weeks, amount=55) bookThree = Course(title="Art", start_date=datetime.now(), end_date=two_weeks, amount=30) session.add(bookOne) session.commit() session.add(bookTwo) session.commit()
# 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() session = DBSession() # Database Templates # User Template User1 = User(name="Jared Nachman", email="*****@*****.**", picture='...') session.add(User1) session.commit() # Coruse Template course1 = Course(name="Appetizer") session.add(course1) session.commit() recipe1 = Recipe( user_id=1, name="Stuffed Mushrooms", total_time="35 Minutes", prep_time="10 Minutes", cook_time="25 Minutes", difficulty="3", directions= "Heat oven on high and combine all ingreients in a bowl Then drizzle olive oil on mushrooms on a baking pan Finally use a spoon and fill the mushrooms with the filling", ingredients="Mushrooms, Bread Crumbs, Garlic, Mint, Black, Pepper", output="28 Mushrooms",
engine = create_engine('postgresql://*****:*****@localhost/catalog') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() current_user = User(name='System Administrator', email='*****@*****.**') session.add(current_user) session.commit() fixtures = json.loads(open('fixtures.json', 'rb').read()) for t in fixtures['categories']: category = Category(name=t['name'], description=t['description'], url=t['url']) session.add(category) session.commit() for c in fixtures['courses']: course = Course(name=c['name'], description=c['description'], number=c['number'], url=c['url'], thumbnail_url=c['thumbnail_url'], category_id=c['category_id'], user=current_user) session.add(course) session.commit()
intermediate = Level(user_id=1, name="Intermediate") session.add(intermediate) session.commit() advanced = Level(user_id=1, name="Advanced") session.add(advanced) session.commit() # courses for Beginner course = Course( user_id=1, name="An Introduction to Interactive Programming in Python (Part 1)", description= """This two-part course is designed to help students with very little or no computing background learn the basics of building simple interactive applications. Our language of choice, Python, is an easy-to learn, high-level computer language that is used in many of the computational courses offered on Coursera. To make learning Python easy, we have developed a new browser-based programming environment that makes developing interactive applications in Python simple. These applications will involve windows whose contents are graphical and respond to buttons, the keyboard and the mouse.""", review="2973", link= "https://www.class-central.com/mooc/408/coursera-an-introduction-to-interactive-programming-in-python-part-1", provider="Rice University via Coursera", level=beginner) session.add(course) session.commit() course = Course( user_id=1, name="Programming for Everybody (Getting Started with Python)", description= """This course aims to teach everyone the basics of programming computers using Python. We cover the basics of how one constructs a program from a series of simple instructions in Python. The course has no pre-requisites and avoids all but the simplest mathematics. Anyone with moderate computer experience should be able to master the materials in this course. This course will cover Chapters 1-5 of the textbook “Python for Everybody”. Once a student completes this course, they will be ready to take more advanced programming courses. This course covers Python 3. """, review="1602", link= "https://www.class-central.com/mooc/4319/coursera-programming-for-everybody-getting-started-with-python",
engine = create_engine(os.environ.get('LOCAL_DB_URI_MATH')) # Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # 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() session = DBSession() course1 = Course(grade="6 - 8", course="Geometry") session.add(course1) session.commit() course2 = Course(grade="6 - 8", course="Trigonometry") session.add(course2) session.commit() course3 = Course(grade="K - 5", course="Elementary Math") session.add(course3) session.commit() course4 = Course(grade="K - 5", course="Basic Math") session.add(course4) session.commit()
defaultCat6 = Categories(name="Science") session.add(defaultCat6) defaultCat7 = Categories(name="Psychology") session.add(defaultCat7) defaultCat8 = Categories(name="Business") session.add(defaultCat8) defaultCat9 = Categories(name="Design") session.add(defaultCat9) defaultCat10 = Categories(name="History") session.add(defaultCat10) # create items default_Course = Course( title="How to make vegan steak burger", picture= "https://www.bestsoccerbuys.com/content/images/thumbs/0000447_classic-collection-soccer-ball-black-white-butyl-bladder-japanese-pu-cover.jpeg", duration="3 months", description= "Whether you're vegan or simply exploring, this course will help you make an amazing meatless steak burger!", category_ref=defaultCat4.id, creator_ref=defaultUser.id) session.add(default_Course) session.commit() print("Great! Default data loaded!")
# Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # 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() session = DBSession() # Courses session.add(Course(name="Not Specified")) session.add(Course(name="Entree")) session.add(Course(name="Appetizer")) session.add(Course(name="Salads")) session.add(Course(name="Soup")) session.add(Course(name="Dessert")) session.add(Course(name="Beverage")) session.commit() # Menu for UrbanBurger restaurant = Restaurant(name="Urban Burger") session.add(restaurant) session.commit() course = session.query(Course).filter_by(name="Entree").one() session.add(
# Create dummy user User1 = User(name="Robo Barista", email="*****@*****.**", picture='https://pbs.twimg.com/profile_images/2671170543/' '18debd694829ed78203a5a36dd364160_400x400.png') session.add(User1) session.commit() # --- inst_rob = Institute(name="Institute of Robotics", user_id=1) session.add(inst_rob) session.commit() pro_con = Course(user_id=1, name="Process Control", description="The Control of Processes", institute=inst_rob) session.add(pro_con) session.commit() robotics = Course(user_id=1, name="Robotics", description="The Science of Robots", institute=inst_rob) session.add(robotics) session.commit() # --- inst_automotive = Institute(user_id=1, name="Institute of Automotive Engineering") session.add(inst_automotive)
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Course, Recipe, Ingredients, Directions, Base engine = create_engine('sqlite:////var/www/healthyRecipes/healthyRecipes/healthyRecipes.db?check_same_thread=False') DBSession = sessionmaker(bind=engine) session = DBSession() # -------------------------------- # # Add all Courses # # -------------------------------- # # Add Soup to courses soup = Course( id='1', name='Soup' ) session.add(soup) session.commit() # Add Side Dish to courses side_dish = Course( id="2", name="Side Dish" ) session.add(side_dish) session.commit() # Add Appetizer to courses appetizer = Course(