7. FLASK 기초

##### 7. FLASK 기초 #####
from flask import Flask # flask 패키지에서 Flask 클래스 가져오기
app = Flask(__name__)

### 기본 라우팅 ###
@app.route('/') # 해당 페이지를 웹 어플리케이션의 경로에 직접 연결함.
                # http://127.0.0.1:5000
def index():
    return '<h1>Hello Puppy!<h1>'

# 결과: * Running on http://127.0.0.1:5000
# 그리고 이 주소를 브라우저에 붙여 넣고 확인!

@app.route('/information')  # http://127.0.0.1:5000/information
def info():
    return '<h1>Puppies are cute!<h1>'

### 동적 라우팅 ###
# @app.route('/puppy/<name>') # http://127.0.0.1:5000/puppy/넣고 싶은 데이터
# def puppy(name):
#     return '<h1>This is a page for {}</h1>'.format(name)

# @app.route('/puppy/<name>')
# def puppy(name):
#     return 'Upper case: {}'.format(name.upper()) # -> 입력 받은 값을 다 대문자로 바꿔 보여줌.

### 디버그 ####
@app.route('/puppy/<name>')
def puppy(name):
    return '100th letter: {}'.format(name[100]) # 데이터의 100번째의 값을 돌려받으려고 함.

if __name__ == '__main__': # 스크립트를 실행하는 경우 애플리케이션을 실행.
    app.run(debug=True)    
# debug=True 옵션: 디버그 모드가 실행되어 어디서 에러가 났는지 확인 가능.
# * 참고-변수를 변경해보면서 확인하고 싶을 때: 
# 웹사이트 안 트레이스백의 단계마다 있는 콘솔 아이콘 누른 후 디버거 핀 번호를 입력하면 편리한 디버그 가능.
# (단, 배포할 땐 debug=True를 포함하면 안됨. -> 다른 사람들이 내부서버오류 대신 이 디버그 페이지를 통해 전체 트레이스백을 볼 수 있기 때문)

8. 템플릿

##### 8. 템플릿 #####
# render_template 함수를 가져와서
# view 함수에서 HTML 파일을 반환하여 템플릿을 렌더링하기

# 주의: 
# templates 경로와 basic.py 는 같은 레벨에 있어야 함.
# templates폴더 이름은 flask에서 지정한 것 같다. 절대 내 마음대로 바꾸지 않기.

from flask import Flask, render_template

app = Flask(__name__)

# @app.route('/')
# def index():
    # puppies = ['Fluffy', 'Rufus', 'Spike']
    # return render_template('basic.html', puppies=puppies)

    # name = "Jose"
    # letters = list(name)
    # pup_dictionary = {'pup_name':'Sammy'}
    # return render_template('basic.html', name=name, letters=letters,
    #                        pup_dictionary=pup_dictionary)

    # some_variable = "Jose"
    # return render_template('basic.html', my_variable=some_variable)

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

@app.route('/puppy/<name>')
def pup_name(name):
    return render_template('puppy.html', name=name)

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

본 후기는 정보통신산업진흥원(NIPA)에서 주관하는 <AI 서비스 완성! AI+웹개발 취업캠프 - 프론트엔드&백엔드> 과정 학습/프로젝트/과제 기록으로 작성 되었습니다.

profile
유후랄라 개발일기

0개의 댓글