├── __init__.py ├── step0 ├── __init__.py ├── templates │ ├── 404.html │ ├── 500.html │ ├── home.html │ └── layouts │ │ └── main.html └── webapp.py ├── db_connector ├── __init__.py ├── templates │ └── db_test.html ├── sample.py └── db_connector.py ├── starter_website ├── __init__.py ├── templates │ ├── 404.html │ ├── 500.html │ ├── db_test.html │ ├── home.html │ ├── layouts │ │ └── main.html │ ├── people_add_new.html │ ├── update-person.html │ ├── people_browse.html │ ├── people_update.html │ ├── people_certs.html │ └── people.html └── webapp.py ├── .gitignore ├── requirements.txt ├── CONTRIBUTING.md ├── db_credentials.py.sample ├── run.py ├── bsg_db.sql ├── README.md └── LICENSE /__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /step0/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /db_connector/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /starter_website/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | db_credentials.py 2 | *.pyc 3 | .vscode/ -------------------------------------------------------------------------------- /step0/templates/404.html: -------------------------------------------------------------------------------- 1 |

Error 404 - Page Is Nowhere to be Found

-------------------------------------------------------------------------------- /step0/templates/500.html: -------------------------------------------------------------------------------- 1 |

Error 500 - Something Has Gone Terribly Wrong

-------------------------------------------------------------------------------- /starter_website/templates/404.html: -------------------------------------------------------------------------------- 1 |

Error 404 - Page Is Nowhere to be Found

-------------------------------------------------------------------------------- /starter_website/templates/500.html: -------------------------------------------------------------------------------- 1 |

Error 500 - Something Has Gone Terribly Wrong

-------------------------------------------------------------------------------- /db_connector/templates/db_test.html: -------------------------------------------------------------------------------- 1 |
    2 | {% for r in rows %} 3 |
  1. {{ r }}
  2. 4 | {% endfor %} 5 |
6 | -------------------------------------------------------------------------------- /starter_website/templates/db_test.html: -------------------------------------------------------------------------------- 1 |
    2 | {% for r in rows %} 3 |
  1. {{ r }}
  2. 4 | {% endfor %} 5 |
6 | -------------------------------------------------------------------------------- /step0/templates/home.html: -------------------------------------------------------------------------------- 1 |

MySQL Results:

2 | {% for result in results%} 3 |

{{result}}

4 | {% endfor %} 5 | -------------------------------------------------------------------------------- /starter_website/templates/home.html: -------------------------------------------------------------------------------- 1 |

MySQL Results:

2 |

3 | {% for r in result %} 4 |

5 | {{r}} 6 |
7 | {% endfor %} 8 | 9 |

-------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Click==7.0 2 | Flask==1.0.2 3 | gunicorn==19.9.0 4 | itsdangerous==1.1.0 5 | Jinja2==2.10 6 | MarkupSafe==1.1.0 7 | mysqlclient==1.3.13 8 | waitress==1.4.3 9 | Werkzeug==0.14.1 10 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | === How to contribute to this Project? ==== 2 | 3 | If you are a student of CS340 or CS464 at an OSU class, you can send a pull request to make this starter code better. 4 | 5 | === What can I contribute to this Project? ==== 6 | 7 | You can help make the instructions for the project setup or usage easier. 8 | 9 | 10 | -------------------------------------------------------------------------------- /starter_website/templates/layouts/main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Demo Page 5 | 6 | {% for myscript in jsscripts %} 7 | 8 | {% endfor %} 9 | 10 | 11 | {{{body}}} 12 | 13 | 14 | -------------------------------------------------------------------------------- /step0/templates/layouts/main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Project Step 0: Connect webapp to database 5 | 6 | {% for myscript in jsscripts %} 7 | 8 | {% endfor %} 9 | 10 | 11 | {{{body}}} 12 | 13 | 14 | -------------------------------------------------------------------------------- /db_credentials.py.sample: -------------------------------------------------------------------------------- 1 | # To actually have your app use this file, you need to RENAME the file to db_credentials.py 2 | # You will find details about your CS340 database credentials on Canvas. 3 | 4 | # the following will be used by the db_connector.py and 5 | # in turn by all the Python code in this codebase to interact with the database 6 | 7 | host = 'classmysql.engr.oregonstate.edu' #DON'T CHANGE ME UNLESS THE INSTRUCTIONS SAY SO 8 | user = 'cs340_ONID' #CHANGE ME 9 | passwd = 'super_secret_password' #CHANGE ME 10 | db = 'cs340_ONID' #CHANGE ME 11 | -------------------------------------------------------------------------------- /run.py: -------------------------------------------------------------------------------- 1 | #this file is used to run your flask-based-database-interacting-website persistently! 2 | 3 | #change this line to run the app that you want to run 4 | #from db_connector.sample import app 5 | #for example, the above line tells to run the sample db connection app in db_connector/ directory 6 | from starter_website.webapp import webapp 7 | #from step0.webapp import webapp 8 | 9 | #then from the commandline run: 10 | #./venv/bin/activate 11 | #gunicorn run:app -b 0.0.0.0:SOME_NUMBER_BETWEEN_1025_and_65535 12 | #eg. gunicorn run:app -b 0.0.0.0:8842 13 | -------------------------------------------------------------------------------- /starter_website/templates/people_add_new.html: -------------------------------------------------------------------------------- 1 |

