Skip to content

Commit

Permalink
Merge pull request #9 from krafton-jungle-AEIOU-mini-project/epic/#2-…
Browse files Browse the repository at this point in the history
…letsjo
  • Loading branch information
letsjo authored Apr 5, 2023
2 parents d8177b8 + 72f9cdf commit c0af905
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 64 deletions.
108 changes: 54 additions & 54 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from pymongo import MongoClient
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
import hashlib
import datetime
import datetime
import jwt
import time
from pytz import timezone
Expand All @@ -27,43 +27,25 @@ def home():
return render_template('index.html', isLogin=True, nickname=user_info["nick"])
except jwt.ExpiredSignatureError:
session.pop('Authorization', None)
return render_template('index.html', isLogin=False, alert="로그인 시간이 만료되었습니다. 다시 로그인 해주세요.")
return redirect(url_for("redirectPage", alert="로그인 시간이 만료되었습니다. 다시 로그인 해주세요."))
except jwt.exceptions.DecodeError:
session.pop('Authorization', None)
return render_template('index.html', isLogin=False, alert="로그인 정보가 존재하지 않아 로그아웃 되었습니다.")
return redirect(url_for("redirectPage", alert="로그인 정보가 존재하지 않아 로그아웃 되었습니다."))
else:
return render_template('index.html')


@app.route('/join')
def join():
if 'Authorization' in session:
token_receive = session['Authorization']
try:
payload = jwt.decode(token_receive, SECRET_KEY,
algorithms=['HS256'])
user_info = db.user.find_one({"id": payload['id']})
return redirect(url_for("home", alert="이미 로그인 된 상태라 홈으로 이동합니다.", isLogin=True, nickname=user_info["nick"]))
except jwt.ExpiredSignatureError:
session.pop('Authorization', None)
except jwt.exceptions.DecodeError:
session.pop('Authorization', None)
return redirect(url_for("home"))
return render_template('join.html')


@app.route('/login')
def login():
if 'Authorization' in session:
token_receive = session['Authorization']
try:
payload = jwt.decode(token_receive, SECRET_KEY,
algorithms=['HS256'])
user_info = db.user.find_one({"id": payload['id']})
return redirect(url_for("home", alert="이미 로그인 된 상태라 홈으로 이동합니다.", isLogin=True, nickname=user_info["nick"]))
except jwt.ExpiredSignatureError:
session.pop('Authorization', None)
except jwt.exceptions.DecodeError:
session.pop('Authorization', None)
return redirect(url_for("home"))
return render_template('login.html')


Expand Down Expand Up @@ -130,14 +112,15 @@ def logout():
session.pop('Authorization', None)
return render_template('index.html')


@app.route('/api/ask/list', methods=['GET'])
def show_articles():
filter = {}
project = {}
rs = list()
docs = list(db.memos.find(filter, project).sort('date', -1))
# docs = list(db.memos.find().sort({'date', -1}))
#시간으로 리스트 정리하기
# 시간으로 리스트 정리하기
for memo in docs:
item = {
'_id': str(memo['_id']),
Expand All @@ -147,52 +130,69 @@ def show_articles():
'date': datetime.datetime.fromtimestamp(memo['date'])
}
rs.append(item)

return jsonify({'code': 1, 'data': rs})


@app.route('/api/ask/create', methods=['POST'])
def post_article():
title = request.form['title']
nickname = request.form['nickname']
now = int(time.time())
memo = {'title': title, 'content':"", 'nickname':nickname,'date':now}
memo = {'title': title, 'content': "", 'nickname': nickname, 'date': now}
result = db.memos.insert_one(memo)
memo['_id'] = str(result.inserted_id)
chatgpt_comment(memo['_id'],title)
chatgpt_comment(memo['_id'], title)
return jsonify({'code': 1, 'data': memo})

@app.route('/api/<id>/comment/create', methods =['POST'])

@app.route('/api/<id>/comment/create', methods=['POST'])
def post_comment(id):
comment = request.form['comment']
now = int(time.time())
nickname = request.form['nickname']
memo = {'postid': id, 'comment': comment ,'nickname' : nickname, 'date':now}
memo = {'postid': id, 'comment': comment,
'nickname': nickname, 'date': now}
db.comment.insert_one(memo)
return jsonify({'code':1})
#memo['_id'] = str(result.inserted_id)
@app.route('/api/ask/<id>/comment/list' , methods = ['GET'] )
return jsonify({'code': 1})
# memo['_id'] = str(result.inserted_id)


