flask 로 개발할 웹 페이지는 대략 아래와 같다.
1. 회원가입
2. 로그인
3. 메시지 쓰기
4. 메시지에 코멘트 달기
데이터베이스 다이어그램은 아래와 같다.
먼저 mysql connection 을위한 설정을 한다.
mysql connetion.py 에 데이터 베이스 연결 설정을 한다.
# Create a class that will give us an object that we can use to connect to a database
#
""" BEGIN DATABASE CONFIGURATIONS """
'
'
'
'
# comment out the line below for windows
# 'unix_socket': '/Applications/MAMP/tmp/mysql/mysql
# comment out the line below for
'unix_socket': '/tmp/mysql
}
""" BELOW ARE THE CUSTOM FUNCTIONS WE BUILT FOR YOU TO USE """
"""
Rows are returned in a list of tuples with each tuple corresponding to a row
"""
# Begin fetch
"""
run_mysql_query function should be used for INSERT/UPDATE/DELETE queries
"""
# Begin run_mysql_query
self.conn.commit
string_escaper = self
escaped_string = string_escaper
# This is the module method to be called by the user in server
app=Flask
b=Bcrypt
EMAIL_REGEX=re.compile(r'^[a-zA-Z0-9\.\+_-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]*$')
@app
@app
@app
#check email
if len(request.form['email'])<1:
return redirect('/register')
elif not EMAIL_REGEX.match(request.form['email']):
flash('Invalid Email Address!')
return redirect('/register')
elif len(request.form['first_name'])<1:
flash('first_name cannot be blank!')
return redirect('/register')
elif len(request.form['last_name'])<1:
flash('last_name cannot be blank!')
return redirect('/register')
elif len(request.form['password'])<3:
flash('password short! password is more than 8 character ')
return redirect('/register')
elif request.form['password_confirmation'] != request.form['password']:
flash('password not match ! ')
return redirect('/register')
first_name=request.form['first_name']
last_name=request.form['last_name']
email=request.form['email']
password=request.form['password']
password_hash=b.generate_password_hash(password)
sql = "INSERT INTO Users (first_name, last_name, email, password) values('{}', '{}', '{}', '{}')".format(first_name, last_name, email, password_hash)
mysql.run_mysql_query(sql)
return redirect("/")
@app.route('/login',methods=['POST'])
def login():
email = request.form['email']
password = request.form['password']
sql = "select * from users where email = '{}'".format(email)
user = mysql.fetch(sql)
if len(user) > 0 and b.check_password_hash(user[0]['password'], password):
session['user_id'] = user[0]['id']
session['first_name'] = user[0]['first_name']
return redirect('/wall')
return redirect('/')
@app.route('/logout')
def logout():
session.clear()
return redirect('/')
@app.route('/wall')
def wall():
user_ql = "select id, first_name, last_name from users where id = '{}'".format(session['user_id'])
user = mysql.fetch(user_ql)
messages_sql = "SELECT messages.id, users.first_name, messages.message, messages.created_at from messages join users on messages.users_id = users.id"
messages = mysql.fetch(messages_sql)
comments_sql = "SELECT comments.comment, comments.created_at, comments.updated_at, comments.messages_id, comments.users_id, users.first_name from comments join users on comments.users_id = users.id"
comments = mysql.fetch(comments_sql)
return render_template('wall.html', user=user[0], messages = messages, comments = comments)
@app.route('/messages', methods=["post"])
def message():
sql = "INSERT INTO messages (message, users_id, created_at, updated_at) values('{}', '{}', NOW(), NOW())".format(re.escape(request.form['message']), request.form['user_id'])
mysql.run_mysql_query(sql)
return redirect('/wall')
@app.route('/comments', methods=["post"])
def comment():
sql = "INSERT INTO comments (comment, messages_id, users_id, created_at, updated_at) values ('{}', '{}', '{}', NOW(), NOW())".format(request.form['comment'], request.form['message_id'], request.form['user_id'])
mysql.run_mysql_query(sql)
return redirect('/wall')
app.run(debug=True)
웹 페이지 html 은 파일로 첨부.
해당 html 페이지는 template 폴더에 있어야 flask 가 html 을 찾아서 render 해 줄 수 있다.
파일 첨부