def createNewItem(): """Allow users to create a new item in the catalog.""" if 'username' not in login_session: return redirect('/login') session = dbconnect() if request.method == 'POST': if not request.form['name']: flash("New item not created: No name provided.") return redirect(url_for('showCatalogHome')) if request.form['name'] == "items": flash("Error: Can't have an item called 'items'.") return redirect(url_for('showCatalogHome')) # make sure item names are unique qry = session.query(Item).filter(Item.name == request.form['name']) already_exists = (session.query(literal(True)). filter(qry.exists()).scalar()) if already_exists is True: flash("Error: There is already an item with the name '%s'" % request.form['name']) session.close() return redirect(url_for('showCatalogHome')) category = (session.query(Category) .filter_by(name=request.form['category']).one()) add_new_item = Item(category=category, name=request.form['name'], description=request.form['description'], quantity=request.form['quantity'], price=request.form['price'], user_id=login_session['user_id']) try: createimagefile = request.files['file'] except Exception: createimagefile = None try: createimageurl = request.form['image_url'] except Exception: createimageurl = None if createimagefile and allowedFile(createimagefile.filename): filename = secure_filename(createimagefile.filename) if os.path.isdir(app.config['UPLOAD_FOLDER']) is False: os.mkdir(app.config['UPLOAD_FOLDER']) createimagefile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) add_new_item.image_filename = filename elif createimageurl: add_new_item.image_url = request.form['image_url'] session.add(add_new_item) session.commit() flash("New Item successfully created!") category_name = category.name item_name = add_new_item.name session.close() return redirect(url_for('showItem', category_name=category_name, item_name=item_name)) else: categories = session.query(Category).all() # See, if any, which category page new item was click on. ref_category = None if request.referrer and 'catalog' in request.referrer: ref_url_elements = request.referrer.split('/') if len(ref_url_elements) > 5: ref_category = ref_url_elements[4] session.close() return render_template('create_new_item.html', categories=categories, ref_category=ref_category)
def create_item(): """Allow users to create a new item in the catalog.""" if 'username' not in login_session: return redirect('/login') session = connect_to_database() if request.method == 'POST': if not request.form['name']: flash("New paper not created: No name provided.") return redirect(url_for('show_homepage')) if request.form['name'] == "items": # Can't have an item called "items" as this is a route. flash("Error: Can't have a paper called 'items'.") return redirect(url_for('show_homepage')) # Enforce rule that item names are unique qry = session.query(Item).filter(Item.name == request.form['name']) already_exists = (session.query(literal(True)). filter(qry.exists()).scalar()) if already_exists is True: flash("Error: There is already a paper with the name '%s'" % request.form['name']) session.close() return redirect(url_for('show_homepage')) category = (session.query(Category) .filter_by(name=request.form['category']).one()) new_item = Item(category=category, name=request.form['name'], description=request.form['description'], quantity=request.form['quantity'], user_id=login_session['user_id']) # Process optional item image image_file = request.files['file'] if image_file and allowed_file(image_file.filename): filename = secure_filename(image_file.filename) if os.path.isdir(app.config['UPLOAD_FOLDER']) is False: os.mkdir(app.config['UPLOAD_FOLDER']) image_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) new_item.image_filename = filename elif request.form['image_url']: new_item.image_url = request.form['image_url'] session.add(new_item) session.commit() flash("New paper successfully added!") category_name = category.name item_name = new_item.name session.close() return redirect(url_for('show_item', category_name=category_name, item_name=item_name)) else: categories = session.query(Category).all() # See, if any, which category page new item was click on. ref_category = None if request.referrer and 'catalog' in request.referrer: ref_url_elements = request.referrer.split('/') if len(ref_url_elements) > 5: ref_category = ref_url_elements[4] session.close() return render_template('new_item.html', categories=categories, ref_category=ref_category)
def create_item(): """Allow users to create a new item in the catalog.""" if 'username' not in login_session: return redirect('/login') session = connect_to_database() if request.method == 'POST': if not request.form['name']: flash("New vehicle not created: No name provided.") return redirect(url_for('show_homepage')) if request.form['name'] == "items": # Can't have an item called "items" as this is a route. flash("Error: Can't have an vehicle called 'items'.") return redirect(url_for('show_homepage')) # Enforce rule that item names are unique qry = session.query(Item).filter(Item.name == request.form['name']) already_exists = (session.query(literal(True)).filter( qry.exists()).scalar()) if already_exists is True: flash("Error: There is already an vehicle with the name '%s'" % request.form['name']) session.close() return redirect(url_for('show_homepage')) category = (session.query(Category).filter_by( name=request.form['category']).one()) new_item = Item(category=category, name=request.form['name'], description=request.form['description'], user_id=login_session['user_id']) if request.form['image_url']: new_item.image_url = request.form['image_url'] session.add(new_item) session.commit() flash("New vehicle successfully created!") category_name = category.name item_name = new_item.name session.close() return redirect( url_for('show_item', category_name=category_name, item_name=item_name)) else: categories = session.query(Category).all() # See, if any, which category page new item was click on. ref_category = None if request.referrer and 'catalog' in request.referrer: ref_url_elements = request.referrer.split('/') if len(ref_url_elements) > 5: ref_category = ref_url_elements[4] session.close() return render_template('new_item.html', categories=categories, ref_category=ref_category)
def populate_database(): """Populate the item catalog database some initial content.""" session = connect_to_database() # Make sure the database is empty before running this inital data dump. category_count = session.query(func.count(Category.id)).scalar() if category_count > 0: session.close() return # Create the six categories animals fall in to. category1 = Category(name="Mammals") session.add(category1) session.commit() category2 = Category(name="Birds") session.add(category2) session.commit() category3 = Category(name="Fish") session.add(category3) session.commit() category4 = Category(name="Reptiles") session.add(category4) session.commit() category5 = Category(name="Amphibians") session.add(category5) session.commit() category6 = Category(name="Arthropods") session.add(category6) session.commit() # Create a dummy user for these initial items user1 = User(name="Bob Fossil", email="*****@*****.**") session.add(user1) session.commit() # Create some mammals item1 = Item( user=user1, category=category1, name="Polar Bear", description=( "The polar bear is a carnivorous bear whose native range lies " "largely within the Arctic Circle, encompassing the Arctic Ocean, " "its surrounding seas and surrounding land masses. It is a large " "bear, approximately the same size as the omnivorous Kodiak bear." ), quantity=3, image_url="https://upload.wikimedia.org/wikipedia/commons/6/66/Polar_Bear_-_Alaska_(cropped).jpg" ) session.add(item1) session.commit() item2 = Item( user=user1, category=category1, name="Elephant", description=( "Elephants are large mammals of the family Elephantidae and the " "order Proboscidea. Two species are traditionally recognised, the " "African elephant and the Asian elephant, although some evidence " "suggests that African bush elephants and African forest elephants " "are separate species." ), quantity=4, image_url="http://res.freestockphotos.biz/pictures/10/10004-an-elephant-in-the-wild-pv.jpg" ) session.add(item2) session.commit() # Create some Birds item3 = Item( user=user1, category=category2, name="Kingfisher", description=( "Kingfishers are a group of small to medium-sized brightly colored " "birds in the order Coraciiformes. There are roughly 90 species of " "kingfisher. All have large heads, long, sharp, pointed bills, " "short legs, and stubby tails. Most species have bright plumage " "with little differences between the sexes." ), quantity=2, image_url="https://upload.wikimedia.org/wikipedia/commons/d/de/Common_Kingfisher_(Alcedo_atthis_taprobana)_-_Male_-_Flickr_-_Lip_Kee.jpg" ) session.add(item3) session.commit() item4 = Item( user=user1, category=category2, name="Blue Tit", description=( "The Eurasian blue tit is a small passerine bird in the tit family " "Paridae. The bird is easily recognisable by its blue and yellow " "plumage, but various authorities dispute their scientific " "classification." ), quantity=7, image_url="https://upload.wikimedia.org/wikipedia/commons/6/65/Blue_Tit_-_flickr.jpg" ) session.add(item4) session.commit() # Create some fish item5 = Item( user=user1, category=category3, name="Swordfish", description=( "Swordfish, also known as broadbills in some countries, are large, " "highly migratory, predatory fish characterized by a long, flat " "bill. They are a popular sport fish of the billfish category, " "though elusive. Swordfish are elongated, round-bodied, and lose " "all teeth and scales by adulthood." ), quantity=4, image_url="https://upload.wikimedia.org/wikipedia/commons/f/f6/Xiphias_gladius2.jpg" ) session.add(item5) session.commit() item6 = Item( user=user1, category=category3, name="Whale Shark", description=( "The whale shark is a slow-moving filter feeding shark and the " "largest known extant fish species. The largest confirmed " "individual had a length of 12.65 m (41.50 ft) and a weight of " "about 21.5 metric tons (47,000 lb), and unconfirmed reports of " "considerably larger whale sharks exist. Claims of individuals " "over 14 m (46 ft) long and weighing at least 30 metric tons " "(66,000 lb) are not uncommon." ), quantity=1, image_url="https://upload.wikimedia.org/wikipedia/commons/thumb/5/57/Male_whale_shark_at_Georgia_Aquarium_crop.jpg/1024px-Male_whale_shark_at_Georgia_Aquarium_crop.jpg" ) session.add(item6) session.commit() # Create some reptiles item7 = Item( user=user1, category=category4, name="Saltwater Crocodile", description=( "The saltwater crocodile is the largest of all living reptiles, " "as well as the largest terrestrial and riparian predator in the " "world. The males of this species can reach sizes up to 6.3 m " "(20.7 ft) and weigh up to 1,360 kg (3,000 lb). However, an adult " "male saltwater crocodile is generally between 4.3 and 5.2 m (14 " "and 17 ft) in length and weighs 400 to 1,000 kg (880-2,200 lb), " "rarely growing larger." ), quantity=2, image_url="https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Saltwater_crocodile.jpg/640px-Saltwater_crocodile.jpg" ) session.add(item7) session.commit() item8 = Item( user=user1, category=category4, name="Burmese Python", description=( "The Burmese python is one of the five largest species of snakes " "in the world (about the third-largest as measured either by " "length or weight). It is native to a large variation of tropic " "and subtropic areas of South and Southeast Asia. Until 2009, it " "was considered a subspecies of Python molurus, but now is " "recognized as belonging to a distinct species." ), quantity=2, image_url="https://upload.wikimedia.org/wikipedia/commons/thumb/6/62/Burmese_Python_02.jpg/640px-Burmese_Python_02.jpg" ) session.add(item8) session.commit() # Create some amphibians item9 = Item( user=user1, category=category5, name="Golden Poison Frog", description=( "The golden poison frog, also known as the golden frog, golden " "poison arrow frog, or golden dart frog, is a poison dart frog " "endemic to the Pacific coast of Colombia. Its optimal habitat is " "the rainforest with high rain rates (5 m or more per year), " "altitudes between 100 and 200 m, temperatures of at least 26C, " "and relative humidity of 80-90%." ), quantity=2, image_url="https://upload.wikimedia.org/wikipedia/commons/9/9a/Phyllobates_terribilis_climbing_on_leaves.png" ) session.add(item9) session.commit() item10 = Item( user=user1, category=category5, name="Glass Frog", description=( "The glass frogs (or glassfrogs) are frogs of the amphibian family " "Centrolenidae (order Anura). While the general background " "coloration of most glass frogs is primarily lime green, the " "abdominal skin of some members of this family is translucent. The " "internal viscera, including the heart, liver, and " "gastrointestinal tract, are visible through the skin, hence the " "common name." ), quantity=4, image_url="https://c1.staticflickr.com/7/6143/5991036083_b2a7f8d894_b.jpg" ) session.add(item10) session.commit() # Create some arthropods item11 = Item( user=user1, category=category6, name="Fire Ant", description=( "Fire ant is the common name for several species of ants in the " "genus Solenopsis. They are however only a minority in the genus, " "which includes over 200 species of Solenopsis worldwide." ), quantity=200, image_url="https://c2.staticflickr.com/4/3614/3469703353_9020c24f36.jpg" ) session.add(item11) session.commit() item12 = Item( user=user1, category=category6, name="Swallowtail Butterfly", description=( "Swallowtail butterflies are large, colorful butterflies in the " "family Papilionidae, and include over 550 species. Though the " "majority are tropical, members of the family inhabit every " "continent except Antarctica." ), quantity=5, image_url="https://upload.wikimedia.org/wikipedia/commons/f/fe/Swallowtail_Butterfly_(Papilio_machaon)_-_geograph.org.uk_-_854088.jpg" ) session.add(item12) session.commit() session.close() print "Populated database with some animals..."
def populate_database(): """Populate the item catalog database some initial content.""" session = connect_to_database() # Make sure the database is empty before running this inital data dump. category_count = session.query(func.count(Category.id)).scalar() if category_count > 0: session.close() return # Create the six categories animals fall in to. category1 = Category( name="HTML&CSS", about= "HyperText Markup Language (HTML) is a markup language for creating webpages. Webpages are usually viewed in a web browser. They can include writing, links, pictures, and even sound and video. HTML is used to mark and describe each of these kinds of content so the web browser can show them correctly.", linkCat="https://www.w3.org/html/", linkCat2="https://www.w3.org/Style/CSS/", imageCat="fab fa-html5", imageCat2="fab fa-css3-alt") session.add(category1) session.commit() category2 = Category( name="JavaScript", about= "JavaScript (JS) is a lightweight interpreted or JIT-compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB and Adobe Acrobat. JavaScript is a prototype-based, multi-paradigm, dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles", linkCat="https://developer.mozilla.org/en-US/docs/Web/JavaScript", imageCat="fab fa-js-square") session.add(category2) session.commit() category3 = Category( name="React.js", about= "React is a JavaScript library for building user interfaces. It is maintained by Facebook and a community of individual developers and corporations.", linkCat="https://reactjs.org/", imageCat="fab fa-react") session.add(category3) session.commit() category4 = Category( name="Node.js", about= "Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code server-side.", linkCat="https://nodejs.org/", imageCat="fab fa-node") session.add(category4) session.commit() category5 = Category( name="Python", about= "Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace.", linkCat="https://www.python.org/", imageCat="fab fa-python") session.add(category5) session.commit() category6 = Category( name="APIs", about= "API is a set of subroutine definitions, protocols, and tools for building application software." ) session.add(category6) session.commit() category7 = Category( name="Databases", about= "A database is an organized collection of data. A relational database, more restrictively, is a collection of schemas, tables, queries, reports, views, and other elements.", imageCat="fas fa-database") session.add(category7) session.commit() category8 = Category( name="OAuth", about= "OAuth (Open Authorization) is an open standard for token-based authentication and authorization on the Internet. OAuth, which is pronounced oh-auth, allows an end user's account information to be used by third-party services, such as Facebook, without exposing the user's password.", linkCat="https://oauth.net") session.add(category8) session.commit() category9 = Category( name="Git", about= "Git is a version control system for tracking changes in computer files and coordinating work on those files among multiple people.", linkCat="https://git-scm.com/", imageCat="fab fa-git") session.add(category9) session.commit() # Create a user for these initial items user1 = User(name="Irina Serova", email="*****@*****.**") session.add(user1) session.commit() # Create some items item1 = Item( user=user1, category=category1, name="Learn HTML", description= ("Learn the basics of HTML with this interactive Codecademy course. The introduction here gives an overview of the structure, purpose, and syntax of the language." ), duration="2 to 4 hours", level="BEGINNER", image_url= "https://production.cdmycdn.com/webpack/3d7c19cebe85b8d870e6d2c181dec922.svg", link="https://www.codecademy.com/learn/learn-html") session.add(item1) session.commit() item2 = Item( user=user1, category=category1, name="Learn CSS", description=( "Elephants are large mammals of the family Elephantidae and the " "order Proboscidea. Two species are traditionally recognised, the " "African elephant and the Asian elephant, although some evidence " "suggests that African bush elephants and African forest elephants " "are separate species."), duration="8 to 16 hours", level="INTERMEDIATE", image_url= "https://production.cdmycdn.com/webpack/9522085449ef048604ca3f5fa8d1bc27.svg", link="https://www.codecademy.com/learn/learn-css") session.add(item2) session.commit() item3 = Item( user=user1, category=category2, name="Learn JavaScript", description= ("Learn the fundamentals of JavaScript, the programming language of the web." ), duration="4 to 8 hours", level="INTERMEDIATE", image_url= "https://production.cdmycdn.com/webpack/fbac2e163a79bceb56b5dbabe6c74945.png", link="https://www.codecademy.com/learn/learn-javascript") session.add(item3) session.commit() item5 = Item( user=user1, category=category3, name="Learn ReactJS: Part I", description= ("Continue your learning by starting with Learn ReactJS: Part I Build powerful interactive applications with this popular JavaScript library." ), duration="8 to 16 hours", level="INTERMEDIATE", image_url= "https://production.cdmycdn.com/webpack/d38587f67ab102541186df1c157597d1.svg", link="https://www.codecademy.com/learn/react-101") item4 = Item( user=user1, category=category4, name="NODESCHOOL", description= ("Open source workshops that teach web software skills. Do them on your own or at a workshop nearby." ), duration="8 to 16 hours", level="INTERMEDIATE", image_url="https://nodeschool.io/images/schoolhouse.svg", link="https://nodeschool.io") session.add(item4) session.commit() session.add(item5) session.commit() item6 = Item( user=user1, category=category5, name="Python", description= ("Learn Python fundamentals that set you up to work in web development and machine learning." ), duration="8 to 16 hours", level="INTERMEDIATE", image_url= "https://production.cdmycdn.com/webpack/4bef5020e69a6464ebd9dabe087cb809.svg", link="https://www.codecademy.com/learn/learn-python") session.add(item6) session.commit() item7 = Item( user=user1, category=category6, name="Learn API!", description=("Learn how to use the YouTube API!"), duration="8 to 16 hours", level="BEGINNER", image_url= "https://s3.amazonaws.com/codecademy-production/original/50ecea3ba778dddcd50001d2_871712554.png", link="https://www.codecademy.com/en/tracks/youtube") session.add(item7) session.commit() item8 = Item( user=user1, category=category7, name="Getting Started with PostgreSQL on Mac OSX", description= ("This tutorial will teach you how to set up, configure, and use PostgreSQL on MacOSX 10.7 (Lion) and above. You will need at least a basic level of comfort using the command line using either the MacOSX built-in terminal, iTerm2, Zsh, or something similar." ), duration="to 1 hour", level="BEGINNER", image_url= "https://process.filestackapi.com/cache=expiry:max/resize=width:1050/compress/Vx31ILRQRSO5fBiMSvEg", link= "https://www.codementor.io/engineerapart/getting-started-with-postgresql-on-mac-osx-are8jcopb" ) session.add(item8) session.commit() # Create some amphibians item9 = Item( user=user1, category=category8, name="OAuth2 with GitHub", description=("Learn OAuth2 with the GitHub API"), duration="2 to 4 hours", level="BEGINNER", image_url= "https://process.filestackapi.com/cache=expiry:max/resize=width:1050/compress/Vx31ILRQRSO5fBiMSvEg", link= "https://www.codementor.io/engineerapart/getting-started-with-postgresql-on-mac-osx-are8jcopb" ) session.add(item9) session.commit() item10 = Item( user=user1, category=category9, name="Learn Version Control with Git", description=("A step-by-step course for the complete beginner"), duration="to 1 hour", level="BEGINNER", image_url= "https://tower-website-ftkdppxp1xaznovg.netdna-ssl.com/learn/assets/img/keyvisual/ebook_dark.1527173730.png", link= "https://www.git-tower.com/learn/git/ebook/en/command-line/appendix/best-practices" ) session.add(item10) session.commit() item11 = Item( user=user1, category=category2, name="Javascript", description= ("Make your websites dynamic and interactive with JavaScript! You'll create features and stand-alone applications. This course will wrap everything you've learned at The Odin Project into one, final capstone project. 30 lessons" ), duration="16 to 32 hours", level="BEGINNER", image_url= "https://www.theodinproject.com/assets/home-isometric-60f02f572fa9ae583a22bf4d391e48f30cae707cbdb602e130bc3f12d73bac85.svg", link="https://www.theodinproject.com/courses/javascript") session.add(item11) session.commit() item12 = Item( user=user1, category=category3, name="Start Learning React", description= ("This series will explore the basic fundamentals of React to get you started." ), duration="2 to 4 hours", level="BEGINNER", image_url= "https://d2eip9sf3oo6c2.cloudfront.net/series/square_covers/000/000/003/full/course_image.png", link="https://egghead.io/courses/start-learning-react") session.add(item12) session.commit() item13 = Item( user=user1, category=category4, name="Node JS Training and Fundamentals", description= ("Node basics and fundamentals to make you ready to create any web app using express, jade and node modules." ), duration="4 to 8 hours", level="BEGINNER", image_url= "https://udemy-images.udemy.com/course/480x270/595294_bc81.jpg", link= "https://www.udemy.com/node-js-training-and-fundamentals/?siteID=Fh5UMknfYAU-TkergXOKdpODeZTt.miTZw&LSNPUBID=Fh5UMknfYAU" ) session.add(item13) session.commit() item14 = Item( user=user1, category=category5, name="Python for Beginners with Examples", description= ("A practical Python course for beginners with examples and exercises." ), duration="4 to 8 hours", level="BEGINNER", image_url= "https://udemy-images.udemy.com/course/480x270/577248_3b6f_12.jpg", link= "https://www.udemy.com/ardit-sulce-python-for-beginners/?siteID=Fh5UMknfYAU-XQ5mHVXoiEA5LjPQW.xmAg&LSNPUBID=Fh5UMknfYAU" ) session.add(item14) session.commit() item15 = Item( user=user1, category=category6, name="Laravel E-Commerce Restful API", description= ("Know what is Rest concept and how to create a RESTFUL API with Laravel Resource" ), duration="32 to 64 hours", level="INTERMEDIATE", image_url= "https://udemy-images.udemy.com/course/480x270/1470550_2d1e.jpg", link= "https://www.udemy.com/ardit-sulce-python-for-beginners/?siteID=Fh5UMknfYAU-XQ5mHVXoiEA5LjPQW.xmAg&LSNPUBID=Fh5UMknfYAU" ) session.add(item15) session.commit() item16 = Item( user=user1, category=category7, name="Creating Programmatic SQL Database Objects", description= ("Learn how to add functionality to your database with programmatic database objects using the R programming language." ), duration="8 to 16 hours", level="INTERMEDIATE", image_url= "https://prod-discovery.edx-cdn.org/media/course/image/d471fec7-5d9d-45f1-b622-af86a31064be-6fe9a510bf23.small.jpg", link= "https://www.edx.org/course/creating-programmatic-sql-database-objects?source=aw&awc=6798_1528876589_9c64f89577cb3b4983eebd3c02c6f2e2" ) session.add(item16) session.commit() item17 = Item( user=user1, category=category8, name="OAuth 2.0 Tutorial", description= ("This tutorial series explains how OAuth 2.0, the open authorization protocol, works." ), duration="4 to 8 hours", level="BEGINNER", image_url="http://tutorials.jenkov.com/images/oauth2/introduction.png", link="http://tutorials.jenkov.com/oauth2/index.html") session.add(item17) session.commit() item18 = Item( user=user1, category=category9, name="How to Use Git and GitHub", description= ("This course, built with input from GitHub, will introduce the basics of using version control by focusing on a particular version control system called Git and a collaboration platform called GitHub." ), duration="8 to 16 hours", level="BEGINNER", image_url= "https://res.cloudinary.com/db194k5td/image/upload/v1510723267/git_logo_tjnjxd.svg", link="https://in.udacity.com/course/how-to-use-git-and-github--ud775") session.add(item18) session.commit() session.close() print "Populated database..."
def newItem(category_id): # if 'username' not in login_session: # return redirect('/login') category = session.query(Category).filter_by(id=category_id).one() categorys = session.query(Category).order_by(asc(Category.name)) # if login_session['user_id'] != category.user_id: # return "<script>function myFunction() {alert('You are not authorized # to add items to this Category.');}</script><body onload='myFunction()'>" states = ['ALABAMA', 'ALASKA', 'ARIZONA', 'ARKANSAS', 'CALIFORNIA', 'COLORADO', 'CONNECTICUT', 'DELAWARE', 'FLORIDA', 'GEORGIA', 'HAWAII', 'IDAHO', 'ILLINOIS', 'INDIANA', 'IOWA', 'KANSAS', 'KENTUCKY', 'LOUISIANA', 'MAINE', 'MARYLAND', 'MASSACHUSETTS', 'MICHIGAN', 'MINNESOTA', 'MISSISSIPPI', 'MISSOURI', 'MONTANA', 'NEBRASKA', 'NEVADA', 'NEW HAMPSHIRE', 'NEW JERSEY', 'NEW MEXICO', 'NEW YORK', 'NORTH CAROLINA', 'NORTH DAKOTA', 'OHIO', 'OKLAHOMA', 'OREGON', 'PENNSYLVANIA', 'RHODE ISLAND', 'SOUTH CAROLINA', 'SOUTH DAKOTA', 'TENNESSEE', 'TEXAS', 'UTAH', 'VERMONT', 'VIRGINIA', 'WASHINGTON', 'WEST VIRGINIA', 'WISCONSIN', 'WYOMING', 'GUAM', 'PUERTO RICO', 'VIRGIN ISLANDS'] if request.method == 'POST': missing_fields = '' file = request.files['inputFile'] if file.filename == '': missing_fields = missing_fields + '..Image file ' if request.form['name'] == '': missing_fields = missing_fields + '..Name ' item_name = '' else: item_name = request.form['name'] if request.form['description'] == '': missing_fields = missing_fields + '..Description ' item_des = '' else: item_des = request.form['description'] if request.form['price'] == '': missing_fields = missing_fields + '..Price ' item_price = '' else: item_price = request.form['price'] if request.form['your_state'] == '': missing_fields = missing_fields + '..Your home state' item_state = '' else: item_state = request.form['your_state'] if request.form['method'] == '': missing_fields = missing_fields + '..Method' item_method = '' else: item_method = request.form['method'] print("missing_fields last =", missing_fields) if(missing_fields == ''): UPLOAD_FOLDER = img_file_path app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # profane = profanity_filter.Filter(product_review, "unicorn") # print ("Clean Text: %s" % profane.clean()) newItem = Item(name=Filter(request.form['name'], "???").clean(), description=Filter(request.form['description'], "???").clean(), price=Filter(request.form['price'], "???").clean(), category_id=request.form['category_id'], user_id=login_session['user_id'], date=datetime.datetime.now(), file_name=filename, state=item_state, method=item_method) # , data=file.read()) session.add(newItem) session.commit() flash('New Item %s Successfully Created' % (newItem.name)) return redirect(url_for('showCategoryItems', category_id=category_id)) else: flash('New item was not created. All fields need to be filled ' 'before clicking on Create button. Missing fields: %s.' % missing_fields) return render_template('newitem.html', category=category, category_id=category_id, categorys=categorys, item_name=item_name, item_des=item_des, item_price=item_price, states=states, item_state=item_state, item_method=item_method) else: return render_template('newitem.html', category=category, category_id=category_id, categorys=categorys, item_name='', item_des='', item_price='', states=states, item_state='', item_method='')
def populate(): session = connect_to_database() # Make sure the database is empty before running this inital data dump. category_count = session.query(func.count(Category.id)).scalar() if category_count > 0: session.close() return # Create the categories for Vehicles categoryBicycles = Category(name="Bicycles") session.add(categoryBicycles) session.commit() categoryMotor = Category(name="Motor Vehicles") session.add(categoryMotor) session.commit() categoryRailed = Category(name="Railed Vehicles") session.add(categoryRailed) session.commit() categoryWatercraft = Category(name="Watercraft") session.add(categoryWatercraft) session.commit() categoryAircraft = Category(name="Aircraft") session.add(categoryAircraft) session.commit() categorySpacecraft = Category(name="Spacecraft") session.add(categorySpacecraft) session.commit() # Create a user user1 = User(name="Rui Bot", email="*****@*****.**") session.add(user1) session.commit() item1 = Item( user=user1, category=categoryBicycles, name="Chinese Flying Pigeon", description= ("The most popular bicycle model-and most popular vehicle of any kind in" "the world-is the Chinese Flying Pigeon, with about 500 million produced" ), image_url= "https://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Left_side_of_Flying_Pigeon.jpg/1280px-Left_side_of_Flying_Pigeon.jpg" ) session.add(item1) session.commit() item2 = Item( user=user1, category=categoryBicycles, name=" Trek Y-Foil", description=("A carbon fiber Trek Y-Foil from the late 1990s"), image_url= "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/Trek_Y_Foil.jpg/1280px-Trek_Y_Foil.jpg" ) session.add(item2) session.commit() item3 = Item( user=user1, category=categoryMotor, name="1927 Ford Model T", description=("1927 Ford Model T"), image_url= "https://upload.wikimedia.org/wikipedia/commons/1/15/Late_model_Ford_Model_T.jpg" ) session.add(item3) session.commit() item4 = Item( user=user1, category=categoryMotor, name="Nissan Leaf", description=( "The Nissan Leaf is an all-electric car launched in December 2010" ), image_url= "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/2018_Nissan_Leaf_Tekna_Front.jpg/280px-2018_Nissan_Leaf_Tekna_Front.jpg" ) session.add(item4) session.commit() item5 = Item( user=user1, category=categoryMotor, name="Freightliner M2 dump truck", description=("Big truck: Freightliner M2 dump truck"), image_url= "https://upload.wikimedia.org/wikipedia/commons/thumb/1/11/Freightliner_M2_106_6x4_2014_%2814240376744%29.jpg/1280px-Freightliner_M2_106_6x4_2014_%2814240376744%29.jpg" ) session.add(item5) session.commit() item6 = Item( user=user1, category=categoryMotor, name="Doble Decker Bus", description= ("A New Routemaster double-decker bus, operating for Arriva London on" "London Buses route 73"), image_url= "https://upload.wikimedia.org/wikipedia/commons/thumb/6/63/LT_471_%28LTZ_1471%29_Arriva_London_New_Routemaster_%2819522859218%29.jpg/1280px-LT_471_%28LTZ_1471%29_Arriva_London_New_Routemaster_%2819522859218%29.jpg" ) session.add(item6) session.commit() item7 = Item( user=user1, category=categoryMotor, name="Old bus", description=( "A Toronto Transit Commission bus system trolleybus in Toronto"), image_url= "https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/Toronto_Flyer_E700A_trolleybus_in_1987.jpg/1280px-Toronto_Flyer_E700A_trolleybus_in_1987.jpg" ) session.add(item7) session.commit() item8 = Item( user=user1, category=categoryMotor, name="Norton motorcycle", description=("A classic Norton motorcycle"), image_url= "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Norton_Motorcycle.jpg/800px-Norton_Motorcycle.jpg" ) session.add(item8) session.commit() item9 = Item( user=user1, category=categoryMotor, name="Suzuki GS500", description=( "A Suzuki GS500 with a clearly visible frame, painted silver"), image_url= "https://upload.wikimedia.org/wikipedia/commons/thumb/3/36/1997SuzukiGS500E-001.jpg/1280px-1997SuzukiGS500E-001.jpg" ) session.add(item9) session.commit() item10 = Item( user=user1, category=categoryRailed, name="Glass Frog", description=( "Japanese Shinkansen 500 Series train, Shinkansen 500 series" " at Kyoto Station taken by Nick Coutts on 2005-03-19."), image_url= "https://upload.wikimedia.org/wikipedia/commons/3/31/Shinkansen_500_Kyoto_2005-03-19.jpg" ) session.add(item10) session.commit() item11 = Item( user=user1, category=categoryRailed, name="ETT 303 and 304 Sunshine.", description=("ETT 303 and 304 Sunshine."), image_url= "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/City_of_Rockhampton_train_%28Sunshine_railway_station%2C_Brisbane%29.jpg/800px-City_of_Rockhampton_train_%28Sunshine_railway_station%2C_Brisbane%29.jpg" ) session.add(item11) session.commit() item12 = Item( user=user1, category=categoryWatercraft, name="RMS Titanic 3", description=("Titanic!!!"), image_url= "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/RMS_Titanic_3.jpg/800px-RMS_Titanic_3.jpg" ) session.add(item12) session.commit() item13 = Item( user=user1, category=categoryWatercraft, name="Colombo Express", description= ("The Colombo Express, one of the largest container ships in the world," "owned and operated by Hapag-Lloyd of Germany on its maiden voyage into Hamburg," "with the Kohlbrand bridge in the background"), image_url= "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7e/Colombo.Express.wmt.jpg/800px-Colombo.Express.wmt.jpg" ) session.add(item13) session.commit() item14 = Item( user=user1, category=categoryAircraft, name="Cessna 172", description=( "The Cessna 172 Skyhawk is the most produced aircraft in history." ), image_url= "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Cessna172-CatalinaTakeOff.JPG/800px-Cessna172-CatalinaTakeOff.JPG" ) session.add(item14) session.commit() item15 = Item( user=user1, category=categoryAircraft, name="Mil Mi-8", description=( "The Mil Mi-8 is the most-produced helicopter in history."), image_url= "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Mi-8_%28RA-24477%29_Helicopter_in_SPB.jpg/800px-Mi-8_%28RA-24477%29_Helicopter_in_SPB.jpg" ) session.add(item15) session.commit() session.close() print("Populated database with some rows...")