This repository has been archived by the owner on Nov 1, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Прототип MetaEdnpoint ApiClient и мелкие изменения (#12)
- Loading branch information
Showing
9 changed files
with
217 additions
and
48 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
import requests | ||
|
||
import json | ||
import time | ||
import base64 | ||
|
||
from metaappscriptsdk import read_developer_settings | ||
from metaappscriptsdk.exceptions import SDKError | ||
from metaappscriptsdk.internal import read_cfg, write_cfg | ||
|
||
AUTH_CACHE_FILE = "/.rwmeta_auth_cache.json" | ||
OAUTH_TOKEN_URL = "https://account.devision.io/oauth2/token" | ||
|
||
|
||
class ApiClient: | ||
""" | ||
Упрощает взаимодействие с внутренними API Devision | ||
""" | ||
|
||
def __init__(self, host, api_version, access_token=None, refresh_token=None, client_id=None, client_secret=None): | ||
""" | ||
:type app: metaappscriptsdk.MetaApp | ||
""" | ||
self.host = host | ||
self.api_version = api_version | ||
self.access_token = access_token | ||
self.refresh_token = refresh_token | ||
self.client_id = client_id | ||
self.client_secret = client_secret | ||
|
||
def get(self, method_path, get_params=None): | ||
return self.request("GET", method_path, get_params) | ||
|
||
def post(self, method_path, get_params=None, post_data=None): | ||
return self.request("POST", method_path, get_params, post_data) | ||
|
||
def request(self, http_method, method_path, get_params=None, post_data=None): | ||
auth_cache = read_cfg(AUTH_CACHE_FILE) | ||
if auth_cache: | ||
if self.refresh_token == auth_cache.get('refresh_token', ''): | ||
self.access_token = self.__fetch_and_validate_access_token(auth_cache) | ||
|
||
if not self.access_token: | ||
self.refresh_access_token() | ||
|
||
if not self.access_token: | ||
raise ValueError("access_token должен был быть получен") | ||
|
||
for try_idx in range(2): | ||
url = self.host + '/' + self.api_version + '/' + method_path | ||
headers = {"Authorization": "Bearer " + self.access_token} | ||
|
||
req_param = { | ||
"method": http_method, | ||
"url": url, | ||
"data": get_params, | ||
"json": post_data, | ||
"headers": headers | ||
} | ||
resp = requests.request(**req_param) | ||
if resp.status_code == 401: | ||
self.refresh_access_token() | ||
continue | ||
|
||
return resp.json() | ||
|
||
def refresh_access_token(self): | ||
resp = requests.post(OAUTH_TOKEN_URL, data={ | ||
"client_id": self.client_id, | ||
"client_secret": self.client_secret, | ||
"refresh_token": self.refresh_token, | ||
"grant_type": "refresh_token", | ||
}, headers={ | ||
"Content-Type": "application/x-www-form-urlencoded" | ||
}) | ||
|
||
json = resp.json() | ||
if json.get('error'): | ||
raise SDKError(json) | ||
self.access_token = json.get('access_token') | ||
|
||
write_cfg(AUTH_CACHE_FILE, { | ||
"refresh_token": self.refresh_token, | ||
"access_token": self.access_token | ||
}) | ||
|
||
@staticmethod | ||
def build_from_developer_settings(api_name: str, api_version: str): | ||
""" | ||
:param api_name: Example hello | ||
:param api_version: Example v1, v2alpha | ||
:return: ApiClient | ||
""" | ||
developer_settings = read_developer_settings() | ||
|
||
api_host = "http://" + api_name + ".apis.devision.io" | ||
return ApiClient( | ||
host=api_host, | ||
api_version=api_version, | ||
access_token=None, | ||
refresh_token=developer_settings['refreshToken'], | ||
client_id=developer_settings['clientId'], | ||
client_secret=developer_settings['clientSecret'], | ||
) | ||
|
||
@staticmethod | ||
def __fetch_and_validate_access_token(auth_cache): | ||
access_token = auth_cache.get('access_token', '') | ||
t = json.loads(base64.b64decode(access_token.split(".")[1] + "=").decode(encoding="utf-8")) | ||
if time.time() > t.get('exp'): | ||
return None | ||
return access_token |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
from metaappscriptsdk.apiclient import ApiClient | ||
|
||
api = ApiClient.build_from_developer_settings("hello", "v1") | ||
|
||
# Установите другой URL api если надо | ||
# api.host = "http://localhost:8084" | ||
|
||
resp = api.request("hello/ping", post_data={ | ||
"ping": "Hi!!!" | ||
}) | ||
|
||
print(u"resp = %s" % str(resp)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
* |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
__version__ = '0.6.22' | ||
__version__ = '0.7.0' | ||
__package_name__ = 'metaappscriptsdk' | ||
|
||
if __name__ == "__main__": | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
""" | ||
ВНИМАНИЕ! Только для использования внутри кода SDK | ||
Запрещено добавление общих утилит в этот файл | ||
""" | ||
import platform | ||
from os.path import expanduser | ||
|
||
import os | ||
|
||
import json | ||
|
||
|
||
def read_developer_settings(): | ||
""" | ||
Читает конфигурации разработчика с локальной машины или из переменных окружения | ||
При этом переменная окружения приоритетнее | ||
:return: dict|None | ||
""" | ||
ret = read_cfg("/.rwmeta/developer_settings.json") | ||
|
||
env_developer_settings = os.environ.get('META_SERVICE_ACCOUNT_SECRET', None) | ||
if not env_developer_settings: | ||
env_developer_settings = os.environ.get('X-META-Developer-Settings', None) | ||
if env_developer_settings: | ||
ret = json.loads(env_developer_settings) | ||
|
||
return ret | ||
|
||
|
||
def read_cfg(path) -> dict: | ||
""" | ||
:param path: example: "/.rwmeta/developer_settings.json" | ||
:return: dict | ||
""" | ||
ret = None | ||
full_path = __build_path(path) | ||
if os.path.isfile(full_path): | ||
with open(full_path, 'r') as myfile: | ||
ret = json.loads(myfile.read()) | ||
return ret | ||
|
||
|
||
def write_cfg(path, value) -> None: | ||
""" | ||
:param path: example: "/.rwmeta/developer_settings.json" | ||
:param value: dict | ||
""" | ||
full_path = __build_path(path) | ||
with open(full_path, 'w') as myfile: | ||
myfile.write(json.dumps(value)) | ||
|
||
|
||
def __build_path(path): | ||
if OS_NAME == "windows": | ||
path = path.replace("/", "\\") | ||
full_path = expanduser("~") + path | ||
return full_path | ||
|
||
|
||
def __get_os(): | ||
if os.name == "nt": | ||
return "windows" | ||
|
||
if platform.system() == "Darwin": | ||
return "macos" | ||
|
||
return "linux" | ||
|
||
|
||
OS_NAME = __get_os() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters