개발일지/삽질

1.2) 서울시 지가 선형회귀모델 프로젝트 개발 환경설정 Flask & Bootstrap template

Millennials 2021. 10. 6. 21:44

이번에는 Flask library 개발 환경을 설정하고, 기본적인 Bootstrap template과 연동시켜 창을 띄울것이다.

1. Flask library 설치
$ pip install flask
2. __init.py 파일 생성
# __init__.py
from flask import Flask

app = Flask(__name__)

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

if __name__ ==  '__main__':
    app.run()
3. Flask 서버 가동 테스트
$ FLASK_APP=seoul_landprice_model flask run

위 코드 실행시 아래와 같은 터미널이 출력되어야 한다.

http://127.0.0.1:5000/ 을 CTRL + 클릭 했을 때,

화면에 Hello World!가 뜬다면 서버가 정상적으로 작동하는 것이다.

 

서버가 정상적으로 작동한다면 그대로 두고 

새로운 터미널을 열어서 작업하도록하자

4. Bootstrap templete 다운로드

이번프로젝트에서는 https://startbootstrap.com/ 에서 무료로 배포되는 템플릿을 활용할 생각이다.

https://startbootstrap.com/previews/grayscale 에서 템플릿을 받아서 seoul_landprice_model 폴더에 넣는다.

 

5. render_template를 통해 index.html과 연결
#__init__.py
from flask import Flask
from flask import render_template

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')
 
if __name__ ==  '__main__':
   app.run(debug=True)  # debug 모드 on

아까 helloworld를 지우고 render_template('index.html') 을 넣어 index.html을 찾아오도록 한다.

app.run(debug=True)로 수정하여 debug 모드를 가능하도록 만들었다.

 

그렇게 바꾼 후 flask run을 해보면 아래처럼 에러가 발생한다.

TemplateNotFound 에러가 발생하는데

그 이유는 아직 Bootstrap으로 받은 파일의 폴더이름을 안바꾸었기 때문이다.

6. Bootstrap에서 받은 파일 이름 바꾸기 및 경로 수정

기존 html과는 조금 달리 Flask를 사용하기 위해서는 경로가 어느정도 정해져 있어, 그 경로대로 템플릿이나 이미지를 넣지 않으면 제대로 불러오지 못한다.

1) 폴더의 이름 templates으로 변경한다.

2) static 이라는 상위 폴더를 만들어 css, js 그리고 img 폴더를 넣어 아래의 스키마 형태로 만든다.

프로젝트폴더
|_ __init__.py
|_ static
|	|_ css
|	|_ img
|	|_ js
|_ template
	|_index.html

3) index.html 에서 부트스트랩을 제대로 불러올 수 있겠끔 아래 코드를 <head> 탭에 삽입한다.

<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>

 4) index.html 내의 css,js,img 경로를 수정한다.

현재 이미지 파일들의 경로가 "assets/img/~~.jpg"로 설정되어 있는데, 이를 "static/img/~~.jpg"로 수정한다.

css와 js의 경로에도 앞에 static을 붙여 제대로 찾아올 수 있도록 만든다.

<link href="static/css/styles.css" rel="stylesheet" />
7. flask 실행 확인

이제 제대로 불러와 지는것을 확인할 수 있다.

 

반응형