colab에서 flask 사용하기

semi·2020년 11월 19일
0

Web

목록 보기
1/2

예제 코드

!pip install flask-ngrok
from flask import Flask, url_for, redirect, render_template, request
from flask_ngrok import run_with_ngrok
import os

app = Flask(__name__)
run_with_ngrok(app)   #starts ngrok when the app is run

@app.route('/')
def index():
    return render_template('index.html')  # Start ngrok when app is run

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

flask web 구조

flask는 html 파일을 template 폴더 안에서, 나머지 js, css, image 파일 등은 static 폴더 안에서 참조를 한다. 기본적으로 template 폴더와 static폴더는 content/template, content/static로 경로 설정이 되어있는데 부득이하게 그러한 경로설정이 불가능할 경우 임의로 폴더 경로설정을 해줄 수 있다.

TEMPLATE_FOLDER = 'C:\temp\template' # 임의의 경로
STATIC_FOLDER = 'C:\temp\static' # 임의의 경로
app = Flask(__name__, template_folder=TEMPLATE_FOLDER, static_folder = STATIC_FOLDER)

위와 같은 코드로 폴더의 경로설정을 바꾸어줄 수 있다.

html 코드 안에서 동적 경로 설정

html상에 삽입된 정적 경로들은 위와 같이 경로를 임의로 변경하였을 때, 제대로 동작하지 않을 수 있다. 그럴 경우에 flask에서 rendering을 할 때 경로를 지정해주어 코드를 제대로 동작하도록 수정할 수 있다.

# 기존 index.html 코드
<img src="img/tmp_image.jpg">

# 수정된 index.html 코드
{% if True %}
	<img src="{{ url_for('static', filename=image_path) }}">
{% endif %}

# python flask 코드
@app.route('/')
def index():
    return render_template('index.html', image_path='img/tmp_image.jpg')

위와 같이 코드를 삽입하여 주면 코드가 경로를 제대로 참조하여 코드가 오류없이 동작하게 된다.

최종 예시 코드

  • index.html
<!DOCTYPE html>

<html lang="ko">

<head>
    <meta charset="utf-8">
    <title>Feeling, Healing</title>
    
    # css file
    <!-- <link rel="stylesheet" href="index.css"> -->
    {% if True %}
        <link rel="stylesheet" href="{{ url_for('static', filename=css_path) }}">
    {% endif %}
</head>

<body>
    <div class="image-div">
        {% if True %}
            <img src="{{ url_for('static', filename=about_image) }}">
        {% endif %}
    </div>
    
    # js file
    <!-- <script src="index.js"> -->
    {% if True %}
        <script src="{{ url_for('static', filename=js_path) }}"></script>
    {% endif %}
</body>
  • app.py
!pip install flask-ngrok
from flask import Flask, url_for, redirect, render_template, request
from flask_ngrok import run_with_ngrok
import os

TEMPLATE_FOLDER = 'C:\temp\template' # 임의의 경로
STATIC_FOLDER = 'C:\temp\static' # 임의의 경로
app = Flask(__name__, template_folder=TEMPLATE_FOLDER, static_folder = STATIC_FOLDER)
run_with_ngrok(app)   

@app.route('/')
def index():
    return render_template('index.html', image_path='img/tmp_image.jpg', css_path='index.css', js_path='index.js')

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

0개의 댓글