Add new people:

2 |
3 | First name:
4 | Last name:
5 | Homeworld:
11 | Age:
12 | 13 |
14 |
15 | -------------------------------------------------------------------------------- /starter_website/templates/update-person.html: -------------------------------------------------------------------------------- 1 | 2 |

Update {{person.fname}} {{person.lname}}:

3 |
4 | First name:
5 | Last name:
6 | Homeworld:
11 | Age:
12 |
13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /db_connector/sample.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template 2 | from db_connector.db_connector import connect_to_database, execute_query 3 | 4 | app = Flask(__name__) 5 | 6 | #the route is what you will type in browser 7 | @app.route('/hello') 8 | #the name of this function is just a cosmetic thing 9 | def hello(): 10 | #this is the output returned to browser 11 | return "Hello world!" 12 | 13 | @app.route('/') 14 | def index(): 15 | return "Are you looking for /db-test or /hello ?" 16 | 17 | @app.route('/db-test') 18 | def test_database_connection(): 19 | print("Executing a sample query on the database using the credentials from db_credentials.py") 20 | db_connection = connect_to_database() 21 | query = "SELECT * from bsg_people;" 22 | result = execute_query(db_connection, query) 23 | return render_template('db_test.html', rows=result) 24 | -------------------------------------------------------------------------------- /starter_website/templates/people_browse.html: -------------------------------------------------------------------------------- 1 | 2 | Browse people 3 |

Add new people

4 | 5 |

Current people

6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | {% for r in rows %} 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | {% endfor %} 26 | 27 |
IDFirst NameLast NameHomeworldAge
{{ r[4] }} {{ r.0 }} {{ r[1] }} {{ r[2] }} {{ r[3] }}
28 | 29 | 30 | -------------------------------------------------------------------------------- /starter_website/templates/people_update.html: -------------------------------------------------------------------------------- 1 |

Add new people:

2 |
3 | 4 | 5 | First name:
6 | Last name:
7 | Homeworld:
19 | Age:
20 | 21 |
22 |
23 | -------------------------------------------------------------------------------- /step0/webapp.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template 2 | from flask import request, redirect 3 | from db_connector.db_connector import connect_to_database, execute_query 4 | #create the web application 5 | webapp = Flask(__name__) 6 | 7 | #provide a route where requests on the web application can be addressed 8 | @webapp.route('/hello') 9 | #provide a view (fancy name for a function) which responds to any requests on this route 10 | def hello(): 11 | return "Hello World!"; 12 | 13 | @webapp.route('/') 14 | def index(): 15 | print("Running queries for project step 0") 16 | db_connection = connect_to_database() 17 | drop_table = "DROP TABLE IF EXISTS diagnostic;" 18 | create_table = "CREATE TABLE diagnostic(id INT PRIMARY KEY AUTO_INCREMENT, text VARCHAR(255) NOT NULL);" 19 | insert_row = "INSERT INTO diagnostic (text) VALUES ('MySQL is Working!')" 20 | query = "SELECT * FROM diagnostic;" 21 | execute_query(db_connection, drop_table); 22 | execute_query(db_connection, create_table); 23 | execute_query(db_connection, insert_row); 24 | values = execute_query.fetchall(db_connection, query); 25 | return render_template('home.html', results=values) 26 | -------------------------------------------------------------------------------- /starter_website/templates/people_certs.html: -------------------------------------------------------------------------------- 1 | 2 | {% for eachfoo in foo %} 3 | {{eachfoo}} 4 | {% endfor %} 5 |
6 |

