[flask] chatGPT api 통신 기록

민하·2023년 4월 15일

flask

목록 보기
1/1
post-thumbnail

flask는 오늘 난생 처음 써봤다. 장장 9시간의 수고 끝에 openAPI의 chatGPT와 통신을 성공해서 무척이나 뿌듯하다.
javascript로는 chatGPT와의 api 통신을 이미 만들어 봤으니 js코드와 비교하고, 파이썬 코드 한 줄 적고, 구글링 잔뜩하고 다시 파이썬 코드 적고의 반복이었다.

✅ 오늘의 작업 중인 flask 통신 : https://github.com/ariel1031/ztudio_chat

✅ javascript로 작업한 운세보는 챗도지 프로젝트 : https://github.com/ariel1031/Fortune-telling-ChatDogge
이 글은 맨땅에 헤딩하며 삽질하고 배운 것들을 적은 포스팅이다.

0. import

#app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
@app.route('/diction_post', methods=['GET','POST'])
def diction_post():
	return render_template('index.html')

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

도움 되는 사이트 : https://flask.palletsprojects.com/en/2.2.x/quickstart/#a-minimal-application
flask 공식페이지

1.

SyntaxError: Non-UTF-8 code starting with '\xec' in file (path)(filename).py on line 9, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

flask 작업전, chatGPT api 통신을 했을 때 뜬 에러 메세지

해결법

# -*coding: utf-8 -*

한글 인코딩 에러가 날 때가 있었다. 이 문장을 코드 맨 앞에 넣어주면 된다.

도움받은 사이트 : https://allnewthings.tistory.com/120

2.

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

해결법

@app.route('/diction_post', methods=['GET','POST'])

app route에에 url 메서드를 삽입해야 한다. 처음에 메서드를 넣지 않아 에러가 떴다.

도움 받은 사이트 : https://stackoverflow.com/questions/20689195/flask-error-method-not-allowed-the-method-is-not-allowed-for-the-requested-url

역시 스텍오버플로우..

3. render_template을 이용하여 HTML 파일을 Flask에 연결

render_template를 사용할 모든 파일은 templates 폴더 내에 존재해야 한다. 작업 경로에 templates 폴더를 추가하자. 즉, templates 폴더 안에 index.html 을 둔다.

  • app.py: 프로그램을 실행시키는 파일
  • static 폴더: css나 이미지 파일을 담아두는 폴더
  • templates 폴더: html 파일을 담아두는 폴더

    도움 받은 사이트 :
    https://go-guma.tistory.com/9
    https://jinnynote.com/learn/web/스파르타-flask/

    4. html

    <!--index.html-->
    <form action="/diction_post" method="post" class="input-form">
    	<div class="inputBox">
        	<input
            	type="text"
                name="input_name"
                placeholder="대사를 입력해주세요"
            />
            <button id="btn" onsubmit="event.preventDefault(); start();">
                    Send
            </button>
        </div>
    </form>

    < form > 태그의 action 속성은 폼 데이터(form data)를 서버로 보낼 때 해당 데이터가 도착할 URL을 명시
    form 태그의 method="post" 방식으로 전달

    도움 받은 사이트 : http://www.tcpschool.com/html-tag-attrs/form-action
    코드 참고 도움 받은 사이트 :
    https://jvvp.tistory.com/1102
    https://velog.io/@dltpal07/flask와-html-간의-변수-전달

    5.

    #app.py
    @app.route('/diction_post', methods=['GET','POST'])
    def diction_post():
      if request.method =='POST':
          usermessages = request.form['input_name'] # <- index.html의 form에서 name="input_name"인 input을 받아옴
          #usermessages = request.form
          usermessages = str(usermessages)
          print(usermessages)
          messages_history = [
                      {"role":"system", "content":"Analyze the next sentence and recommend a 'gesture' that the speaker of the sentence would do. As a result of the gesture recommendations in the sentence, You can choose one from the list. list=['wave your hand', 'hit the person next to you', 'kiss you', 'hurray', 'cover your face with your hands'.] For example, if I send the sentence, '권민철: 오늘 알바비 들어왔다' you can recommend the action of 'hurray'. Now, analyze the sentence."},
                      {"role":"user", "content":"Analyze the next sentence and recommend a 'gesture' that the speaker of the sentence would do. As a result of the gesture recommendations in the sentence, You can choose one from the list. list=['wave your hand', 'hit the person next to you', 'kiss you', 'hurray', 'cover your face with your hands'.] For example, if I send the sentence, '권민철: 오늘 알바비 들어왔다' you can recommend the action of 'hurray'. Now, analyze the sentence."}
                  ]
          messages_history.append({"role":"user", "content":usermessages})
          print(messages_history)
    
          #요청
          completion = openai.ChatCompletion.create(
                  model="gpt-3.5-turbo",
                  messages=messages_history
              )
    
          #응답 저장
          gpt_reply = completion.choices[0].message.content
          print(gpt_reply)
          messages_history.append({"role":"assistant", "content":gpt_reply})
          print(messages_history)
    
      return render_template('index.html')

    usermessages = request.form['input_name'] # <- index.html의 form에서 name="input_name"인 input을 받아옴

    6. event.preventDefault()

    수정전

    <form action="\diction_post" method="post" class="input-form">
    	<div class="inputBox">
    		<input
    			type="text"
    			name="input_name"
    			placeholder="대사를 입력해주세요"
    		/>
    		<button id="btn" onClick="start()">Send</button>
    	</div>
    </form>

    수정후

    <form action="\diction_post" method="post" class="input-form">
    	<div class="inputBox">
    		<input
    			type="text"
    			name="input_name"
    			placeholder="대사를 입력해주세요"
    		/>
    		<button id="btn" onsubmit="event.preventDefault(); start();">Send</button>
    	</div>
    </form>

    문제
    html form에서 input에 작성한 코드가 파이썬으로 넘겨지지 않음

    해결
    문제는 HTML 페이지에서 입력된 텍스트가 서버로 전송되지 않았기 때문. 이를 수정하려면, HTML 코드에서 버튼의 onClick 속성을 제거

    GPT의 도움을 받아 의미를 알아냈다.

    onsubmit="event.preventDefault(); start();"는 HTML form의 submit 이벤트가 발생했을 때 실행되는 JavaScript 코드입니다. 이 코드의 의미는 다음과 같습니다:
    event.preventDefault();: 이 코드는 기본 이벤트 동작을 취소합니다. 기본적으로 HTML form은 제출될 때 페이지를 새로고침합니다. event.preventDefault()를 사용하면 페이지 새로고침을 방지할 수 있습니다.
    start();: event.preventDefault()로 기본 이벤트 동작이 취소된 후, start() 함수가 호출됩니다. 이 함수는 사용자가 입력한 텍스트를 화면에 표시하고, 해당 값을 서버로 전송하기 전에 추가 작업을 수행할 수 있습니다.
    결과적으로, 코드는 form이 제출될 때 페이지 새로고침을 방지하고 사용자 정의 함수인 start()를 호출하여 추가 작업을 수행하도록 하는 역할을 합니다.

    아주 뿌듯한 하루였다.

  • 0개의 댓글