Skip to content

Commit

Permalink
Merge pull request #25 from jamakase/feature/backend-api
Browse files Browse the repository at this point in the history
update create_conversation.py
  • Loading branch information
anntish authored Sep 8, 2024
2 parents 74c4656 + c493bae commit d8347d8
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 12 deletions.
2 changes: 2 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ services:
build:
context: ./services/backend
dockerfile: Dockerfile
env_file:
- .env
volumes:
- ./services/backend:/app
environment:
Expand Down
1 change: 1 addition & 0 deletions frontend/src/app/api.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export const api = {
async createConversation(userId: string) {
const response = await fetch(`${API_URL}/conversation/create`, {
method: 'POST',
credentials: "include",
headers: {
'Content-Type': 'application/json',
},
Expand Down
10 changes: 8 additions & 2 deletions services/backend/app.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
from flasgger import Swagger
from flask import Flask
from flask_cors import CORS
Expand All @@ -11,6 +12,9 @@
from routes.conversation.delete_conversation import delete_message


broker_url = os.environ.get('BROKER_URL')
result_backend = os.environ.get('RESULT_BACKEND')

def create_app():
app = Flask(__name__)

Expand All @@ -25,8 +29,8 @@ def create_app():

app.config.from_mapping(
CELERY=dict(
broker_url="redis://redis",
result_backend="redis://redis",
broker_url=broker_url,
result_backend=result_backend,
task_ignore_result=True,
),
)
Expand All @@ -36,6 +40,8 @@ def create_app():

db.create_all()

app.secret_key = os.environ.get('APP_SECRET_KEY')

app.add_url_rule('/message', view_func=send_message, methods=['POST'])
app.add_url_rule('/conversation/create', view_func=create_conversation, methods=['POST'])
app.add_url_rule('/task/<id>', view_func=task_result, methods=['GET'])
Expand Down
10 changes: 7 additions & 3 deletions services/backend/config.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import os

database_url = os.environ.get('DATABASE_URL')
celery_broker_url = os.environ.get('CELERY_BROKER_URL')
celery_result_backend = os.environ.get('CELERY_RESULT_BACKEND')


class Config:
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'postgresql://user:password@db:5432/afana_propdoc')
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', database_url)
SQLALCHEMY_TRACK_MODIFICATIONS = False
CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL', 'redis://:password@redis:6379/0')
CELERY_RESULT_BACKEND = os.environ.get('CELERY_RESULT_BACKEND', 'redis://:password@redis:6379/0')
CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL', celery_broker_url)
CELERY_RESULT_BACKEND = os.environ.get('CELERY_RESULT_BACKEND', celery_result_backend)
2 changes: 1 addition & 1 deletion services/backend/models/conversation_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class ConversationModel(db.Model):
__tablename__ = 'conversations'

id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Uuid(as_uuid=True), default=uuid.uuid4, unique=True, nullable=True)
user_id = db.Column(db.String(50))

def __repr__(self):
return f"<Conversation(id={self.id}, user_id={self.user_id})>"
18 changes: 15 additions & 3 deletions services/backend/routes/conversation/create_conversation.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
import uuid
from functools import wraps

from flasgger import swag_from
from flask import jsonify, Blueprint
from flask import jsonify, Blueprint, g, session, request, make_response
from services.conversation_service import ConversationService
from schemas.conversation_schema import ConversationSchema, create_conversation_swagger

from utils.user_required import user_required

api = Blueprint('api', __name__)

conversation_schema = ConversationSchema()


@api.route('/conversation/create', methods=['POST'])
@swag_from(create_conversation_swagger)
@user_required
def create_conversation():
"""
Создает новую беседу.
Возвращает ID созданной беседы.
"""
new_conversation = ConversationService.create_conversation()
return jsonify({'conversation_id': new_conversation.id}), 201
user_id = request.cookies.get('user_id')

new_conversation = ConversationService.create_conversation(user_id)

resp = make_response(jsonify({'conversation_id': new_conversation.id}), 201)

return resp

9 changes: 6 additions & 3 deletions services/backend/services/conversation_service.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from flask import jsonify
import uuid

from flask import jsonify, session
from models import db
from models.conversation_model import ConversationModel
from services.message_service import MessageService, SaveMessageOptions, Role
Expand All @@ -21,8 +23,9 @@ def from_id(conversation_id: int):


@staticmethod
def create_conversation() -> ConversationModel:
new_conversation = ConversationModel()
def create_conversation(user_id: uuid) -> ConversationModel:

new_conversation = ConversationModel(user_id = user_id)

db.session.add(new_conversation)
db.session.commit()
Expand Down
23 changes: 23 additions & 0 deletions services/backend/utils/user_required.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import os
import uuid
from dotenv import load_dotenv
from flask import make_response, request


load_dotenv()
access_control_allow_origin = os.environ.get('ACCESS_CONTROL_ALLOW_ORIGIN')

def user_required(f):
def decorated_function(*args, **kws):
response = f(*args, **kws)
response = make_response(response)

if not request.cookies.get('user_id'):
response.set_cookie('user_id', value=str(uuid.uuid4()), max_age=60 * 60 * 24 * 365 * 2, httponly = True)

response.headers.add('Access-Control-Allow-Origin', access_control_allow_origin)
response.headers.add('Access-Control-Allow-Credentials', 'true')

return response

return decorated_function

0 comments on commit d8347d8

Please sign in to comment.