Browse Source

Changing the architecture of a project

Evgeny Polivanov 2 years ago
parent
commit
467e85d5e4
10 changed files with 12 additions and 196 deletions
  1. 2 1
      .gitignore
  2. 0 101
      SharixQuery.py
  3. 2 2
      api.py
  4. 2 0
      api_config.py
  5. 0 9
      config.py
  6. 0 29
      connect.py
  7. 0 52
      function.py
  8. 3 0
      install.bat
  9. 0 2
      run.bat
  10. 3 0
      run_api.bat

+ 2 - 1
.gitignore

@@ -1,2 +1,3 @@
 rest_venv/
-__pycache__/
+__pycache__/
+BackendApi/

+ 0 - 101
SharixQuery.py

@@ -1,101 +0,0 @@
-from 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)
-
-   
-            

+ 2 - 2
api.py

@@ -4,8 +4,8 @@ from xmpp import cli
 from flask_jwt_extended import JWTManager, jwt_required, get_jwt_identity, create_access_token
 from datetime import timedelta
 
-from config import Config
-from SharixQuery import SharixQuery
+from api_config import Config
+from BackendApi.SharixQuery import SharixQuery
 #from OpenSSL import SSL
 
 #context = SSL.Context(SSL.PROTOCOL_TLSv1_2)

+ 2 - 0
api_config.py

@@ -0,0 +1,2 @@
+class Config:
+    SECRET_KEY = "2198jf1239198234790182u3f9"

+ 0 - 9
config.py

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

+ 0 - 29
connect.py

@@ -1,29 +0,0 @@
-import psycopg2 as pg
-from sshtunnel import SSHTunnelForwarder
-from 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...') 

+ 0 - 52
function.py

@@ -1,52 +0,0 @@
-from 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
-
-    

+ 3 - 0
install.bat

@@ -0,0 +1,3 @@
+@echo off
+git clone -b master http://git.sharix-app.org/ShariX_Open/BackendApi.git && python -m venv rest_venv && %~dp0\rest_venv\Scripts\activate.bat && pip install -r requirements.txt
+pause

+ 0 - 2
run.bat

@@ -1,2 +0,0 @@
-@echo off
-python -m venv rest_venv && %~dp0\rest_venv\Scripts\activate.bat && pip install -r requirements.txt && python %~dp0\api.py

+ 3 - 0
run_api.bat

@@ -0,0 +1,3 @@
+@echo off
+%~dp0\rest_venv\Scripts\activate.bat && python %~dp0\api.py
+pause