Homework 5

In this blog, I will create a simple webapp using Flask.

1.Enable Submissions

Create a submit template. This template inlude a text box for message, a text box for name, and a submit button. w1.png

First, define a funtion get_message_db(). This function should handle creating the database of messages.

def get_message_db():
	"""
	1. Check whether there is a database called message_db in the g attribute of the app. If not, then connect to that database.
	2. Check whether a table called messages exists in message_db.
	3. Return the connection g.message_db
	"""
	try:
		return g.message_db
	except:
		g.message_db = sqlite3.connect("messages_db.sqlite")
	cmd = \
	"""
	CREATE TABLE IF NOT EXISTS messages (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		message TEXT NOT NULL,
		handle TEXT NOT NULL)
	"""
	cursor = g.message_db.cursor()
	
	#execute the command
	cursor.execute(cmd)
	
	# return the connection g.message_db
	return g.message_db

Second, define a funtion insert_message(). This function should handle inserting a user message into the database of messages.

def insert_message():
	"""
	1.Extract the message and the handle from request.
	2.Using a cursor, insert the message into the message database.
	"""
	conn = get_message_db()

	# use request.form to get data when submitting a form with the POST method.
	cmd = \
	f"""
	INSERT INTO messages (message, handle)
	VALUES ("{request.form["message"]}", "{request.form["handle"]}")
	"""
	cursor = conn.cursor()

	# execute the command
	cursor.execute(cmd)
	conn.commit()
	
	# close the database connection
	conn.close()
	return request.form["message"], request.form["handle"]

Finally, write a function to render_template() the submit.html template.

@app.route('/submit/', methods=['POST', 'GET'])
def submit():
	if request.method == 'GET':
		return render_template('submit.html')
	else:
		try:
			# call the database function if successful submission
			message, handle = insert_message()
			return render_template('submit.html', thanks=True, message=message, handle=handle)
		except:
			return render_template('submit.html', error=True)

Here is the message submission interface. q0.png q1.png

2. Viewing Random Submissions

Create a view template. It will random show the message that users submit. w2.png Write a function random_messages(n). It will return a collection of n random messages from the message_db.

def random_messages(n):
	"""
	1. call the funtion get_message_db()
	2. random select the data from database
	"""
	db = get_message_db()
	r_m = db.execute(f"SELECT * FROM messages ORDER BY RANDOM() LIMIT {n}").fetchall()

	# close the database connection
	db.close()
	return  r_m

Define a function view(). It will render_template() the view.html template.

def view():
	return render_template('view.html', messages=random_messages(5))

Here is the message submission interface. q2.png q3.png

3.Customize My App

Write some CSS to customize my app.

html {
	font-family: sans-serif;
	background: rgb(247, 243, 244);
	background-image: url("https://www.2008php.com/2021_Website_appreciate/2022-03-05/20220305210134.jpg") ;
}

body {
	max-width: 900px;
	margin: 0  auto;
}

h1 {
	color: rgb(0, 0, 0);
	font-family: sans-serif;
	margin: 1rem  0;
	text-align: center;
}

a {
	color: CornflowerBlue;
	text-decoration: none;
}

nav {
	background: rgb(169, 222, 225);
	padding: 0  0.5rem;
	border-radius: 25px;
}

nav ul {
	display: flex;
	list-style: none;
	margin: 0;
	padding: 0;
}

  

nav ul li a {
	display: block;
	padding: 0.5rem;
}

.content {
	padding: 0  1rem  1rem;
	background: rgb(169, 222, 225);
	border-radius: 25px;
}

For more information, please check on https://github.com/TianliangTao/web-development/tree/main/hw.

Written on May 25, 2022