Flask 시작하기


Python 다운로드

[IDE] Pycham 다운로드

Pycham 에서 flask 시작하기

1. Project 생성

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'


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

2. 실행해보기

  1. ide로 실행하기
    • 우측 “Run” 버튼 클릭!
  2. 명령어로 실행하기
> python start_flask.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

2-1. Debug 모드로 실행하기

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    app.run(debug=True) # Debugger is active!

3. Routing

@app.route('/tuna')
def tuna():
    return '<h2>Tuna is good</h2>'
@app.route('/profile/<username>') # plain string
  def profile(username):
    return '<h3>hey there %s</h3>' % username

@app.route('/post/<int:post_id>') # specific type
  def show_post(post_id):
    return '<h3>Post ID is %s</h3>' % post_id

4. Http method

from flask import Flask, request

## HTTP method : import request
@app.route('/method')
def method():
    return 'Method used : %s' % request.method

@app.route('/bacon', methods=['GET', 'POST'])
def bacon():
    if request.method == "POST":
        return 'You are using POST'
    else:
        return 'You are probably using GET'

5. HTML Templates

from flask import Flask, request, render_template
# need packages : templates , static
@app.route('/profile/<name>')
def profileWithTemplate(name):
    return render_template('profile.html', name=name)
<!-- profile.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Welcome!</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='style.css')}} " /> <!-- dynamic generate path-->
</head>
<body>
<h1>Hey! there {{name}}, yo!</h1>
</body>
</html>
## Mapping Multiple URLs
@app.route('/multi')
@app.route('/multi/<user>')
def multi(user=None): ## None by default
    return render_template('user.html', user=user)
<!-- user.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Welcome!</title>
    <link rel="stylesheet" type="text/css" href="" /> <!-- dynamic generate path-->
</head>
<body>
    <h1>Hey! there , yo!</h1>
</body>
</html>
## Passing Objects into Templates
@app.route('/shopping')
  def shopping():
    food = ["Cheese", "Tuna", "Beef"]
    return render_template('shopping.html', food=food)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Shopping</title>
</head>
<body>
    <ul>
        
    </ul>
</body>
</html>

Github repository