Associate Certificate(s) with a Person

7 |
8 | Person: 13 |
14 | Certificates:Multi-select
20 | 21 |
22 |
23 |
24 |

List of People with their Certifications

25 | 26 | 27 | 28 | 29 | 30 | 31 | {% if people_with_certs %} 32 | {% for ppl_with_cert in people_with_certs %} 33 | 34 | 35 | 36 | 37 | 38 | 39 | {% endfor %} 40 | {% else %} 41 | No people with any certifications found! Grant some using the form. 42 | {% endif %} 43 | 44 |
NameCertificate
{{ppl_with_cert.name}}{{ppl_with_cert.certificate}}Update
45 | 46 | -------------------------------------------------------------------------------- /starter_website/templates/people.html: -------------------------------------------------------------------------------- 1 | 2 | {% for eachfoo in foo %} 3 | {{eachfoo}} 4 | {% endfor %} 5 |

Add new people:

6 |
7 | First name:
8 | Last name:
9 | Homeworld:
14 | Age:
15 | 16 |
17 |
18 | 19 |
20 | 21 | 22 |
27 | 28 |
29 | 30 |
31 | 32 | 33 | 34 | 35 |
36 | 37 |

Current people:

38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | {% for ppl in people %} 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | {% endfor %} 56 | 57 |
First NameLast NameHomeworldAge
{{ppl.fname}}{{ppl.lname}}{{ppl.homeworld}}{{ppl.age}}Update
58 | 59 | -------------------------------------------------------------------------------- /db_connector/db_connector.py: -------------------------------------------------------------------------------- 1 | import MySQLdb as mariadb 2 | from db_credentials import host, user, passwd, db 3 | 4 | def connect_to_database(host = host, user = user, passwd = passwd, db = db): 5 | ''' 6 | connects to a database and returns a database objects 7 | ''' 8 | db_connection = mariadb.connect(host,user,passwd,db) 9 | return db_connection 10 | 11 | def execute_query(db_connection = None, query = None, query_params = ()): 12 | ''' 13 | executes a given SQL query on the given db connection and returns a Cursor object 14 | 15 | db_connection: a MySQLdb connection object created by connect_to_database() 16 | query: string containing SQL query 17 | 18 | returns: A Cursor object as specified at https://www.python.org/dev/peps/pep-0249/#cursor-objects. 19 | You need to run .fetchall() or .fetchone() on that object to actually acccess the results. 20 | 21 | ''' 22 | 23 | if db_connection is None: 24 | print("No connection to the database found! Have you called connect_to_database() first?") 25 | return None 26 | 27 | if query is None or len(query.strip()) == 0: 28 | print("query is empty! Please pass a SQL query in query") 29 | return None 30 | 31 | print("Executing %s with %s" % (query, query_params)) 32 | # Create a cursor to execute query. Why? Because apparently they optimize execution by retaining a reference according to PEP0249 33 | cursor = db_connection.cursor() 34 | 35 | ''' 36 | params = tuple() 37 | #create a tuple of paramters to send with the query 38 | for q in query_params: 39 | params = params + (q) 40 | ''' 41 | #TODO: Sanitize the query before executing it!!! 42 | cursor.execute(query, query_params) 43 | # this will actually commit any changes to the database. without this no 44 | # changes will be committed! 45 | db_connection.commit() 46 | return cursor 47 | 48 | if __name__ == '__main__': 49 | print("Executing a sample query on the database using the credentials from db_credentials.py") 50 | db = connect_to_database() 51 | query = "SELECT * from bsg_people;" 52 | results = execute_query(db, query) 53 | print("Printing results of %s" % query) 54 | 55 | for r in results.fetchall(): 56 | print(r) 57 | -------------------------------------------------------------------------------- /starter_website/webapp.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template 2 | from flask import request, redirect 3 | from db_connector.db_connector import connect_to_database, execute_query 4 | #create the web application 5 | webapp = Flask(__name__) 6 | 7 | #provide a route where requests on the web application can be addressed 8 | @webapp.route('/hello') 9 | #provide a view (fancy name for a function) which responds to any requests on this route 10 | def hello(): 11 | return "Hello World!" 12 | 13 | @webapp.route('/browse_bsg_people') 14 | #the name of this function is just a cosmetic thing 15 | def browse_people(): 16 | print("Fetching and rendering people web page") 17 | db_connection = connect_to_database() 18 | query = "SELECT fname, lname, homeworld, age, id from bsg_people;" 19 | result = execute_query(db_connection, query).fetchall() 20 | print(result) 21 | return render_template('people_browse.html', rows=result) 22 | 23 | @webapp.route('/add_new_people', methods=['POST','GET']) 24 | def add_new_people(): 25 | db_connection = connect_to_database() 26 | if request.method == 'GET': 27 | query = 'SELECT id, name from bsg_planets' 28 | result = execute_query(db_connection, query).fetchall() 29 | print(result) 30 | 31 | return render_template('people_add_new.html', planets = result) 32 | elif request.method == 'POST': 33 | print("Add new people!") 34 | fname = request.form['fname'] 35 | lname = request.form['lname'] 36 | age = request.form['age'] 37 | homeworld = request.form['homeworld'] 38 | 39 | query = 'INSERT INTO bsg_people (fname, lname, age, homeworld) VALUES (%s,%s,%s,%s)' 40 | data = (fname, lname, age, homeworld) 41 | execute_query(db_connection, query, data) 42 | return ('Person added!') 43 | 44 | @webapp.route('/') 45 | def index(): 46 | return "

