浏览代码

first push BackendApi

Evgeny Polivanov 2 年之前
当前提交
ac38155b8c
共有 9 个文件被更改,包括 198 次插入0 次删除
  1. 10 0
      README.md
  2. 101 0
      SharixQuery.py
  3. 二进制
      __pycache__/SharixQuery.cpython-39.pyc
  4. 二进制
      __pycache__/config.cpython-39.pyc
  5. 二进制
      __pycache__/connect.cpython-39.pyc
  6. 二进制
      __pycache__/function.cpython-39.pyc
  7. 6 0
      config.py
  8. 29 0
      connect.py
  9. 52 0
      function.py

+ 10 - 0
README.md

@@ -0,0 +1,10 @@
+# BACKEND API Python
+### Instruction
+1. Change config.py
+2. Add this project to mine
+3. Add library: ```from BackendApi.SharixQuery import SharixQuery```
+4. Initialize and use: 
+```python
+your_name = SharixQuery()
+your_name.add_query()
+```

+ 101 - 0
SharixQuery.py

@@ -0,0 +1,101 @@
+from BackendApi.function import QueryFunc
+
+restfunc = QueryFunc()
+
+def generate_return_data(data, code):
+        return {"data":data, "httpcode":code}
+
+class SharixQuery:
+    
+    def auth_query(self, request_data):
+        try:
+            result = restfunc.query_select('''
+            SELECT * FROM rest_user
+            WHERE (rest_user.name=%s OR rest_user.email=%s) AND rest_user.password=%s;
+            ''', (request_data['login_email'], request_data['login_email'], request_data['password'],), True)
+            return generate_return_data(result, 200)
+        except Exception as ex:
+            return generate_return_data({"msg":str(ex)}, 500)
+    
+    def add_query(self, request_data):
+        try:
+            check_email_login = restfunc.query_check_count(''' 
+            SELECT * FROM rest_user
+            WHERE rest_user.name=%s OR rest_user.email=%s;
+            ''', (request_data['name'], request_data['email']))
+            if(check_email_login):
+                return generate_return_data({"msg":"User exist!"}, 400)
+            else:
+                result = restfunc.query_insert('''
+                INSERT INTO rest_user (name, birthday, lastlogintime, insys, idrole, email, password) 
+                VALUES (%s, %s, %s, %s, %s, %s, %s)
+                RETURNING id;
+                ''', \
+                    (request_data['name'], request_data['reg_date'],\
+                        request_data['log_time'], request_data['in_sys'],\
+                            request_data['role_id'], request_data['email'], request_data['password']))
+                return generate_return_data(result, 201)
+        except Exception as ex:
+            return generate_return_data({"msg":str(ex)}, 500)
+    
+    def get_user_query(self, id):
+        try:
+            result = restfunc.query_select('''
+            SELECT * FROM rest_user WHERE id = %s;
+            ''', (id,), True)
+            return generate_return_data(result, 200)
+        except Exception as ex:
+            return generate_return_data({"msg":str(ex)}, 500)
+    
+    def get_all_user_query(self):
+        try:
+            result = restfunc.query_select('''
+            SELECT rest_user.id, rest_user.name, rest_user.birthday, rest_user.insys, rest_role.name AS role_name, rest_user.lastlogintime, rest_user.email, rest_user.password
+            FROM rest_user, rest_role
+            WHERE rest_user.idrole = rest_role.id
+            ORDER BY id ASC;
+            ''', (), False)
+            return generate_return_data(result, 200)
+        except Exception as ex:
+            return generate_return_data({"msg":str(ex)}, 500)
+    
+    def delete_user_query(self, request_data):
+        try:
+            result = restfunc.query_delete_update('''
+            DELETE FROM rest_user
+            WHERE id = %s;
+            ''', (request_data['id'],))
+            if(result):
+                return generate_return_data({"msg":"Successful delete!"}, 200)
+            else:
+                return generate_return_data({"msg":"User does not exist!"}, 400)
+        except Exception as ex:
+            return generate_return_data({"msg":str(ex)}, 500)
+    
+    def update_user_query(self, request_data, id):
+        try:
+            result = restfunc.query_delete_update('''
+            UPDATE rest_user
+            SET name = %s
+            WHERE id = %s;
+            ''', (request_data['name'], id))
+            if(result):
+                return {"data": {"msg":"Successful update!"}, "httpcode": 200}
+            else:
+                return generate_return_data({"msg":"User does not exist!"}, 400)
+        except Exception as ex:
+            return generate_return_data({"msg":str(ex)}, 500)
+
+    def add_car_log(self, request_data):
+        try:
+            result = restfunc.query_insert(''' 
+            INSERT INTO cars_log (id, resource_id, operation, time_log_created, user_id)
+            VALUES(%s, %s, %s, %s, %s)
+            RETURNING id;
+            ''', (8, 3, request_data['operation'], request_data['date_cur'], 1))
+            return generate_return_data(result, 201)
+        except Exception as ex:
+            return generate_return_data({"msg":str(ex)}, 500)
+
+   
+            

