본문 바로가기
카테고리 없음

flask-web develope

by ByteBridge 2016. 4. 2.
반응형


flask 로 개발할 웹 페이지는 대략 아래와 같다.

1. 회원가입

2. 로그인

3. 메시지 쓰기

4. 메시지에 코멘트 달기


데이터베이스 다이어그램은 아래와 같다.





먼저 mysql  connection 을위한 설정을 한다.

sudo -H pip install --allow-external mysql-connector-python-rf mysql-connector-python-rf


mysql connetion.py 에 데이터 베이스 연결 설정을 한다.

import mysql.connector

import collections


def _convert(data):

    if isinstance(data, basestring):

        return str(data)

    elif isinstance(data, collections.Mapping):

        return dict(map(_convert, data.iteritems()))

    elif isinstance(data, collections.Iterable):

        return type(data)(map(_convert, data))

    else:

        return data

# Create a class that will give us an object that we can use to connect to a database

class MySQLConnection(object):

    # init method with configurations.

    def __init__(self, db):

        """ BEGIN DATABASE CONFIGURATIONS """

        self.config = {

            'user': 'root',

            'password': 'kgs8337', # Change this for windows users

            'database': db,

            'host': 'localhost',

            # comment out the line below for windows

            # 'unix_socket': '/Applications/MAMP/tmp/mysql/mysql.sock'

            # comment out the line below for mac

            'unix_socket': '/tmp/mysql.sock',

        }

        self.conn = mysql.connector.connect(**self.config)

    """ BELOW ARE THE CUSTOM FUNCTIONS WE BUILT FOR YOU TO USE """

    """

    fetch function should be used for queries that return multiple rows

    Rows are returned in a list of tuples with each tuple corresponding to a row

    """

    # Begin fetch

    def fetch(self, query):

        cursor = self.conn.cursor(dictionary=True)

        cursor.execute(query)

        data = list(cursor.fetchall())

        cursor.close()

        return _convert(data)

    """

    run_mysql_query function should be used for INSERT/UPDATE/DELETE queries

    returns the number of rows affected

    """

    # Begin run_mysql_query

    def run_mysql_query(self, query):

        cursor = self.conn.cursor(dictionary=True)

        data = cursor.execute(query)

        self.conn.commit()

        cursor.close()

        return data

    def escape_string(self, query):

        string_escaper = self.conn.converter.escape

        escaped_string = string_escaper(query)

        return escaped_string

# This is the module method to be called by the user in server.py. Make sure to provide the db name!

def MySQLConnector(db):

    return MySQLConnection(db)


server.py 에서 해당 request,response , session,flash messag,render,redirect, bcrypt,route 설정을 해준다.



from flask import Flask,render_template,redirect,request,session,flash

import re

from flask.ext.bcrypt import Bcrypt

from mysqlconnection import MySQLConnector


app=Flask(__name__)

b=Bcrypt(app)

app.secret_key="2342asfkjawesld234kfjsld123111"

mysql = MySQLConnector('wall')


EMAIL_REGEX=re.compile(r'^[a-zA-Z0-9\.\+_-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]*$')


@app.route('/',methods=['GET'])

def index():

return render_template("index.html")


@app.route('/register',methods=['GET'])

def init_register():

return render_template("/register.html")


@app.route('/register',methods=['POST'])

def register():

#check email

if len(request.form['email'])<1:

flash('Email cannot be blank!')

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')

else:

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')

else:

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 해 줄 수 있다.


파일 첨부

index.html


register.html


wall.html


반응형