Are you looking for /db_test or /hello or /browse_bsg_people or /add_new_people or /update_people/id or /delete_people/id

" 47 | 48 | @webapp.route('/home') 49 | def home(): 50 | db_connection = connect_to_database() 51 | query = "DROP TABLE IF EXISTS diagnostic;" 52 | execute_query(db_connection, query) 53 | query = "CREATE TABLE diagnostic(id INT PRIMARY KEY, text VARCHAR(255) NOT NULL);" 54 | execute_query(db_connection, query) 55 | query = "INSERT INTO diagnostic (text) VALUES ('MySQL is working');" 56 | execute_query(db_connection, query) 57 | query = "SELECT * from diagnostic;" 58 | result = execute_query(db_connection, query) 59 | for r in result: 60 | print(f"{r[0]}, {r[1]}") 61 | return render_template('home.html', result = result) 62 | 63 | @webapp.route('/db_test') 64 | def test_database_connection(): 65 | print("Executing a sample query on the database using the credentials from db_credentials.py") 66 | db_connection = connect_to_database() 67 | query = "SELECT * from bsg_people;" 68 | result = execute_query(db_connection, query) 69 | return render_template('db_test.html', rows=result) 70 | 71 | #display update form and process any updates, using the same function 72 | @webapp.route('/update_people/', methods=['POST','GET']) 73 | def update_people(id): 74 | print('In the function') 75 | db_connection = connect_to_database() 76 | #display existing data 77 | if request.method == 'GET': 78 | print('The GET request') 79 | people_query = 'SELECT id, fname, lname, homeworld, age from bsg_people WHERE id = %s' % (id) 80 | people_result = execute_query(db_connection, people_query).fetchone() 81 | 82 | if people_result == None: 83 | return "No such person found!" 84 | 85 | planets_query = 'SELECT id, name from bsg_planets' 86 | planets_results = execute_query(db_connection, planets_query).fetchall() 87 | 88 | print('Returning') 89 | return render_template('people_update.html', planets = planets_results, person = people_result) 90 | elif request.method == 'POST': 91 | print('The POST request') 92 | character_id = request.form['character_id'] 93 | fname = request.form['fname'] 94 | lname = request.form['lname'] 95 | age = request.form['age'] 96 | homeworld = request.form['homeworld'] 97 | 98 | query = "UPDATE bsg_people SET fname = %s, lname = %s, age = %s, homeworld = %s WHERE id = %s" 99 | data = (fname, lname, age, homeworld, character_id) 100 | result = execute_query(db_connection, query, data) 101 | print(str(result.rowcount) + " row(s) updated") 102 | 103 | return redirect('/browse_bsg_people') 104 | 105 | @webapp.route('/delete_people/') 106 | def delete_people(id): 107 | '''deletes a person with the given id''' 108 | db_connection = connect_to_database() 109 | query = "DELETE FROM bsg_people WHERE id = %s" 110 | data = (id,) 111 | 112 | result = execute_query(db_connection, query, data) 113 | return (str(result.rowcount) + "row deleted") 114 | -------------------------------------------------------------------------------- /bsg_db.sql: -------------------------------------------------------------------------------- 1 | -- MySQL dump 10.16 Distrib 10.1.35-MariaDB, for Linux (x86_64) 2 | -- 3 | -- Host: localhost Database: bsg2 4 | -- ------------------------------------------------------ 5 | -- Server version 10.1.35-MariaDB 6 | 7 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 8 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 9 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 10 | /*!40101 SET NAMES utf8 */; 11 | /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; 12 | /*!40103 SET TIME_ZONE='+00:00' */; 13 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 14 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 15 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 16 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 17 | 18 | -- 19 | -- Table structure for table `bsg_cert` 20 | -- 21 | 22 | DROP TABLE IF EXISTS `bsg_cert`; 23 | /*!40101 SET @saved_cs_client = @@character_set_client */; 24 | /*!40101 SET character_set_client = utf8 */; 25 | CREATE TABLE `bsg_cert` ( 26 | `certification_id` int(11) NOT NULL AUTO_INCREMENT, 27 | `title` varchar(255) NOT NULL, 28 | PRIMARY KEY (`certification_id`) 29 | ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; 30 | /*!40101 SET character_set_client = @saved_cs_client */; 31 | 32 | -- 33 | -- Dumping data for table `bsg_cert` 34 | -- 35 | 36 | LOCK TABLES `bsg_cert` WRITE; 37 | /*!40000 ALTER TABLE `bsg_cert` DISABLE KEYS */; 38 | INSERT INTO `bsg_cert` VALUES (1,'Raptor'),(2,'Viper'),(3,'Mechanic'),(4,'Command'); 39 | /*!40000 ALTER TABLE `bsg_cert` ENABLE KEYS */; 40 | UNLOCK TABLES; 41 | 42 | -- 43 | -- Table structure for table `bsg_cert_people` 44 | -- 45 | 46 | DROP TABLE IF EXISTS `bsg_cert_people`; 47 | /*!40101 SET @saved_cs_client = @@character_set_client */; 48 | /*!40101 SET character_set_client = utf8 */; 49 | CREATE TABLE `bsg_cert_people` ( 50 | `cid` int(11) NOT NULL DEFAULT '0', 51 | `pid` int(11) NOT NULL DEFAULT '0', 52 | `certification_date` date NOT NULL, 53 | PRIMARY KEY (`cid`,`pid`), 54 | KEY `pid` (`pid`), 55 | CONSTRAINT `bsg_cert_people_ibfk_1` FOREIGN KEY (`cid`) REFERENCES `bsg_cert` (`certification_id`), 56 | CONSTRAINT `bsg_cert_people_ibfk_2` FOREIGN KEY (`pid`) REFERENCES `bsg_people` (`character_id`) 57 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1; 58 | /*!40101 SET character_set_client = @saved_cs_client */; 59 | 60 | -- 61 | -- Dumping data for table `bsg_cert_people` 62 | -- 63 | 64 | LOCK TABLES `bsg_cert_people` WRITE; 65 | /*!40000 ALTER TABLE `bsg_cert_people` DISABLE KEYS */; 66 | INSERT INTO `bsg_cert_people` VALUES (1,1,'0000-00-00'),(1,2,'0000-00-00'),(2,1,'0000-00-00'),(2,2,'0000-00-00'),(3,1,'0000-00-00'),(3,6,'0000-00-00'),(4,1,'0000-00-00'),(4,6,'0000-00-00'); 67 | /*!40000 ALTER TABLE `bsg_cert_people` ENABLE KEYS */; 68 | UNLOCK TABLES; 69 | 70 | -- 71 | -- Table structure for table `bsg_people` 72 | -- 73 | 74 | DROP TABLE IF EXISTS `bsg_people`; 75 | /*!40101 SET @saved_cs_client = @@character_set_client */; 76 | /*!40101 SET character_set_client = utf8 */; 77 | CREATE TABLE `bsg_people` ( 78 | `character_id` int(11) NOT NULL AUTO_INCREMENT, 79 | `fname` varchar(255) NOT NULL, 80 | `lname` varchar(255) DEFAULT NULL, 81 | `homeworld` int(11) DEFAULT NULL, 82 | `age` int(11) DEFAULT NULL, 83 | `race` varchar(5) NOT NULL DEFAULT 'Human', 84 | PRIMARY KEY (`character_id`), 85 | KEY `homeworld` (`homeworld`), 86 | CONSTRAINT `bsg_people_ibfk_1` FOREIGN KEY (`homeworld`) REFERENCES `bsg_planets` (`planet_id`) ON DELETE SET NULL ON UPDATE CASCADE 87 | ) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=latin1; 88 | /*!40101 SET character_set_client = @saved_cs_client */; 89 | 90 | -- 91 | -- Dumping data for table `bsg_people` 92 | -- 93 | 94 | LOCK TABLES `bsg_people` WRITE; 95 | /*!40000 ALTER TABLE `bsg_people` DISABLE KEYS */; 96 | INSERT INTO `bsg_people` VALUES (1,'Will','Adama',20,634,'Human'),(2,'Lee','Adama',3,100,'Human'),(3,'Laura','Roslin',22,100,'Human'),(6,'Saul','Tigh',NULL,71,'Human'),(9,'Callandra','Henderson',NULL,NULL,'Human'),(17,'Trey','Hoover',16,23,'Human'),(18,'Luke','Bob',16,24,'Human'),(20,'Bob','Jones',2,27,'Human'); 97 | /*!40000 ALTER TABLE `bsg_people` ENABLE KEYS */; 98 | UNLOCK TABLES; 99 | 100 | -- 101 | -- Table structure for table `bsg_planets` 102 | -- 103 | 104 | DROP TABLE IF EXISTS `bsg_planets`; 105 | /*!40101 SET @saved_cs_client = @@character_set_client */; 106 | /*!40101 SET character_set_client = utf8 */; 107 | CREATE TABLE `bsg_planets` ( 108 | `planet_id` int(11) NOT NULL AUTO_INCREMENT, 109 | `name` varchar(255) NOT NULL, 110 | `population` bigint(20) DEFAULT NULL, 111 | `language` varchar(255) DEFAULT NULL, 112 | `capital` varchar(255) DEFAULT NULL, 113 | PRIMARY KEY (`planet_id`), 114 | UNIQUE KEY `name` (`name`) 115 | ) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1; 116 | /*!40101 SET character_set_client = @saved_cs_client */; 117 | 118 | -- 119 | -- Dumping data for table `bsg_planets` 120 | -- 121 | 122 | LOCK TABLES `bsg_planets` WRITE; 123 | /*!40000 ALTER TABLE `bsg_planets` DISABLE KEYS */; 124 | INSERT INTO `bsg_planets` VALUES (1,'Gemenon',2800000000,'Old Gemenese','Oranu'),(2,'Leonis',2600000000,'Leonese','Luminere'),(3,'Caprica',4900000000,'Caprican','Caprica City'),(7,'Sagittaron',1700000000,NULL,'Tawa'),(16,'Aquaria',25000,NULL,NULL),(17,'Canceron',6700000000,NULL,'Hades'),(18,'Libran',2100000,NULL,NULL),(19,'Picon',1400000000,NULL,'Queestown'),(20,'Scorpia',450000000,NULL,'Celeste'),(21,'Tauron',2500000000,'Tauron','Hypatia'),(22,'Virgon',4300000000,NULL,'Boskirk'); 125 | /*!40000 ALTER TABLE `bsg_planets` ENABLE KEYS */; 126 | UNLOCK TABLES; 127 | 128 | -- 129 | -- Table structure for table `bsg_spaceship` 130 | -- 131 | 132 | DROP TABLE IF EXISTS `bsg_spaceship`; 133 | /*!40101 SET @saved_cs_client = @@character_set_client */; 134 | /*!40101 SET character_set_client = utf8 */; 135 | CREATE TABLE `bsg_spaceship` ( 136 | `id` int(11) NOT NULL AUTO_INCREMENT, 137 | `name` varchar(255) NOT NULL, 138 | `seperate_saucer_section` bit(1) DEFAULT b'0', 139 | `length` int(11) NOT NULL, 140 | PRIMARY KEY (`id`) 141 | ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; 142 | /*!40101 SET character_set_client = @saved_cs_client */; 143 | 144 | -- 145 | -- Dumping data for table `bsg_spaceship` 146 | -- 147 | 148 | LOCK TABLES `bsg_spaceship` WRITE; 149 | /*!40000 ALTER TABLE `bsg_spaceship` DISABLE KEYS */; 150 | INSERT INTO `bsg_spaceship` VALUES (1,'t1','',0),(2,'t2','',0),(3,'t2','',0),(4,'t3','',0),(5,'t4','\0',0),(6,'t5','',0); 151 | /*!40000 ALTER TABLE `bsg_spaceship` ENABLE KEYS */; 152 | UNLOCK TABLES; 153 | /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; 154 | 155 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 156 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 157 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 158 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 159 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 160 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 161 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 162 | 163 | -- Dump completed on 2018-10-28 13:23:54 164 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Using Python Flask on the Engineering Servers 2 | 3 | 4 | ## Intro 5 | 6 | Flask[1] is a Python micro framework for building web applications which began as a simple wrapper from Werkzeug and Jinjia but has become one of the most popular Python web application frameworks now[2]. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. This guide will walk you through setting it up on the OSU Engineering server and connecting it to an Engineering provided SQL database. 7 | 8 | 9 | ## Overview 10 | 11 | In general things will be very similar to how you deploy a NodeJS app. There are a few important things to note in terms of Python and Flask on the Engineering server. 12 | 13 | The first is that your engineering account is __**not**__ preconfigured with the required demo applications so you will need to get those yourself. 14 | 15 | The next is that _the only way you will be able to see your site is if you are on the OSU VPN or you are physically connected to the on campus internet_. If you are not connected to the VPN you will not be able to access your site. You can find information on connecting to the VPN [here](http://oregonstate.edu/helpdocs/osu-applications/offered-apps/virtual-private-network-vpn). 16 | 17 | The other piece is that your MySQL database that you will be using will need to be made for you. This is usually done as part of a class and your instructor will provide you with the appropriate addresses and credentials to access it. 18 | 19 | 20 | ## Gitting Files 21 | 22 | You should make a new directory in your OSU engineering space, e.g. `mkdir ~/cs340/`. Then from within that directory run the command: 23 | 24 | original git repo 25 | ```bash 26 | git clone https://github.com/knightsamar/CS340_starter_flask_app 27 | ``` 28 | 29 | Note that this repository has 2 webapps: 30 | 31 | 1. A sample database webapp showing how to run a SELECT query on the database and print the results on the webpage 32 | 33 | 2. A (almost) full-fledged webapp demonstrating Create, Read, Update and Delete functionalities. 34 | 35 | Both use the database dump bsg_sample.sql for demonstration. 36 | 37 | This command will clone all the class files from the class Git repository into that directory you created (~/cs340/). 38 | 39 | 40 | ## Making Required Changes 41 | 42 | First you should go to the `CS340_starter_flask_app` repository folder and setup a new Python virtual environment for Flask, then install related dependencies. Run the commands within previous directory: 43 | 44 | ```bash 45 | cd CS340_starter_flask_app 46 | bash 47 | virtualenv venv -p $(which python3) 48 | source ./venv/bin/activate 49 | pip3 install --upgrade pip 50 | pip install -r requirements.txt 51 | ``` 52 | 53 | This will create an virtual environment named `venv` and install the required Python packages to run the starter code, which are listed inside the file `requirements.txt`. 54 | 55 | Next you will need to tweak some files to work with the engineering setup. Because you would have your own database, a few template values will need to be replaced to point to your database. 56 | 57 | In particular, inside the current directory `CS340_starter_flask_app` there is a file called `db_credentials.py.sample`. Rename this file to `db_credentials.py` file and put your actual database credentials inside it. 58 | 59 | You need to edit the file. It should look like the following code with the curly brackets and their contents replaced with the appropriate content: 60 | 61 | ```python 62 | host = 'classmysql.engr.oregonstate.edu' 63 | user = 'cs340_{your_ONID_username}' 64 | passwd = '{last-4-digits-of-your-OSU-ID-number}' 65 | db = 'cs340_{your_ONID_username}' 66 | ``` 67 | 68 | These are the default settings for all students who were enrolled when the term started. 69 | 70 | An **example** would look like this: 71 | 72 | ```python 73 | host = 'classmysql.engr.oregonstate.edu' 74 | user = 'cs340_hedaoos' 75 | passwd = '1234' 76 | db = 'cs340_hedaoos' 77 | ``` 78 | 79 | With that file renamed to `db_credentials.py` and the proper credentials added, we are almost ready to go. 80 | 81 | ## Running the Flask Application! 82 | 83 | Make sure you are still inside the `CS340_starter_flask_app` directory. 84 | 85 | ```bash 86 | source ./venv/bin/activate 87 | export FLASK_APP=run.py 88 | python -m flask run -h 0.0.0.0 -p 8042 --reload 89 | ``` 90 | 91 | **Replace 8042 with a random port number** 92 | 93 | Now, your website should be accessible at http://flipN.engr.oregonstate.edu:YOUR_PORT_NUMBER 94 | 95 | To verify that your server is running, a Hello World page will be visible at `/hello`, while the a READ implementation page can be found at `/browse_bsg_people`. 96 | 97 | So you would go to http://flipN.engr.oregonstate.edu:YOUR_PORT_NUMBER/hello or similar. 98 | 99 | flipN means either of flip1, flip2 or flip3. 100 | YOUR_PORT_NUMBER is the number that you used in the command above to run the app. 101 | 102 | Because this is running on a shared machine everyone cannot use port 8042. Everyone will need to use a unique port, otherwise you will get an error that the port is in use. 103 | 104 | So, we specify the Python file for database connection and also set a port number. You could view the database page of nine entries being served by visiting http://access.engr.oregonstate.edu:5678/browse_bsg_people while you are VPNed into the OSU network. 105 | 106 | This is how you run the app using the Flask Development server. But to submit your URL for assignments, you need to use the method below! 107 | 108 | ## Running the Flask Application Persistently!! 109 | Finally, is the topic of persistence. How to ensure that your app keeps running even after you disconnect from the flip servers/VPN ? 110 | 111 | To do that, we use [gunicorn](https://gunicorn.org/) as follows: 112 | 113 | ```bash 114 | gunicorn run:webapp -b 0.0.0.0:YOUR_PORT_NUMBER -D 115 | ``` 116 | 117 | The -D runs the gunicorn process in background. 118 | 119 | There are a lot of other tools you can use, such as [run with a production server using waitress](http://flask.pocoo.org/docs/1.0/tutorial/deploy/#run-with-a-production-server 120 | ) or [deploy in a standalone WSGI Containers using uWSGI](http://flask.pocoo.org/docs/1.0/deploying/wsgi-standalone/), etc. 121 | 122 | 123 | ### How to kill an old running gunicorn process ? 124 | 125 | You would have to find your process on the right flip server by running 126 | 127 | ```bash 128 | ps ufx | grep gunicorn 129 | ``` 130 | And then kill the process by using it's PID (see the second column in the above output). Note that the grep process also shows up in the output. You want to kill the other process which has a child process. That's most probably the second process in the above output. 131 | 132 | ## The Many Flips 133 | 134 | And as a closing note, if you log into access.engr.oregonstate.edu you will randomly be put on flip1, flip2 or flip3. You can see which flip you are using the command `hostname` then you can switch flips by using the command `ssh flipX` where X is 1, 2 or 3. You need to be sure to log into the same flip every time because the node instance will only be running on one of them. Also be sure to access your website using the right flip server name! 135 | 136 | ## Activity 137 | 138 | You should be able to run the `run.py` and access the page it serves while VPNed onto the server. It will display all entries of bsg_people table. 139 | 140 | ## Review 141 | 142 | This should get you into a position where you have a web server running and it shows you are connected to a database. In addition you should be able to continue to access the site via a browser even if you end your SSH session provided you are on campus or logged into the VPN. 143 | 144 | [1]: http://flask.pocoo.org/ 145 | [2]: https://github.com/pallets/flask 146 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------