본문 바로가기
개발일지/Flask

Flask - [2일차 - (한글자막)Python FLASK로 웹사이트 만들기]

by 개발에정착하고싶다 2022. 12. 28.
320x100

오늘은 flask 탬플릿문 활용하는 것에 대해서 학습을 했다.

탬플릿문이 없으면 사실상 flask든 장고든 쓰는 의미가 없다고 생각이 들정도로

핵심중의 핵심인 부분이라고 생각한다.

그 중에서 생각지는 않았지만 중요한 몇가지들을 배울 수 있었다.


#1 templates 폴더의 등록 불필요

 

django의 경우는 templates폴더의 파일들을 가져오려면

프로젝트 단위의 settings.py에 들어가서 templates 경로를 BASE_DIR / 'templates'

라고 설정을 해줘야 작동되는 반면에, flask는 보니깐

내가 실질적으로 실행하는 파이썬 파일과 templates폴더가 동등선상에 위치해 있다면 그것으로 충분한 것 같다 (이건 완전 확실한건 아니고 차차 두고 봐야할 일이지만 지금까지 봐서는 그러하다)


#2 url_for

 

url_for라는 문법은 처음봤다. 이건 django랑 확실히 다른 것 같다.

가령 html 파일에서 a태그를 사용할때

# templates/base.html

<a class="navbar-brand" href="{{ url_for('index') }}">Home Page</a>

이렇게 써주는데, 이때 여기서 index는 이 html에 연결되어있는 파이썬 파일의 index 함수 혹은 클래스를 의미한다.

그래서 연결되어있는 파이썬 파일로 가보면

# index.py

from flask import Flask, render_template, request

app = Flask(__name__)

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

index는 이렇게 되어있다.

그러면 index 함수에서는 index.html을 끌어와 쓰는 건데 index.html은

# templates/index.html

{% extends 'base.html' %}

{% block content %}
<div class="jumbotron">
    <h1>Welcome to Puppy User Name Check</h1>
    <h1>Let's see if your User Name is secure!</h1>
    <h1>Fill out the below with a User Name that has these restraints</h1>

    <form action="{{ url_for('report') }}">
        <label for="username">User Name:</label>
        <input type="text" name="username">
        <input type="submit" value="Submit Form">
    </form>
</div>
{% endblock  %}

이렇게 구현이 되어있다.

 

무엇보다 중요한 것은 index.py에서 이미 

@app.route('/')

를 통해서 "메인페이지로 이동"한다 = 메인페이지로 활용한다. 라는 뜻도 된다는 점이 중요하다고 생각한다.


#3 문장에 소문자, 대문자, 숫자 있는지 판별하여 에러처리하기

 

이거는 사실 생각하려면 생각할 수 있었겠지만, 나에게는 시간이 없다 다시 무한 인풋의 시간이 다가왔기에 생각을 할 시간보다는 무한 인풋으로 다시 해야한다는 사실이 안타깝지만.. 암튼.. 중요한 부분이였기 때문에 적고 넘어가야겠다.

# index.py

@app.route('/report')
def report():

    # 여기 나오는 조건 문에 대한 작성을 하지 못했었다.
    lower_letter = False
    upper_letter = False
    num_end = False

    # 인자로 들어가는 username은 html파일의 name에서 비롯되었다.
    username = request.args.get('username')

    # *매우중요 "문장에 c가 소문자로 들어가는지 안들어가는지 확인하는 반복문"
    lower_letter = any(c.islower() for c in username)

    # *매우중요 "문장에 c가 대문자로 들어가는지 안들어가는지 확인하는 반복문"
    upper_letter = any(c.isupper() for c in username)

    # *매우중요 "문장의 마지막이 숫자로 끝나는지 아닌지 판별해주는 것"
    num_end = username[-1].isdigit()

    # 이건 report에 하나의 AND 조건으로 True or False를 리턴하는 것이다.
    report = lower_letter and upper_letter and num_end

    return render_template('report.html', report=report, lower=lower_letter,
                           upper=upper_letter, num_end=num_end)
# templates/report.html

{% extends 'base.html' %}

<!-- report.html에 대한 코드도 모두 알려주는 대로 했다. 갈길이 멀다. -->
{% block content %}
<div class="jumbotron">
    <p>Let's check your username!</p>
    {% if report %}
    <p>Your username passed all checks!</p>
    {% else %}
    <ul>
        {% if not lower %}
        <li>You did not use a lowercase letter in your username</li>
        {% endif %}
        {% if not upper %}
        <li>You did not use a uppercase letter in your username</li>
        {% endif %}
        {% if not num_end %}
        <li>You did not use end in a number in your username</li>
        {% endif %}
    </ul>
    {% endif %}
</div>
{% endblock  %}

이 연계되는 에러처리에 대한 코드가 정말 중요한 부분 중 하나라고 생각한다.

300x250