forum/api/api.py

76 lines
2.7 KiB
Python

from http import HTTPStatus
from flask import Flask, Response, config, json, jsonify, request, request_started
from dotenv import dotenv_values
from pymongo import MongoClient
from bson.json_util import dumps
from bson import ObjectId
from uuid import uuid4
config = dotenv_values(".env")
app = Flask(__name__)
mongoclient = MongoClient(config["DB_URI"])
db = mongoclient[config["DB_NAME"]]
print("Connected to MongoDB database")
@app.route('/api/message')
def get_messages():
messages = dumps(list(db["message"].find(limit=100)))
return messages
@app.route('/api/new_message', methods=['POST'])
def new_message():
position = list(json.loads(request.form['position']))
message = request.form['message']
token = request.form['token']
user = db['user'].find_one({'token': token})
if user is not None:
db["message"].insert_one({'position': position, 'message': message, 'userId': user['_id']})
return Response(status=HTTPStatus.NO_CONTENT)
else:
return Response(status=HTTPStatus.BAD_REQUEST)
@app.route('/api/gen_token')
def gen_token():
token = str(uuid4())
db["user"].insert_one({'token': token})
return { 'token': token }
@app.route('/api/remove_message', methods=['DELETE'])
def remove_message():
token = request.form['token']
message_id = ObjectId(request.form['message_id'])
user = db['user'].find_one({'token':token})
if user is not None:
message = db['message'].find_one({'_id': message_id})
if message is not None:
if message['userId'] == user['_id']:
db['message'].delete_one({'_id':message_id})
return Response(status=HTTPStatus.NO_CONTENT)
else:
return Response(status=HTTPStatus.UNAUTHORIZED)
else:
return Response(status=HTTPStatus.BAD_REQUEST)
else:
return Response(status=HTTPStatus.BAD_REQUEST)
@app.route('/api/edit_message', methods=['PUT'])
def edit_message():
token = request.form['token']
message_id = ObjectId(request.form['message_id'])
user = db['user'].find_one({'token':token})
new_message = request.form['message']
if user is not None and new_message is not None:
message = db['message'].find_one({'_id': message_id})
if message is not None:
if message['userId'] == user['_id']:
db['message'].update_one({'_id':message_id}, {'$set': { 'message': new_message }})
return Response(status=HTTPStatus.NO_CONTENT)
else:
return Response(status=HTTPStatus.UNAUTHORIZED)
else:
return Response(status=HTTPStatus.BAD_REQUEST)
else:
return Response(status=HTTPStatus.BAD_REQUEST)