Python/Flask

Python Flask : install / why use / routing / example

만 기 2022. 10. 18. 19:40

Flask web framework

 

1. 설치

pip install Flask

 

2. base

from flask import Flask

app=Flask(__name__)

@app.route('/')
def index():
    return 'hi'

if __name__ == "__main__":
    app.run(port=5001, debug=True)

 

3. Why use

  • web framework는 web application을 구현하는데 필요한 공통적인 기능을 제공해서 시간과 비용을 절약 할 수 있다.
  • 사용자 정의 웹서버를 만들 수 있다.
  • 동적 html을 만든다.
    • return값은 string( 또는 dict, tuple) type 이어야 한다.
    • return값으로 html 태그를 문자열 형태로 넣어줄 수 있다.
  • @app.route('/') def index(): return 'random : <strong>'+str(random.random())+'</strong>'

 

4. 라우팅

Routing : url로 들어오는 요청에 해당하는 응답을 연결시켜주는 작업

web framework를 사용할 때 web framework는 라우팅을 어떻게 하는지부터 알아야 함

Flask 공식 문서

@app.route('/')
def index():
    return 'Welcome'

@app.route('/create/')
def create():
    return 'Create'

@app.route('/read/<id>/')
def read(id):
    return 'Read'+id
  • app.route() 괄호 안에 decorator 자리에 URL 이 들어간다.
  • URL에 들어가는 variable section은 <> 처리하고 함수 인자로 받는다.

 

5. 홈페이지 구현

from flask import Flask
import random

app=Flask(__name__)

topics = [
    {'id':1, 'title':'html', 'body':'html is...'},
    {'id':2, 'title':'css', 'body':'css is...'},
    {'id':3, 'title':'javascript', 'body':'javascript is...'}
]

@app.route('/')
def index():
    liTags = ''
    for topic in topics:
        liTags = liTags + f'<li><a href="/read/{topic["id"]}/">{topic["title"]}</a></li>'
    return f'''<!doctype html>
    <html>
        <body>
            <h1><a href="/">WEB</a></h1>
            <ol>
                {liTags}
            </ol>
            <h2>Welcome</h2>
            Hello, Web
        </body>
    </html>
    '''

@app.route('/read/<id>/')
def read(id):
    return 'Read'+id

if __name__ == "__main__":
    app.run(port=5001, debug=True)
  • topics에 들어가는 리스트에는 데이터베이스를 읽어오는 코드가 들어가면 된다.

'Python > Flask' 카테고리의 다른 글

Python Flask : CRUD  (0) 2022.10.18
Flask - CORS  (0) 2022.05.21