Skip to content

Latest commit

 

History

History
174 lines (133 loc) · 4.06 KB

2019-12-12-Flask.md

File metadata and controls

174 lines (133 loc) · 4.06 KB
title category
flask
Programming

Flask

시작

Flask 공식사이트에서 Flask사용법을

# hello.py
from flask import Flask, escape, request

app = Flask(__name__)

# request를 함수에 연결해주는 데코레이션
@app.route('/')
# /경로로 request가 들어오면 hello()함수가 실행됨
def hello():
    name = request.args.get("name", "World")
    return f'Hello, {escape(name)}!'

위 base코드를 python 파일로 저장한 뒤에 아래 명령어로 flask를 실행시킨다.

env FLASK_APP=hello.py flask run

그러고

http://127.0.0.1:5000/ 경로에 접속하면 위에 작성한 hello() 함수가 실행되면서 웹페이지에 문자가 출력된다.

예제

기본 예제 1

# http://127.0.0.1:5000/hi 에 요청하면 hi 를 출력해주는 코드
@app.route('/hi')
def hi():
    return 'hi'

기본 예제 2

# http://127.0.0.1:5000/html_tag 에 요청하면 html코드를 출력해주는 코드
@app.route('/html_tag')
def html_tag():
    return '<h1>안녕하세요</h1>'

템플릿 렌더링을 이용한 방법

먼저 flask에서 render_template를 import해온다.

from flask import render_template

templates 폴더안에 html 파일을 만들어놓고 다음과 같이 render_template 메서드를 이용해 렌더링 할 수 있다.

# http://127.0.0.1:5000/html_file 에 요청하면 /templates 에 있는 index.html파일을 렌더링해서 보여준다.
@app.route('/html_file')
def html_file():
    return render_template('index.html')

render_template을 통해 변수를 html 에 전달하여 렌더링 하는 방법

# http://127.0.0.1:5000/varialbe 에 요청하면 name에 들어있는 문자열이 html_name이라는 변수로 /templates 에 있는 variable.html파일을 렌더링해서 보여준다.
# 이때 변수는 {{}} 안에 선언하여 보여줄수 있다. <jinja2 참조>
@app.route('/variable')
def varialbe():
    name = '지민'
    return render_template('variable.html', html_name=name)
<!-- /templates/variable.html --> 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>{{html_name}}님 안녕하세요~</h1>
</body>
</html>

주소로 변수 받아오는법

# http://127.0.0.1:5000/greeting/jimin 에 요청하면 jimin이 파이썬에서 name이라는 변수로 받아와서 다음과 같이 사용할 수 있다.
@app.route('/greeting/<string:name>/')
def greeting(name):
    def_name = name
    return render_template('greeting.html', html_name = def_name)

핑퐁 예제

ping에 접속하면 form을 통해 pong에 http POST를 할수 있다.

ping

/pong 에 POST를 받으면 다음과 같이 출력한다.

pong

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

@app.route('/pong', methods=['GET', 'POST'])
def pong():
    #keyword = request.args.get('keyword') #get방식
    keyword = request.form.get('keyword')
    # keyword
    return render_template('pong.html', keyword = keyword)
<!-- /templates/ping -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form action='/pong' method='post'>
        <input type='text' name='keyword'>
        <input type="submit">
    </form>
</body>
</html>
<!-- /templates/pong -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>여기는 pong입니다</h1>
    <h2>정보 = {{keyword}}</h2>
</body>
</html>