@app.route('/api/ask/<id>/comment/list', methods=['GET'])
def show_comment(id):
filter = {'postid':id}
project = {}
rs = list()
#docs = list(db.memos.find ().sort( { 'date' : 1 } ))
docs = list(db.comment.find(filter, project).sort('date', 1))
for memo in docs:
item = {
'nickname':memo['nickname'],
'comment':memo['comment'],
#'_id': str(memo['_id']),
'date': datetime.datetime.fromtimestamp(memo['date'])
}
rs.append(item)
return jsonify({'code':1,'data':rs})

def chatgpt_comment(id,title):
# user_content = request.form['title']
messages = []
messages.append({"role": "user", "content": title})
completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages)
chatgpt_reply = completion.choices[0].message["content"].strip()
db.memos.update_one({'_id': bson.ObjectId(id)},{"$set":{"content":chatgpt_reply}})
filter = {'postid': id}
project = {}
rs = list()
# docs = list(db.memos.find ().sort( { 'date' : 1 } ))
docs = list(db.comment.find(filter, project).sort('date', 1))
for memo in docs:
item = {
'nickname': memo['nickname'],
'comment': memo['comment'],
# '_id': str(memo['_id']),
'date': datetime.datetime.fromtimestamp(memo['date'])
}
rs.append(item)
return jsonify({'code': 1, 'data': rs})


def chatgpt_comment(id, title):
# user_content = request.form['title']
messages = []
messages.append({"role": "user", "content": title})
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo", messages=messages)
chatgpt_reply = completion.choices[0].message["content"].strip()
db.memos.update_one({'_id': bson.ObjectId(id)}, {
"$set": {"content": chatgpt_reply}})


@app.route('/redirect')
def redirectPage():
alert = request.args.get('alert')
session.pop('Authorization', None)
return render_template('redirect.html', alert=alert)


if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
5 changes: 0 additions & 5 deletions templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,6 @@
{% block title %}{% endblock %} - 정글Wiki
</title>
{% endblock %}
<script>
{% if alert %}
alert("{{ alert }}")
{% endif %}
</script>
{% block script %} {% endblock %}
</head>

Expand Down
6 changes: 2 additions & 4 deletions templates/detail.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
</div>
{% if isLogin == True %}
<form class="flex w-full gap-x-4 my-5">
<input id="email-address" name="question" type="text" autocomplete="false" required
<input id="question" name="question" type="text" autocomplete="off" required
class="flex-auto rounded-md border-0 bg-white/5 px-3.5 py-2 text-zinc shadow-sm ring-1 ring-inset ring-black/10 focus:ring-2 focus:ring-inset focus:ring-zinc-500 sm:text-sm sm:leading-6"
placeholder="답변을 도와주세요! ChatGPT 친구가 정확하지 않아요!">
<button type="submit"
Expand All @@ -37,9 +37,7 @@
<div class="flex flex-col border-2 border-transparent border-t-gray-200">
<div class="px-8 py-3 space-y-4 border-2 border-transparent border-b-gray-200">
<p class="text-xl font-bold">홍길동</p>
<p class="text-lg">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Viverra elit donec nunc posuere
pulvinar libero fermentum mi. Lobortis vulputate consectetur suspendisse massa mauris. Lacus odio pretium enim
gravida. Netus sit a, enim enim quam quam egestas arcu.</p>
<p class="text-lg">감사합니다.</p>
<p class="text-right">
2023.04.04
</p>
Expand Down
2 changes: 1 addition & 1 deletion templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<div class="important flex flex-col w-full items-center pb-32">
{% if isLogin == True %}
<form class="flex w-full gap-x-4 my-5">
<input id="email-address" name="question" type="text" autocomplete="false" required
<input id="question" name="question" type="text" autocomplete="off" required
class="flex-auto rounded-md border-0 bg-white/5 px-3.5 py-2 text-zinc shadow-sm ring-1 ring-inset ring-black/10 focus:ring-2 focus:ring-inset focus:ring-zinc-500 sm:text-sm sm:leading-6"
placeholder="{{nickname}} 님 무엇이 궁금하신가요?">
<button type="submit"
Expand Down
17 changes: 17 additions & 0 deletions templates/redirect.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{% extends "base.html" %}

{% block title %}HOME{%endblock %}
{% block script %}
<script>
{% if alert %}
alert("{{ alert }}")
window.location.href = '/login'
{% endif %}
</script>
{%endblock %}
{% block head %}

{% include'head.html' %}
{{ super() }}

{% endblock %}

0 comments on commit c0af905

Please sign in to comment.