본문 바로가기

파이썬

Flask를 이용해 ChatGPT를 이용한 챗봇이 있는 웹페이지 만들어보기 2 [Python, OpenAI, Flask, Cursor IDE]

반응형

화면은 Fomantic UI로 꾸며보려고 한다. 무료 UI Framework다 ㅎ

 

https://fomantic-ui.com/

 

https://fomantic-ui.com/introduction/getting-started.html#using-a-cdn-provider

nodejs 기반이 아니기 때문에 cdn 참조를 통해 포맨틱UI를 불러와보자.

 

index.html로 돌아가 아래처럼 코드를 추가한다.

<!DOCTYPE html>
<html lang="ko">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Example</title>
    </head>

    <body>
        <p>Hello, HTML World!</p>
        <p>{{ data }}</p>
    </body>

    <!-- You MUST include jQuery 3.4+ before Fomantic -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/fomantic-ui@2.9.3/dist/semantic.min.css">
    <script src="https://cdn.jsdelivr.net/npm/fomantic-ui@2.9.3/dist/semantic.min.js"></script>
</html>

 

 

하단에 보면 script와 link라는 태그가 있는데, 이게 바로 라이브러리를 cdn에서 바로 받아오는 코드다.

라이브러리를 불러오기 위해선 파일을 다운로드받아 프로젝트 내 폴더에 저장해서 사용하거나

저런식으로 스크립트로 불러오거나, node같은 경우에는 npm에서 다운로드받아 내장시켜 사용하는 경우도 있다.

 

또 html을 작성할 때에는 코드의 순서가 매우 중요한데 script나 link가 상단에 많이 있을 경우 컨텐츠를 불러오는 속도가 느려지는 등 해당 부분에 대해서는 자세히 다루지는 않겠다. 이론 설명 포스팅이 아니고 빠르게 따라해보는 포스팅이니까!

 

https://fomantic-ui.com/usage/layout.html

https://fomantic-ui.com/examples/login.html

이 곳을 보면 기본으로 제공하는 다양한 예시들을 볼 수 있는데 그 중에서도 login.html을 우선 따라해보자. 아래 코드를 index.html에 덮어 씌운다.

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example</title>
</head>
<style type="text/css">
    body {
        background-color: #DADADA;
    }

    body>.grid {
        height: 100%;
    }

    .image {
        margin-top: -100px;
    }

    .column {
        max-width: 450px;
    }
</style>

<body>

    <div class="ui middle aligned center aligned grid">
        <div class="column">
            <h2 class="ui teal image header">
                <img src="assets/images/logo.png" class="image">
                <div class="content">
                    Log-in to your account
                </div>
            </h2>
            <form class="ui large form initial">
                <div class="ui stacked segment">
                    <div class="field">
                        <div class="ui left icon input">
                            <i class="user icon"></i>
                            <input type="text" name="email" placeholder="E-mail address">
                        </div>
                    </div>
                    <div class="field">
                        <div class="ui left icon input">
                            <i class="lock icon"></i>
                            <input type="password" name="password" placeholder="Password">
                        </div>
                    </div>
                    <div class="ui fluid large teal submit button">Login</div>
                </div>

                <div class="ui error message"></div>

            </form>

            <div class="ui message">
                New to us? <a href="#">Sign Up</a>
            </div>
        </div>
    </div>


    <!-- You MUST include jQuery 3.4+ before Fomantic -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/fomantic-ui@2.9.3/dist/semantic.min.css">
    <script src="https://cdn.jsdelivr.net/npm/fomantic-ui@2.9.3/dist/semantic.min.js"></script>

    <script>
        $(document)
            .ready(function () {
                $('.ui.form').form({
                    fields: {
                        email: {
                            identifier: 'email',
                            rules: [
                                {
                                    type: 'empty',
                                    prompt: 'Please enter your e-mail'
                                },
                                {
                                    type: 'email',
                                    prompt: 'Please enter a valid e-mail'
                                }
                            ]
                        },
                        password: {
                            identifier: 'password',
                            rules: [
                                {
                                    type: 'empty',
                                    prompt: 'Please enter your password'
                                },
                                {
                                    type: 'length[6]',
                                    prompt: 'Your password must be at least 6 characters'
                                }
                            ]
                        }
                    }
                });
            });
    </script>