二进制
__pycache__/SharixQuery.cpython-39.pyc


二进制
__pycache__/config.cpython-39.pyc


二进制
__pycache__/connect.cpython-39.pyc


二进制
__pycache__/function.cpython-39.pyc


+ 6 - 0
config.py

@@ -0,0 +1,6 @@
+#Подключение к базе данных
+host = "localhost"
+user = "postgres"
+password = ""
+db_name = "postgres"
+SSH_H = "46.138.247.90"

+ 29 - 0
connect.py

@@ -0,0 +1,29 @@
+import psycopg2 as pg
+from sshtunnel import SSHTunnelForwarder
+from BackendApi.config import SSH_H, host, user, db_name, password
+
+def connect():
+    try:
+        print('Connecting to the PostgreSQL Database...')
+        # подключение по ssh к серверу
+        ssh_tunnel = SSHTunnelForwarder(
+            (SSH_H, 334), #ip address and port
+            ssh_username="evgeny_polivanov", #имя пользователя
+            ssh_private_key= 'D:/sshc',# путь к файлу где расположен ssh ключ (не .pub)
+            ssh_private_key_password= '',# пароль (в данном случае пароль отсутствует)
+            remote_bind_address=(host, 5432) # не особо понял что это
+        )
+        ssh_tunnel.start()  
+        print("Tunnel start!")   
+        # Подключение к базе данных 
+        conn = pg.connect(
+            host=host,
+            port=ssh_tunnel.local_bind_port,
+            user=user,
+            password= password,
+            database=db_name
+        )
+        print("Success database connect!")
+        return conn
+    except:
+        print('Connection Has Failed...') 

+ 52 - 0
function.py

@@ -0,0 +1,52 @@
+from BackendApi.connect import connect
+
+conn = connect()
+class QueryFunc:
+    #Функция обработки SELECT запросов к бд
+    #Принимает запрос, аргументы которые предаются в запрос. 
+    #Последний параметр отвечает за возврат или одной записи или множества(по умолчанию).
+    def query_select(self, query, args=(), one=False):
+        try:
+            with conn.cursor() as cursor:
+                cursor.execute(query, args)
+                r = [dict((cursor.description[i][0], value) \
+                        for i, value in enumerate(row)) for row in cursor.fetchall()]
+                return (r[0] if r else None) if one else r
+        except Exception as ex:
+            return {"msg":str(ex)}
+    #Функция обработки INSERT запросов к бд
+    #Принимает запрос и аргументы
+    #Возвращает значение первого столбца добавленной записи
+    def query_insert(self, query, args=()):
+        try:
+            with conn.cursor() as cursor:
+                cursor.execute(query, args)
+                conn.commit()
+                return cursor.fetchone()[0]
+        except Exception as ex:
+            return {"msg":str(ex)}
+    #Функция обработки DELETE и UPDATE запросов к бд
+    #Принимает запрос и аргументы
+    #Возвращает истину или ложь в зависимости от результата запроса
+    def query_delete_update(self, query, args=()):
+        try:
+            with conn.cursor() as cursor:
+                cursor.execute(query, args)
+                if(cursor.rowcount != 0):
+                    conn.commit()
+                    return True
+            return False
+        except: 
+            return False
+    #Функция возвращающая истину, если в сущности существет запись
+    def query_check_count(self, query, args=()):
+        try:
+            with conn.cursor() as cursor:
+                cursor.execute(query, args)
+                if(cursor.rowcount > 0):
+                    return True
+            return False
+        except: 
+            return False
+
+