Python

[Python] Flask

아잠만_ 2024. 7. 3. 12:44

Hello world 출력

from flask import Flask
from flask.globals import request

app = Flask(__name__)

# localhost
@app.route('/')
def index():
    return 'Hello World!'

if __name__ == '__main__':
    # app.run(debug=True)
    app.run(host="0.0.0.0", port=80)

GET방식

  • 파라미터 값 가져오기 (getParameter)
    • request.args.get('name값', default='초기값')

from flask import Flask
from flask.globals import request

app = Flask(__name__)

# localhost/param
@app.route('/param')
def param():
    arg = request.args.get('menu', default = '탕수육');
    return 'PARAM : {}'.format(arg)


if __name__ == '__main__':
    # app.run(debug=True)
    app.run(host="0.0.0.0", port=80)

POST 방식

  • post로 페이지 접근하기
    • @app.route('주소', methods=['POST'])
  • post방식으로 데이터 받기
    • request.form['name값']
    • request.form.get('name값', default='기본값')

from flask import Flask
from flask.globals import request

app = Flask(__name__)

# localhost/post
# method를 붙이지않으면 get방식이므로 꼭 post를 넣어야한다
# get 방식도 받을땐 methods=['POST', 'GET']
@app.route('/post', methods=['POST'])
def post():
    arg = request.form['menu'];
    # arg = request.form.get('menu', default='짬뽕')
    return 'POST : {}'.format(arg)

if __name__ == '__main__':
    # app.run(debug=True)
    app.run(host="0.0.0.0", port=80)

Forward방식

  • render_template("html이름")
    • 해당 html은 같은 폴더 내의 templates라는 폴더 안에 존재해야한다
from flask import Flask
from flask.globals import request
from flask.templating import render_template

app = Flask(__name__)

# localhost/forw
@app.route('/forw')
def forw():
    # 해당 위치에 templates 폴더를 생성해 html을 넣어줘야 정상 실행된다
    return render_template("forw.html")

if __name__ == '__main__':
    # app.run(debug=True)
    app.run(host="0.0.0.0", port=80)
localhost/forw를 입력하면 forward방식으로 forw.html파일로 넘어가게되는데
이때 url은 forw.html이 아닌 localhost/forw가 그대로 유지된다 이것이 forward방식이다

redirect는 그대로 주소를 넘겨주는 것이므로 url이 변경된다

Forward 데이터 전달

java flask
request.setAttribute("data", a);
request.getRequestDispatcher("url이름").forward(request, response)
render_template("url이름", data=a)
(JSTL을 통한)
<%c:set var="data" value="<%=data %>">
${data}
{{data}}
  • 데이터 전달
    • render_template("url이름", 이름='전달할 변수')
    • 해당 이름을 통해 html에서 {{이름}}을 입력하면 html에서 출력된다
  • 전달받은 데이터를 출력시 html에서 사용하는 방법
    • {% ... %} - 문장(Sentences)
    • {{ ... }} - 표현식(Expressions)
    • {# ... #} - 주석
    • # ... ## - 라인 문장
from flask import Flask
from flask.globals import request
from flask.templating import render_template

app = Flask(__name__)

# localhost/forw
@app.route('/forw')
def forw():
    a = "홍길동"
    b = ["오리", "거위"]
    # 연관 배열, 사전식 배열, 딕셔너리
    c = [
            {'e_id' : 1, 'e_name':'1', 'gen':'1', 'addr':'1'},
            {'e_id' : 2, 'e_name':'2', 'gen':'2', 'addr':'2'},
            {'e_id' : 3, 'e_name':'3', 'gen':'3', 'addr':'3'}
        ]
    # 해당 위치에 templates 폴더를 생성해 html을 넣어줘야 정상 실행된다
    return render_template("forw.html", data=a, list=b, c=c)
    
if __name__ == '__main__':
    # app.run(debug=True)
    app.run(host="0.0.0.0", port=80)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
FORW HTML화면<br>
{{data}}<br>

{% for i in list %}
	{{i}}<br>
{% endfor %}

<table border="1">
	<tr>
		<th>사번</th>
		<th>이름</th>
		<th>성별</th>
		<th>주소지</th>
	</tr>
{% for i in c %}
	<tr>
		<td>{{i.e_id}}</td>
		<td>{{i.e_name}}</td>
		<td>{{i.gen}}</td>
		<td>{{i.addr}}</td>
	</tr>
{% endfor %}
</table>
</body>
</html>

DB연동

from flask import Flask
from flask.globals import request
from flask.templating import render_template
import pymysql

app = Flask(__name__)

# localhost
@app.route('/')
def index():
    conn = pymysql.connect(host='127.0.0.1', 
                       port=3305,
                       user='root', 
                       password='python',
                       db='python', 
                       charset='utf8')

    # DictCursor, Python에서 MySQL 쿼리 결과에 컬럼 자동으로 붙이기
    # 칼럼이름 : value형식으로 출력됨
    cur = conn.cursor(pymysql.cursors.DictCursor)
    # sql문
    sql = f"""
        SELECT *
        FROM emp
        """
        # sql문을 cur에 입력
    cur.execute(sql)
    # 데이타 Fetch (가져오기)
    rows = cur.fetchall()
    return render_template("emp_list.html", row=rows)

if __name__ == '__main__':
    # app.run(debug=True)
    app.run(host="0.0.0.0", port=80, debug=True)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>EMP LIST Page</h3>
<table border="1">
	<tr>
		<th>사번</th>
		<th>이름</th>
		<th>성별</th>
		<th>주소지</th>
	</tr>
{% for i in row %}
	<tr>
		<td>{{i.e_id}}</td>
		<td>{{i.e_name}}</td>
		<td>{{i.gen}}</td>
		<td>{{i.addr}}</td>
	</tr>
{% endfor %}
</table>
</body>
</html>