</html>

 

참고로 Cursor IDE를 사용한다면, 코드를 붙여넣은 뒤 혹은 작성한 뒤 Ctrl+Alt+L을 누르면 자동으로 정렬해준다.

 

그리고 브라우저에서 새로고침을 해보면 아래 같은 화면이 나온다. Login 버튼을 눌러보면 두 번째 사진처럼 에러 문구도 노출이 된다.

 

그럼 이제 이메일과 패스워드를 입력한 뒤 로그인하면 페이지가 넘어가도록 한 번 코드를 작성해보자. DB 연결이 안 되어 있으니 로그인 검사는 건너 뛴다.

https://fomantic-ui.com/behaviors/form.html

해당 페이지에서 form validaton에 대한 내용을 찾아볼 수 있으니 참고하자.

Before

<form class="ui large form initial">
    <div class="ui stacked segment">
        <div class="field">
            <div class="ui left icon input">
                <i class="user icon"></i>
                <input type="text" name="email" placeholder="E-mail address">
            </div>
        </div>
        <div class="field">
            <div class="ui left icon input">
                <i class="lock icon"></i>
                <input type="password" name="password" placeholder="Password">
            </div>
        </div>
        <div class="ui fluid large teal submit button">Login</div>
    </div>
    <div class="ui error message"></div>
</form>

After

<form class="ui large form initial" action="/login" method="post">
    <div class="ui stacked segment">
        <div class="field">
            <div class="ui left icon input">
                <i class="user icon"></i>
                <input type="text" name="email" placeholder="E-mail address">
            </div>
        </div>
        <div class="field">
            <div class="ui left icon input">
                <i class="lock icon"></i>
                <input type="password" name="password" placeholder="Password">
            </div>
        </div>
        <div class="ui fluid large teal submit button">Login</div>
    </div>
    <div class="ui error message"></div>
</form>

 

그리고 main.py 파일로 돌아가서 /login으로 라우터를 추가한다.

Before

from flask import Flask,render_template
from openai import OpenAI
from dotenv import load_dotenv
import os

app = Flask(__name__)

load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

@app.route("/")
def index():
    return render_template('index.html', data="데이터입니다.")

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

After

from flask import Flask,render_template,session, request
from openai import OpenAI
from dotenv import load_dotenv
import os

app = Flask(__name__)
app.secret_key = os.urandom(10)

load_dotenv()
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))

@app.route('/')
def index():
    if 'user' in session and session['user'] == None:
        return render_template('main.html')
    else:
        return render_template('index.html')

@app.route('/login', methods=['POST'])
def login():
    # session['user'] = request.form['email'];
    session['user'] = request.form;
    return render_template('main.html', email=request.form['email'])

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

 

그리고 main.html을 index.html과 같은 폴더에 추가하고 아래처럼 마크업한다.

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Example</title>
    </head>

    <body>
        <p>{{ email }}님, 환영합니다.</p>
    </body>
</html>

 

저장한 뒤 로그인해보면?

 

짜잔~

 

다음 포스팅에서 백엔드와 프론트엔드를 분리해 프로젝트 두개로 홈페이지를 구성해보자. svelte를 사용해보려고 한다.

 

다음 포스팅

2024.02.02 - [파이썬] - Flask를 이용해 ChatGPT를 이용한 챗봇이 있는 웹페이지 만들어보기 3 [Python, OpenAI, Flask, Svelte, Routify, Cursor IDE]

이전 포스팅

2024.01.25 - [파이썬] - Flask를 이용해 ChatGPT를 이용한 챗봇이 있는 웹페이지 만들어보기 1 [Python, OpenAI, Flask, Cursor IDE]