Skip to content

Commit

Permalink
Update README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnTuwa authored May 25, 2024
1 parent e523417 commit 07f10b0
Showing 1 changed file with 141 additions and 0 deletions.
141 changes: 141 additions & 0 deletions docs/software/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,144 @@ ALTER TABLE "members" ADD CONSTRAINT "members_project_id_fkey" FOREIGN KEY ("pro
```

## RESTfull система управління проектами
main.py
```python
from flask import Flask
from flask import request, jsonify
from model import Users

app = Flask(__name__)

users = Users()

@app.route("/user/all", methods=["GET"])
def get_all_users():
result = users.get_all_users()
return jsonify(result), 200

@app.route("/user/<id>", methods=["GET"])
def get_user(id):
result = users.get_user(id)
return jsonify(result), 200

@app.route("/user/add", methods=["POST"])
def add_user():
data = request.get_json()
result = users.add_user(data)
return jsonify(result), 200

@app.route("/user/update", methods=["PATCH"])
def update_user():
data = request.get_json()
result = users.add_user(data)
return jsonify(result), 200

@app.route("/user/delete/<id>", methods=["DELETE"])
def delete_user(id):
result = users.delete_user(id)
return jsonify(result), 200


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

module.py
```python
import psycopg

class Users:
def __init__(self):
try:
self.connection = psycopg.connect(
dbname="TaskForge",
user="postgres",
password="1234",
host="localhost",
port="5432"
)
print("Connection to database established successfully!")
self.cursor = self.connection.cursor()
except psycopg.Error as error:
print("Failed to connect to the database:", str(error))

def get_all_users(self):
try:
self.cursor.execute("SELECT * FROM users")
result = self.cursor.fetchall()
if self.cursor.rowcount == 0:
return {"message": "There are no users", "error": "Not Found", "status_code": 404}
return {"data": result, "status_code": 200}
except psycopg.Error as error:
return {"message": str(error), "error": "Database Error", "status_code": 500}

def get_user(self, id):
if not str(id).isdigit():
return {"message": "Invalid user id", "error": "Bad Request", "status_code": 400}
try:
self.cursor.execute("SELECT * FROM users WHERE id = %s", (id,))
result = self.cursor.fetchall()
if self.cursor.rowcount == 0:
return {"message": f"There is no user with id {id}", "error": "Not Found", "status_code": 404}
return {"data": result, "status_code": 200}
except psycopg.Error as error:
return {"message": str(error), "error": "Database Error", "status_code": 500}

def add_user(self, data):
data = dict(data)
required_keys = {'id', 'username', 'email', 'password', 'fullname'}
if not required_keys.issubset(data):
return {"message": "Invalid or missing keys", "error": "Bad Request", "status_code": 400}
try:
query = "INSERT INTO users (id, username, email, password, fullname) VALUES (%s, %s, %s, %s, %s)"
values = (data['id'], data['username'], data['email'], data['password'], data['fullname'])
self.cursor.execute(query, values)
self.connection.commit()
if self.cursor.rowcount > 0:
return {"message": "User added succesfully", "status_code": 200}
else:
return {"message": "User wasn`t added to database", "error": "Not Acceptable", "status_code": 406}
except psycopg.Error as error:
self.connection.rollback()
return {"message": "Add user failed: " + str(error), "error": "Database Error", "status_code": 500}


def update_user(self, data):
data = dict(data)
if 'id' not in data:
return {"message": "No user id provided", "error": "Bad Request", "status_code": 400}
user_id = data['id']
del data['id']
if not data:
return {"message": "No data provided", "error": "Bad Request", "status_code": 400}
set_clause = ', '.join([f"{key} = %s" for key in data])
values = list(data.values())
values.append(user_id)
try:
query = f"UPDATE users SET {set_clause} WHERE id = %s"
self.cursor.execute(query, values)
self.connection.commit()

if self.cursor.rowcount > 0:
return {"message": "User updated successfully", "status_code": 200}
else:
return {"message": "No changes made to user", "error": "Not Found", "status_code": 404}
except psycopg.Error as error:
self.connection.rollback()
return {"message": "User update failed: " + str(error), "error": "Database Error", "status_code": 500}

def delete_user(self, id):
if not str(id).isdigit():
return {"message": "Invalid user id", "error": "Bad Request", "status_code": 400}
try:
self.cursor.execute("DELETE FROM users WHERE id = %s", (id,))
self.connection.commit()

if self.cursor.rowcount > 0:
return {"message": "User deleted successfully", "status_code": 200}
else:
return {"message": "Nothing to delete", "error": "Not Found", "status_code": 404}
except Exception as error:
self.connection.rollback()
return {"message": "Delete user failed", "error": str(error), "status_code": 500}
```

0 comments on commit 07f10b0

Please sign in to comment.