flask

Flask


참고 사이트


설치


시작하기


from flask import Flask # 모듈 import
app = Flask(__name__) # 애플리케이션 객체 생성

@app.route('/') # route() 데코레이터
def hello_world(): # View 함수
    result = 'hello world!'
    return result

if __name__ == '__main__':
    app.debug = True
    app.run()

플라스크 애플리케이션 실행 순서


라우팅


from flask import Flask # 모듈 import
app = Flask(__name__) # 애플리케이션 객체 생성

@app.route('/') # route 데코레이터
def root_world(): # View 함수
    result = 'root world!'
    return result

@app.route('/hello') # route 데코레이터
def hello_world(): # View 함수
    result = 'hello world!'
    return result

if __name__ == '__main__':
    app.debug = True
    app.run()

라우팅에 값 전달


@app.route('/users/<userid>') # route 데코레이터
def user_id(userid): # View 함수
    result = 'user_id = ' + userid
    return result
from flask import Flask

app = Flask(__name__)

@app.route('/')
def root_world():
    result = 'root world!!'
    return result

@app.route('/hello')
def hello_world():
    result = 'hello world!'
    return result

@app.route('/users/< userid >') # route 데코레이터
def user_id(userid): # View 함수
    result = 'user_id = ' + userid
    return result

if __name__ == '__main__':
    app.debug = True
    app.run()
from flask import Flask, redirect, url_for
app = Flask(__name__)

@app.route('/admin')
def hello_admin():
   return 'Hello Admin'

@app.route('/guest/< gurest > ')
def hello_guest(guest):
   return 'Hello %s as Guest' % guest

@app.route('/user/')
def hello_user(name):
   if name =='admin':
      return redirect(url_for('hello_admin'))
   else:
      return redirect(url_for('hello_guest',guest = name))

if __name__ == '__main__':
   app.run(debug = True)

HTML 템플릿






    login_form_get.html 



    user ID:  
    user PWD:  








    login_form_get.html 



    user ID:  
    user PWD:  




GET 방식으로 값 전송 및 처리


@app.route('/login_form_get')
def login_form_get():
    return render_template('login/login_form_get.html')

@app.route('/login/login_get_proc', methods=['GET'])
def login_get_proc():
    user_id = request.args.get('user_id')
    user_pwd = request.args.get('user_pwd')

    if len(user_id) == 0 or len(user_pwd) == 0:
        return user_id+', '+ user_pwd + ' 로그인 정보를 제대로 입력하지 않았습니다.'

    return user_id + ' 님 환영합니다.' 

POST방식으로 값 전송 및 처리


@app.route('/login_form_get')
def login_form_get():
    return render_template('login/login_form_get.html')

@app.route('/login/login_get_proc', methods=['GET'])
def login_get_proc():
    user_id = request.args.get('user_id')
    user_pwd = request.args.get('user_pwd')

    if len(user_id) == 0 or len(user_pwd) == 0:
        return user_id+', '+ user_pwd + ' 로그인 정보를 제대로 입력하지 않았습니다.'

    return user_id + ' 님 환영합니다.' 

Flask 에서 HTML 처리 하기


from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
   html = "Hello World"
   return html

@app.route('/users/') # route 데코레이터
def user_id(userid): # View 함수

    html = " User Id : "
    html = html + userid
    html = html + ""

    return html

if __name__ == '__main__':
   app.run(debug = True)

Jinja2 템플릿



@app.route('/users/') # route 데코레이터
def user_id(userid): # View 함수

    return render_template('userid_view.html', userid=userid)


    Title


 User Id : {{ userid }}

Jinja2 템플릿 : 리스트(list) , 튜블(tuple) 등 전달


