Kaynağa Gözat

Added AuthAPI utility & modified README.md

TonyKurts 1 yıl önce
ebeveyn
işleme
ab7cc1e63e
2 değiştirilmiş dosya ile 91 ekleme ve 0 silme
  1. 48 0
      README.md
  2. 43 0
      core/utils/AuthAPI.py

+ 48 - 0
README.md

@@ -106,3 +106,51 @@ Optional configuration params, which can be added to your project settings:
 ```python
 
 ```
+
+## Utilities
+
+Utilities provides important functionality to web-application, so it is important to know and understand how they work. They are stored in *core/utils*.
+
+### AuthAPI
+
+That class provides the ability to authenticate an application account through the
+API and store these authentication tokens.
+
+Modules using the API should log in ShariX system using this class.
+
+#### Setting up
+
+```python
+# core/config.py
+
+# ...
+#API
+# The URL where it is possible to access the API.
+API_URL = 'http://127.0.0.1:8000'
+# ...
+```
+
+```python
+# <module>/apps.py
+
+# ...
+from core.utils.AuthAPI import AuthAPI
+api = AuthAPI("<module_login>", "<module_password>")
+# ...
+```
+
+#### Usage example
+
+```python
+# <module>/<file>.py
+
+import requests
+from <module>.apps import api
+from core.config import API_URL
+
+# You can use api.headers to get the corret authorization header in your requests.
+requests.get(f"{API_URL}/tickets/api/tickets/", headers=api.headers)
+
+# Or you can get just token.
+print(api.token)
+```

+ 43 - 0
core/utils/AuthAPI.py

@@ -0,0 +1,43 @@
+'''
+That class provides the ability to authenticate an application account through the
+API and store these authentication tokens.
+
+Modules using the API should log in ShariX system using this class.
+'''
+
+import requests
+from core.config import API_URL
+
+class AuthAPI:
+    def __init__(self, login: str, password: str):
+        self._login = login
+        self._password = password
+        self._token = None
+        self._headers =  {'Authorization': f'Token {self._token}'}
+
+    def _create_token(self):
+        try:
+            response = requests.post(
+                f"{API_URL}/auth/token/login/", 
+                {
+                    "phone_number": self._login,
+                    "password": self._password
+                }
+            )
+            self._token = response.json()["auth_token"]
+        except requests.exceptions.ConnectionError:
+            print("\033[31m" + f"{self.__class__.__name__}: Can't connect to the API." + "\033[0m")
+        except KeyError:
+            print("\033[31m" + f"{self.__class__.__name__}: Incorrect login data." + "\033[0m")
+    
+    @property
+    def token(self):
+        if self._token is None:
+            self.__create_token()
+        return self._token
+
+    @property
+    def headers(self):
+        if self._token is None:
+            self.__create_token()
+        return self._headers