@app.route('/plays')
def palys():
    games = ('갤러그', '너구리', '리니지')
    sports = ['야구', '축구', '농구']
    return render_template('plays/play.html', title='PLAYS', games=games, sports=sports, )




    Title


    {#
        jinja template comment
        http://jinja.pocoo.org/docs/
    #}
     - title : {{ title }}

    Sports
    {% for i in sports  %}
         {{ i }} 
    {% endfor %}

    Games
    {% for i in games  %}
         {{ i }} 
    {% endfor %}


Jinja2 템플릿 : 딕셔너리(dict) 전달






    Title



           * Games Input * 
         갤러그 
         너구리 
         리니지 



@app.route('/result',methods = ['POST', 'GET'])
def result():
   if request.method == 'POST':
      result = request.form
      return render_template("plays/result.html",result = result)




    Title



         {% for key, value in result.items() %}

         {% endfor %}

                {{ key }} 
                {{ value }} 


로그인 및 세션 생성


@app.route('/login_form')
def login():
    return render_template('login_form.html')

@app.route('/login_proc', methods=['POST'])
def login_proc():
    if request.method == 'POST':
        userId = request.form['id']
        userPwd = request.form['pwd']

        if len(userId) == 0 or len(userPwd) == 0:
            return userId+', '+userPwd+' 로그인 정보를 제대로 입력하지 않았습니다.'

        session['logFlag'] = True
        session['userId'] = userId
        return session['userId'] + ' 님 환영합니다.'
    else:
        return '잘못된 접근입니다.'

app.secret_key = 'sample_secreat_key'




    Title


    {{ session<'logFlag'> }} 
    {{ session<'userId'> }}

sqlite3 db 및 table생성


# file_name : sqlite_con.py
import sqlite3

con = sqlite3.connect("python.db")
cursor = con.cursor()

def insertDb():
    cursor.execute("drop table member")
    sql = "create table member("
    sql = sql + " idx INTEGER PRIMARY KEY AUTOINCREMENT "
    sql = sql + ",userId TEXT NOT NULL"
    sql = sql + ", userPwd TEXT NOT NULL"
    sql = sql + ", userEmail TEXT, regDate DEFAULT (datetime('now', 'localtime')) )"
    cursor.execute(sql)

    insert_sql = "insert into member(userId, userPwd, userEmail) values( "
    insert_sql = insert_sql + "'kim', 'kimpass','kim@email.com')"
    cursor.execute(insert_sql)

    insert_sql = "insert into member(userId, userPwd, userEmail) values( "
    insert_sql = insert_sql + "'lee', 'leepass','lee@email.com')"
    cursor.execute(insert_sql)

    insert_sql = "insert into member(userId, userPwd, userEmail) values( "
    insert_sql = insert_sql + "'park', 'parkpass','park@email.com')"
    cursor.execute(insert_sql)

    con.commit()

def readDb():
    cursor.execute("select * from member")
    rows = cursor.fetchall()
    for rs in rows:
        print(rs)
        #print(rs[0])
        #print(rs[1])

def main():
    #insertDb() # 1. talbe 생성 및 더미 자료 입력
    #readDb() # 2. 입력 확인
    con.close

if __name__ == '__main__':
    main()

로그인 체크 로직 변경


from flask import Flask, request, session, render_template, redirect, url_for
import sqlite3

app = Flask(__name__)

@app.route('/main')
def main():
    return render_template('main.html')

@app.route('/login_form')
def login():
    return render_template('login/login_form.html')

@app.route('/login_proc', methods=['post'])
def login_proc():
    userId = request.form['user_id']
    userPwd = request.form['user_pwd']

    if len(userId) == 0 or len(userPwd) == 0:
        return userId + ', ' + userPwd + ' Login Data Not Found.'
    else:
        con = sqlite3.connect("python.db")
        cursor = con.cursor()
        sql = "select idx, userId, userPwd  from member where userId = ?"
        cursor.execute(sql,(userId,))
        rows = cursor.fetchall()
        for rs in rows:
            if userId == rs[1] and userPwd == rs[2]:
                session['logFlag'] = True
                session['idx'] = rs[0]
                session['userId'] = userId

                return redirect(url_for('main'))
            else:
                return "member not found"

app.secret_key = 'sample_secreat_key'

if __name__ == '__main__':
    app.debug = True
    app.run()




    Title


{% if session.get('logFlag') %}
userId : {{ session.get('userId')}} 
로그아웃
{% else %}
로그인
{% endif %}

로그인 정보 수정


@app.route('/user_info_edit/', methods=['GET'])
def getUser(edit_idx):

    if session.get('logFlag') != True:
        return redirect(url_for('login'))

    con = sqlite3.connect("python.db")
    cursor = con.cursor()
    sql = "select userEmail  from member where idx = ?"
    cursor.execute(sql,(edit_idx,))
    row = cursor.fetchone()
    edit_email = row[0]
    return render_template('users/user_info.html', edit_idx=edit_idx, edit_email=edit_email)




    Title





    Edit User ID : {{ session.get('userId')}} 
    User PWD :  
    User Email :  

    <취소> 



@app.route('/user_info_edit_proc', methods=['post'])
def user_info_edit_proc():
    h_edit_idx = request.form['h_edit_idx']
    userPwd = request.form['userPwd']
    userEmail = request.form['userEmail']

    if len(h_edit_idx) == 0:
        return ' Edit Data Not Found.'
    else:
        con = sqlite3.connect("python.db")
        cursor = con.cursor()
        update_sql = "update member set userPwd = ?, userEmail = ? where idx = ?"

        cursor.execute(update_sql, (userPwd, userEmail, h_edit_idx))

        con.commit()

        return redirect(url_for('main'))

로그 아웃


@app.route('/logout', methods=['POST','GET'])
def logout():
    session.clear()
    return redirect(url_for('main'))

리스트 페이징 하기(list paging)






    lists.html



MiniBoard List 전체


    {% for i in lists  %}
    {{ i }}
    {% endfor %}







    miniboard 페이징 list



MiniBoard List


    {% for i in lists  %}
    {{ i }}
    {% endfor %}


        {% for i in range(page_count)  %}

        {% endfor %}

    <{{ i+1 }}>


#miniboard_run.py
from flask import Flask, request, session, render_template, url_for
import sqlite3
import math

app = Flask(__name__)

def selecte():

    con = sqlite3.connect("python.db")
    cursor = con.cursor()

    cursor.execute("select * from miniboard where idx = ? order by idx desc",(3,))
    rows = cursor.fetchall()
    con.close()
    return rows

def selecte_page(list_limit, page):

    con = sqlite3.connect("python.db")
    cursor = con.cursor()

    offset = (page-1) * list_limit
    sql = "select * from miniboard order by idx desc limit ? offset ?"

    cursor.execute(sql, (list_limit, offset))
    rows = cursor.fetchall()
    con.close()
    return rows

def select_count():

    con = sqlite3.connect("python.db")
    cursor = con.cursor()

    cursor.execute("select count(idx) from miniboard")
    rows = cursor.fetchone()
    con.close()
    return rows[0]

def list_test():
    list = selecte()
    print(list)

@app.route('/lists')
def lists():
    lists = selecte()
    return render_template('miniboard/lists.html', lists=lists)

@app.route('/list/')
def list(page):
    list_num = 5
    lists_count = select_count()
    page_count = int(lists_count/list_num)
    #page_count = math.ceil(lists_count/list_num)

    lists = selecte_page(list_num, page)

    return render_template('miniboard/list.html', lists=lists, page_count=page_count)

if __name__ == '__main__':
    #app.run(debug=True)
    list_test()