code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from ...exception import SDKException
from ...util import Constants
from .writer_response_handler import WriterResponseHandler
class MergeAndDeliverViaWebhookSuccessResponse(WriterResponseHandler):
def __init__(self):
"""Creates an instance of MergeAndDeliverViaWebhookSuccessResponse"""
super().__init__()
self.__merge_report_data_url = None
self.__records = None
self.__key_modified = dict()
def get_merge_report_data_url(self):
"""
The method to get the merge_report_data_url
Returns:
string: A string representing the merge_report_data_url
"""
return self.__merge_report_data_url
def set_merge_report_data_url(self, merge_report_data_url):
"""
The method to set the value to merge_report_data_url
Parameters:
merge_report_data_url (string) : A string representing the merge_report_data_url
"""
if merge_report_data_url is not None and not isinstance(merge_report_data_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: merge_report_data_url EXPECTED TYPE: str', None, None)
self.__merge_report_data_url = merge_report_data_url
self.__key_modified['merge_report_data_url'] = 1
def get_records(self):
"""
The method to get the records
Returns:
list: An instance of list
"""
return self.__records
def set_records(self, records):
"""
The method to set the value to records
Parameters:
records (list) : An instance of list
"""
if records is not None and not isinstance(records, list):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: records EXPECTED TYPE: list', None, None)
self.__records = records
self.__key_modified['records'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/merge_and_deliver_via_webhook_success_response.py | merge_and_deliver_via_webhook_success_response.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import StreamWrapper, Constants
except Exception:
from ...exception import SDKException
from ...util import StreamWrapper, Constants
class GetMergeFieldsParameters(object):
def __init__(self):
"""Creates an instance of GetMergeFieldsParameters"""
self.__file_content = None
self.__file_url = None
self.__key_modified = dict()
def get_file_content(self):
"""
The method to get the file_content
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__file_content
def set_file_content(self, file_content):
"""
The method to set the value to file_content
Parameters:
file_content (StreamWrapper) : An instance of StreamWrapper
"""
if file_content is not None and not isinstance(file_content, StreamWrapper):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: file_content EXPECTED TYPE: StreamWrapper', None, None)
self.__file_content = file_content
self.__key_modified['file_content'] = 1
def get_file_url(self):
"""
The method to get the file_url
Returns:
string: A string representing the file_url
"""
return self.__file_url
def set_file_url(self, file_url):
"""
The method to set the value to file_url
Parameters:
file_url (string) : A string representing the file_url
"""
if file_url is not None and not isinstance(file_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: file_url EXPECTED TYPE: str', None, None)
self.__file_url = file_url
self.__key_modified['file_url'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/get_merge_fields_parameters.py | get_merge_fields_parameters.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from ...exception import SDKException
from ...util import Constants
from .writer_response_handler import WriterResponseHandler
class CompareDocumentResponse(WriterResponseHandler):
def __init__(self):
"""Creates an instance of CompareDocumentResponse"""
super().__init__()
self.__compare_url = None
self.__session_delete_url = None
self.__key_modified = dict()
def get_compare_url(self):
"""
The method to get the compare_url
Returns:
string: A string representing the compare_url
"""
return self.__compare_url
def set_compare_url(self, compare_url):
"""
The method to set the value to compare_url
Parameters:
compare_url (string) : A string representing the compare_url
"""
if compare_url is not None and not isinstance(compare_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: compare_url EXPECTED TYPE: str', None, None)
self.__compare_url = compare_url
self.__key_modified['compare_url'] = 1
def get_session_delete_url(self):
"""
The method to get the session_delete_url
Returns:
string: A string representing the session_delete_url
"""
return self.__session_delete_url
def set_session_delete_url(self, session_delete_url):
"""
The method to set the value to session_delete_url
Parameters:
session_delete_url (string) : A string representing the session_delete_url
"""
if session_delete_url is not None and not isinstance(session_delete_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: session_delete_url EXPECTED TYPE: str', None, None)
self.__session_delete_url = session_delete_url
self.__key_modified['session_delete_url'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/compare_document_response.py | compare_document_response.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import StreamWrapper, Constants
except Exception:
from ...exception import SDKException
from ...util import StreamWrapper, Constants
class CreateDocumentParameters(object):
def __init__(self):
"""Creates an instance of CreateDocumentParameters"""
self.__url = None
self.__document = None
self.__callback_settings = None
self.__document_defaults = None
self.__editor_settings = None
self.__permissions = None
self.__document_info = None
self.__user_info = None
self.__ui_options = None
self.__key_modified = dict()
def get_url(self):
"""
The method to get the url
Returns:
string: A string representing the url
"""
return self.__url
def set_url(self, url):
"""
The method to set the value to url
Parameters:
url (string) : A string representing the url
"""
if url is not None and not isinstance(url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: url EXPECTED TYPE: str', None, None)
self.__url = url
self.__key_modified['url'] = 1
def get_document(self):
"""
The method to get the document
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__document
def set_document(self, document):
"""
The method to set the value to document
Parameters:
document (StreamWrapper) : An instance of StreamWrapper
"""
if document is not None and not isinstance(document, StreamWrapper):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document EXPECTED TYPE: StreamWrapper', None, None)
self.__document = document
self.__key_modified['document'] = 1
def get_callback_settings(self):
"""
The method to get the callback_settings
Returns:
CallbackSettings: An instance of CallbackSettings
"""
return self.__callback_settings
def set_callback_settings(self, callback_settings):
"""
The method to set the value to callback_settings
Parameters:
callback_settings (CallbackSettings) : An instance of CallbackSettings
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.callback_settings import CallbackSettings
except Exception:
from .callback_settings import CallbackSettings
if callback_settings is not None and not isinstance(callback_settings, CallbackSettings):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: callback_settings EXPECTED TYPE: CallbackSettings', None, None)
self.__callback_settings = callback_settings
self.__key_modified['callback_settings'] = 1
def get_document_defaults(self):
"""
The method to get the document_defaults
Returns:
DocumentDefaults: An instance of DocumentDefaults
"""
return self.__document_defaults
def set_document_defaults(self, document_defaults):
"""
The method to set the value to document_defaults
Parameters:
document_defaults (DocumentDefaults) : An instance of DocumentDefaults
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.document_defaults import DocumentDefaults
except Exception:
from .document_defaults import DocumentDefaults
if document_defaults is not None and not isinstance(document_defaults, DocumentDefaults):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_defaults EXPECTED TYPE: DocumentDefaults', None, None)
self.__document_defaults = document_defaults
self.__key_modified['document_defaults'] = 1
def get_editor_settings(self):
"""
The method to get the editor_settings
Returns:
EditorSettings: An instance of EditorSettings
"""
return self.__editor_settings
def set_editor_settings(self, editor_settings):
"""
The method to set the value to editor_settings
Parameters:
editor_settings (EditorSettings) : An instance of EditorSettings
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.editor_settings import EditorSettings
except Exception:
from .editor_settings import EditorSettings
if editor_settings is not None and not isinstance(editor_settings, EditorSettings):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: editor_settings EXPECTED TYPE: EditorSettings', None, None)
self.__editor_settings = editor_settings
self.__key_modified['editor_settings'] = 1
def get_permissions(self):
"""
The method to get the permissions
Returns:
dict: An instance of dict
"""
return self.__permissions
def set_permissions(self, permissions):
"""
The method to set the value to permissions
Parameters:
permissions (dict) : An instance of dict
"""
if permissions is not None and not isinstance(permissions, dict):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: permissions EXPECTED TYPE: dict', None, None)
self.__permissions = permissions
self.__key_modified['permissions'] = 1
def get_document_info(self):
"""
The method to get the document_info
Returns:
DocumentInfo: An instance of DocumentInfo
"""
return self.__document_info
def set_document_info(self, document_info):
"""
The method to set the value to document_info
Parameters:
document_info (DocumentInfo) : An instance of DocumentInfo
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.document_info import DocumentInfo
except Exception:
from .document_info import DocumentInfo
if document_info is not None and not isinstance(document_info, DocumentInfo):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_info EXPECTED TYPE: DocumentInfo', None, None)
self.__document_info = document_info
self.__key_modified['document_info'] = 1
def get_user_info(self):
"""
The method to get the user_info
Returns:
UserInfo: An instance of UserInfo
"""
return self.__user_info
def set_user_info(self, user_info):
"""
The method to set the value to user_info
Parameters:
user_info (UserInfo) : An instance of UserInfo
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.user_info import UserInfo
except Exception:
from .user_info import UserInfo
if user_info is not None and not isinstance(user_info, UserInfo):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: user_info EXPECTED TYPE: UserInfo', None, None)
self.__user_info = user_info
self.__key_modified['user_info'] = 1
def get_ui_options(self):
"""
The method to get the ui_options
Returns:
UiOptions: An instance of UiOptions
"""
return self.__ui_options
def set_ui_options(self, ui_options):
"""
The method to set the value to ui_options
Parameters:
ui_options (UiOptions) : An instance of UiOptions
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.ui_options import UiOptions
except Exception:
from .ui_options import UiOptions
if ui_options is not None and not isinstance(ui_options, UiOptions):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: ui_options EXPECTED TYPE: UiOptions', None, None)
self.__ui_options = ui_options
self.__key_modified['ui_options'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/create_document_parameters.py | create_document_parameters.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class MergeFields(object):
def __init__(self):
"""Creates an instance of MergeFields"""
self.__id = None
self.__display_name = None
self.__type = None
self.__key_modified = dict()
def get_id(self):
"""
The method to get the id
Returns:
string: A string representing the id
"""
return self.__id
def set_id(self, id):
"""
The method to set the value to id
Parameters:
id (string) : A string representing the id
"""
if id is not None and not isinstance(id, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: id EXPECTED TYPE: str', None, None)
self.__id = id
self.__key_modified['id'] = 1
def get_display_name(self):
"""
The method to get the display_name
Returns:
string: A string representing the display_name
"""
return self.__display_name
def set_display_name(self, display_name):
"""
The method to set the value to display_name
Parameters:
display_name (string) : A string representing the display_name
"""
if display_name is not None and not isinstance(display_name, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: display_name EXPECTED TYPE: str', None, None)
self.__display_name = display_name
self.__key_modified['display_name'] = 1
def get_type(self):
"""
The method to get the type
Returns:
string: A string representing the type
"""
return self.__type
def set_type(self, type):
"""
The method to set the value to type
Parameters:
type (string) : A string representing the type
"""
if type is not None and not isinstance(type, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: type EXPECTED TYPE: str', None, None)
self.__type = type
self.__key_modified['type'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/merge_fields.py | merge_fields.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class SheetUserSettings(object):
def __init__(self):
"""Creates an instance of SheetUserSettings"""
self.__display_name = None
self.__key_modified = dict()
def get_display_name(self):
"""
The method to get the display_name
Returns:
string: A string representing the display_name
"""
return self.__display_name
def set_display_name(self, display_name):
"""
The method to set the value to display_name
Parameters:
display_name (string) : A string representing the display_name
"""
if display_name is not None and not isinstance(display_name, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: display_name EXPECTED TYPE: str', None, None)
self.__display_name = display_name
self.__key_modified['display_name'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/sheet_user_settings.py | sheet_user_settings.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class SheetConversionOutputOptions(object):
def __init__(self):
"""Creates an instance of SheetConversionOutputOptions"""
self.__format = None
self.__document_name = None
self.__key_modified = dict()
def get_format(self):
"""
The method to get the format
Returns:
string: A string representing the format
"""
return self.__format
def set_format(self, format):
"""
The method to set the value to format
Parameters:
format (string) : A string representing the format
"""
if format is not None and not isinstance(format, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: format EXPECTED TYPE: str', None, None)
self.__format = format
self.__key_modified['format'] = 1
def get_document_name(self):
"""
The method to get the document_name
Returns:
string: A string representing the document_name
"""
return self.__document_name
def set_document_name(self, document_name):
"""
The method to set the value to document_name
Parameters:
document_name (string) : A string representing the document_name
"""
if document_name is not None and not isinstance(document_name, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_name EXPECTED TYPE: str', None, None)
self.__document_name = document_name
self.__key_modified['document_name'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/sheet_conversion_output_options.py | sheet_conversion_output_options.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
from zohosdk.src.com.zoho.officeintegrator.v1.show_response_handler import ShowResponseHandler
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_response_handler import SheetResponseHandler
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from ...exception import SDKException
from ...util import Constants
from .show_response_handler import ShowResponseHandler
from .sheet_response_handler import SheetResponseHandler
from .writer_response_handler import WriterResponseHandler
class SessionMeta(WriterResponseHandler, SheetResponseHandler, ShowResponseHandler):
def __init__(self):
"""Creates an instance of SessionMeta"""
super().__init__()
self.__status = None
self.__info = None
self.__user_info = None
self.__key_modified = dict()
def get_status(self):
"""
The method to get the status
Returns:
string: A string representing the status
"""
return self.__status
def set_status(self, status):
"""
The method to set the value to status
Parameters:
status (string) : A string representing the status
"""
if status is not None and not isinstance(status, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: status EXPECTED TYPE: str', None, None)
self.__status = status
self.__key_modified['status'] = 1
def get_info(self):
"""
The method to get the info
Returns:
SessionInfo: An instance of SessionInfo
"""
return self.__info
def set_info(self, info):
"""
The method to set the value to info
Parameters:
info (SessionInfo) : An instance of SessionInfo
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.session_info import SessionInfo
except Exception:
from .session_info import SessionInfo
if info is not None and not isinstance(info, SessionInfo):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: info EXPECTED TYPE: SessionInfo', None, None)
self.__info = info
self.__key_modified['info'] = 1
def get_user_info(self):
"""
The method to get the user_info
Returns:
SessionUserInfo: An instance of SessionUserInfo
"""
return self.__user_info
def set_user_info(self, user_info):
"""
The method to set the value to user_info
Parameters:
user_info (SessionUserInfo) : An instance of SessionUserInfo
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.session_user_info import SessionUserInfo
except Exception:
from .session_user_info import SessionUserInfo
if user_info is not None and not isinstance(user_info, SessionUserInfo):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: user_info EXPECTED TYPE: SessionUserInfo', None, None)
self.__user_info = user_info
self.__key_modified['user_info'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/session_meta.py | session_meta.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_response_handler import SheetResponseHandler
except Exception:
from ...exception import SDKException
from ...util import Constants
from .sheet_response_handler import SheetResponseHandler
class CreateSheetResponse(SheetResponseHandler):
def __init__(self):
"""Creates an instance of CreateSheetResponse"""
super().__init__()
self.__document_url = None
self.__document_id = None
self.__save_url = None
self.__session_id = None
self.__session_delete_url = None
self.__document_delete_url = None
self.__gridview_url = None
self.__key_modified = dict()
def get_document_url(self):
"""
The method to get the document_url
Returns:
string: A string representing the document_url
"""
return self.__document_url
def set_document_url(self, document_url):
"""
The method to set the value to document_url
Parameters:
document_url (string) : A string representing the document_url
"""
if document_url is not None and not isinstance(document_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_url EXPECTED TYPE: str', None, None)
self.__document_url = document_url
self.__key_modified['document_url'] = 1
def get_document_id(self):
"""
The method to get the document_id
Returns:
string: A string representing the document_id
"""
return self.__document_id
def set_document_id(self, document_id):
"""
The method to set the value to document_id
Parameters:
document_id (string) : A string representing the document_id
"""
if document_id is not None and not isinstance(document_id, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_id EXPECTED TYPE: str', None, None)
self.__document_id = document_id
self.__key_modified['document_id'] = 1
def get_save_url(self):
"""
The method to get the save_url
Returns:
string: A string representing the save_url
"""
return self.__save_url
def set_save_url(self, save_url):
"""
The method to set the value to save_url
Parameters:
save_url (string) : A string representing the save_url
"""
if save_url is not None and not isinstance(save_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: save_url EXPECTED TYPE: str', None, None)
self.__save_url = save_url
self.__key_modified['save_url'] = 1
def get_session_id(self):
"""
The method to get the session_id
Returns:
string: A string representing the session_id
"""
return self.__session_id
def set_session_id(self, session_id):
"""
The method to set the value to session_id
Parameters:
session_id (string) : A string representing the session_id
"""
if session_id is not None and not isinstance(session_id, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: session_id EXPECTED TYPE: str', None, None)
self.__session_id = session_id
self.__key_modified['session_id'] = 1
def get_session_delete_url(self):
"""
The method to get the session_delete_url
Returns:
string: A string representing the session_delete_url
"""
return self.__session_delete_url
def set_session_delete_url(self, session_delete_url):
"""
The method to set the value to session_delete_url
Parameters:
session_delete_url (string) : A string representing the session_delete_url
"""
if session_delete_url is not None and not isinstance(session_delete_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: session_delete_url EXPECTED TYPE: str', None, None)
self.__session_delete_url = session_delete_url
self.__key_modified['session_delete_url'] = 1
def get_document_delete_url(self):
"""
The method to get the document_delete_url
Returns:
string: A string representing the document_delete_url
"""
return self.__document_delete_url
def set_document_delete_url(self, document_delete_url):
"""
The method to set the value to document_delete_url
Parameters:
document_delete_url (string) : A string representing the document_delete_url
"""
if document_delete_url is not None and not isinstance(document_delete_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_delete_url EXPECTED TYPE: str', None, None)
self.__document_delete_url = document_delete_url
self.__key_modified['document_delete_url'] = 1
def get_gridview_url(self):
"""
The method to get the gridview_url
Returns:
string: A string representing the gridview_url
"""
return self.__gridview_url
def set_gridview_url(self, gridview_url):
"""
The method to set the value to gridview_url
Parameters:
gridview_url (string) : A string representing the gridview_url
"""
if gridview_url is not None and not isinstance(gridview_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: gridview_url EXPECTED TYPE: str', None, None)
self.__gridview_url = gridview_url
self.__key_modified['gridview_url'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/create_sheet_response.py | create_sheet_response.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class FillableSubmissionSettings(object):
def __init__(self):
"""Creates an instance of FillableSubmissionSettings"""
self.__callback_options = None
self.__redirect_url = None
self.__onsubmit_message = None
self.__key_modified = dict()
def get_callback_options(self):
"""
The method to get the callback_options
Returns:
FillableCallbackSettings: An instance of FillableCallbackSettings
"""
return self.__callback_options
def set_callback_options(self, callback_options):
"""
The method to set the value to callback_options
Parameters:
callback_options (FillableCallbackSettings) : An instance of FillableCallbackSettings
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.fillable_callback_settings import FillableCallbackSettings
except Exception:
from .fillable_callback_settings import FillableCallbackSettings
if callback_options is not None and not isinstance(callback_options, FillableCallbackSettings):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: callback_options EXPECTED TYPE: FillableCallbackSettings', None, None)
self.__callback_options = callback_options
self.__key_modified['callback_options'] = 1
def get_redirect_url(self):
"""
The method to get the redirect_url
Returns:
string: A string representing the redirect_url
"""
return self.__redirect_url
def set_redirect_url(self, redirect_url):
"""
The method to set the value to redirect_url
Parameters:
redirect_url (string) : A string representing the redirect_url
"""
if redirect_url is not None and not isinstance(redirect_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: redirect_url EXPECTED TYPE: str', None, None)
self.__redirect_url = redirect_url
self.__key_modified['redirect_url'] = 1
def get_onsubmit_message(self):
"""
The method to get the onsubmit_message
Returns:
string: A string representing the onsubmit_message
"""
return self.__onsubmit_message
def set_onsubmit_message(self, onsubmit_message):
"""
The method to set the value to onsubmit_message
Parameters:
onsubmit_message (string) : A string representing the onsubmit_message
"""
if onsubmit_message is not None and not isinstance(onsubmit_message, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: onsubmit_message EXPECTED TYPE: str', None, None)
self.__onsubmit_message = onsubmit_message
self.__key_modified['onsubmit_message'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/fillable_submission_settings.py | fillable_submission_settings.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import StreamWrapper, Constants
from zohosdk.src.com.zoho.officeintegrator.v1.show_response_handler import ShowResponseHandler
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_response_handler import SheetResponseHandler
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from ...exception import SDKException
from ...util import StreamWrapper, Constants
from .show_response_handler import ShowResponseHandler
from .sheet_response_handler import SheetResponseHandler
from .writer_response_handler import WriterResponseHandler
class FileBodyWrapper(WriterResponseHandler, SheetResponseHandler, ShowResponseHandler):
def __init__(self):
"""Creates an instance of FileBodyWrapper"""
super().__init__()
self.__file = None
self.__key_modified = dict()
def get_file(self):
"""
The method to get the file
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__file
def set_file(self, file):
"""
The method to set the value to file
Parameters:
file (StreamWrapper) : An instance of StreamWrapper
"""
if file is not None and not isinstance(file, StreamWrapper):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: file EXPECTED TYPE: StreamWrapper', None, None)
self.__file = file
self.__key_modified['file'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/file_body_wrapper.py | file_body_wrapper.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class UserInfo(object):
def __init__(self):
"""Creates an instance of UserInfo"""
self.__user_id = None
self.__display_name = None
self.__key_modified = dict()
def get_user_id(self):
"""
The method to get the user_id
Returns:
string: A string representing the user_id
"""
return self.__user_id
def set_user_id(self, user_id):
"""
The method to set the value to user_id
Parameters:
user_id (string) : A string representing the user_id
"""
if user_id is not None and not isinstance(user_id, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: user_id EXPECTED TYPE: str', None, None)
self.__user_id = user_id
self.__key_modified['user_id'] = 1
def get_display_name(self):
"""
The method to get the display_name
Returns:
string: A string representing the display_name
"""
return self.__display_name
def set_display_name(self, display_name):
"""
The method to set the value to display_name
Parameters:
display_name (string) : A string representing the display_name
"""
if display_name is not None and not isinstance(display_name, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: display_name EXPECTED TYPE: str', None, None)
self.__display_name = display_name
self.__key_modified['display_name'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/user_info.py | user_info.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class FillableFormOptions(object):
def __init__(self):
"""Creates an instance of FillableFormOptions"""
self.__download = None
self.__print = None
self.__submit = None
self.__key_modified = dict()
def get_download(self):
"""
The method to get the download
Returns:
bool: A bool representing the download
"""
return self.__download
def set_download(self, download):
"""
The method to set the value to download
Parameters:
download (bool) : A bool representing the download
"""
if download is not None and not isinstance(download, bool):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: download EXPECTED TYPE: bool', None, None)
self.__download = download
self.__key_modified['download'] = 1
def get_print(self):
"""
The method to get the print
Returns:
bool: A bool representing the print
"""
return self.__print
def set_print(self, print):
"""
The method to set the value to print
Parameters:
print (bool) : A bool representing the print
"""
if print is not None and not isinstance(print, bool):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: print EXPECTED TYPE: bool', None, None)
self.__print = print
self.__key_modified['print'] = 1
def get_submit(self):
"""
The method to get the submit
Returns:
bool: A bool representing the submit
"""
return self.__submit
def set_submit(self, submit):
"""
The method to set the value to submit
Parameters:
submit (bool) : A bool representing the submit
"""
if submit is not None and not isinstance(submit, bool):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: submit EXPECTED TYPE: bool', None, None)
self.__submit = submit
self.__key_modified['submit'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/fillable_form_options.py | fillable_form_options.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import StreamWrapper, Constants
except Exception:
from ...exception import SDKException
from ...util import StreamWrapper, Constants
class CreatePresentationParameters(object):
def __init__(self):
"""Creates an instance of CreatePresentationParameters"""
self.__url = None
self.__document = None
self.__callback_settings = None
self.__editor_settings = None
self.__permissions = None
self.__document_info = None
self.__user_info = None
self.__key_modified = dict()
def get_url(self):
"""
The method to get the url
Returns:
string: A string representing the url
"""
return self.__url
def set_url(self, url):
"""
The method to set the value to url
Parameters:
url (string) : A string representing the url
"""
if url is not None and not isinstance(url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: url EXPECTED TYPE: str', None, None)
self.__url = url
self.__key_modified['url'] = 1
def get_document(self):
"""
The method to get the document
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__document
def set_document(self, document):
"""
The method to set the value to document
Parameters:
document (StreamWrapper) : An instance of StreamWrapper
"""
if document is not None and not isinstance(document, StreamWrapper):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document EXPECTED TYPE: StreamWrapper', None, None)
self.__document = document
self.__key_modified['document'] = 1
def get_callback_settings(self):
"""
The method to get the callback_settings
Returns:
CallbackSettings: An instance of CallbackSettings
"""
return self.__callback_settings
def set_callback_settings(self, callback_settings):
"""
The method to set the value to callback_settings
Parameters:
callback_settings (CallbackSettings) : An instance of CallbackSettings
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.callback_settings import CallbackSettings
except Exception:
from .callback_settings import CallbackSettings
if callback_settings is not None and not isinstance(callback_settings, CallbackSettings):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: callback_settings EXPECTED TYPE: CallbackSettings', None, None)
self.__callback_settings = callback_settings
self.__key_modified['callback_settings'] = 1
def get_editor_settings(self):
"""
The method to get the editor_settings
Returns:
ZohoShowEditorSettings: An instance of ZohoShowEditorSettings
"""
return self.__editor_settings
def set_editor_settings(self, editor_settings):
"""
The method to set the value to editor_settings
Parameters:
editor_settings (ZohoShowEditorSettings) : An instance of ZohoShowEditorSettings
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.zoho_show_editor_settings import ZohoShowEditorSettings
except Exception:
from .zoho_show_editor_settings import ZohoShowEditorSettings
if editor_settings is not None and not isinstance(editor_settings, ZohoShowEditorSettings):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: editor_settings EXPECTED TYPE: ZohoShowEditorSettings', None, None)
self.__editor_settings = editor_settings
self.__key_modified['editor_settings'] = 1
def get_permissions(self):
"""
The method to get the permissions
Returns:
dict: An instance of dict
"""
return self.__permissions
def set_permissions(self, permissions):
"""
The method to set the value to permissions
Parameters:
permissions (dict) : An instance of dict
"""
if permissions is not None and not isinstance(permissions, dict):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: permissions EXPECTED TYPE: dict', None, None)
self.__permissions = permissions
self.__key_modified['permissions'] = 1
def get_document_info(self):
"""
The method to get the document_info
Returns:
DocumentInfo: An instance of DocumentInfo
"""
return self.__document_info
def set_document_info(self, document_info):
"""
The method to set the value to document_info
Parameters:
document_info (DocumentInfo) : An instance of DocumentInfo
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.document_info import DocumentInfo
except Exception:
from .document_info import DocumentInfo
if document_info is not None and not isinstance(document_info, DocumentInfo):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_info EXPECTED TYPE: DocumentInfo', None, None)
self.__document_info = document_info
self.__key_modified['document_info'] = 1
def get_user_info(self):
"""
The method to get the user_info
Returns:
UserInfo: An instance of UserInfo
"""
return self.__user_info
def set_user_info(self, user_info):
"""
The method to set the value to user_info
Parameters:
user_info (UserInfo) : An instance of UserInfo
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.user_info import UserInfo
except Exception:
from .user_info import UserInfo
if user_info is not None and not isinstance(user_info, UserInfo):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: user_info EXPECTED TYPE: UserInfo', None, None)
self.__user_info = user_info
self.__key_modified['user_info'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/create_presentation_parameters.py | create_presentation_parameters.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class UiOptions(object):
def __init__(self):
"""Creates an instance of UiOptions"""
self.__save_button = None
self.__chat_panel = None
self.__file_menu = None
self.__dark_mode = None
self.__key_modified = dict()
def get_save_button(self):
"""
The method to get the save_button
Returns:
string: A string representing the save_button
"""
return self.__save_button
def set_save_button(self, save_button):
"""
The method to set the value to save_button
Parameters:
save_button (string) : A string representing the save_button
"""
if save_button is not None and not isinstance(save_button, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: save_button EXPECTED TYPE: str', None, None)
self.__save_button = save_button
self.__key_modified['save_button'] = 1
def get_chat_panel(self):
"""
The method to get the chat_panel
Returns:
string: A string representing the chat_panel
"""
return self.__chat_panel
def set_chat_panel(self, chat_panel):
"""
The method to set the value to chat_panel
Parameters:
chat_panel (string) : A string representing the chat_panel
"""
if chat_panel is not None and not isinstance(chat_panel, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: chat_panel EXPECTED TYPE: str', None, None)
self.__chat_panel = chat_panel
self.__key_modified['chat_panel'] = 1
def get_file_menu(self):
"""
The method to get the file_menu
Returns:
string: A string representing the file_menu
"""
return self.__file_menu
def set_file_menu(self, file_menu):
"""
The method to set the value to file_menu
Parameters:
file_menu (string) : A string representing the file_menu
"""
if file_menu is not None and not isinstance(file_menu, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: file_menu EXPECTED TYPE: str', None, None)
self.__file_menu = file_menu
self.__key_modified['file_menu'] = 1
def get_dark_mode(self):
"""
The method to get the dark_mode
Returns:
string: A string representing the dark_mode
"""
return self.__dark_mode
def set_dark_mode(self, dark_mode):
"""
The method to set the value to dark_mode
Parameters:
dark_mode (string) : A string representing the dark_mode
"""
if dark_mode is not None and not isinstance(dark_mode, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: dark_mode EXPECTED TYPE: str', None, None)
self.__dark_mode = dark_mode
self.__key_modified['dark_mode'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/ui_options.py | ui_options.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class DocumentInfo(object):
def __init__(self):
"""Creates an instance of DocumentInfo"""
self.__document_name = None
self.__document_id = None
self.__key_modified = dict()
def get_document_name(self):
"""
The method to get the document_name
Returns:
string: A string representing the document_name
"""
return self.__document_name
def set_document_name(self, document_name):
"""
The method to set the value to document_name
Parameters:
document_name (string) : A string representing the document_name
"""
if document_name is not None and not isinstance(document_name, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_name EXPECTED TYPE: str', None, None)
self.__document_name = document_name
self.__key_modified['document_name'] = 1
def get_document_id(self):
"""
The method to get the document_id
Returns:
string: A string representing the document_id
"""
return self.__document_id
def set_document_id(self, document_id):
"""
The method to set the value to document_id
Parameters:
document_id (string) : A string representing the document_id
"""
if document_id is not None and not isinstance(document_id, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_id EXPECTED TYPE: str', None, None)
self.__document_id = document_id
self.__key_modified['document_id'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/document_info.py | document_info.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import StreamWrapper, Constants
except Exception:
from ...exception import SDKException
from ...util import StreamWrapper, Constants
class CompareDocumentParameters(object):
def __init__(self):
"""Creates an instance of CompareDocumentParameters"""
self.__document1 = None
self.__url1 = None
self.__document2 = None
self.__url2 = None
self.__title = None
self.__lang = None
self.__key_modified = dict()
def get_document1(self):
"""
The method to get the document1
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__document1
def set_document1(self, document1):
"""
The method to set the value to document1
Parameters:
document1 (StreamWrapper) : An instance of StreamWrapper
"""
if document1 is not None and not isinstance(document1, StreamWrapper):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document1 EXPECTED TYPE: StreamWrapper', None, None)
self.__document1 = document1
self.__key_modified['document1'] = 1
def get_url1(self):
"""
The method to get the url1
Returns:
string: A string representing the url1
"""
return self.__url1
def set_url1(self, url1):
"""
The method to set the value to url1
Parameters:
url1 (string) : A string representing the url1
"""
if url1 is not None and not isinstance(url1, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: url1 EXPECTED TYPE: str', None, None)
self.__url1 = url1
self.__key_modified['url1'] = 1
def get_document2(self):
"""
The method to get the document2
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__document2
def set_document2(self, document2):
"""
The method to set the value to document2
Parameters:
document2 (StreamWrapper) : An instance of StreamWrapper
"""
if document2 is not None and not isinstance(document2, StreamWrapper):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document2 EXPECTED TYPE: StreamWrapper', None, None)
self.__document2 = document2
self.__key_modified['document2'] = 1
def get_url2(self):
"""
The method to get the url2
Returns:
string: A string representing the url2
"""
return self.__url2
def set_url2(self, url2):
"""
The method to set the value to url2
Parameters:
url2 (string) : A string representing the url2
"""
if url2 is not None and not isinstance(url2, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: url2 EXPECTED TYPE: str', None, None)
self.__url2 = url2
self.__key_modified['url2'] = 1
def get_title(self):
"""
The method to get the title
Returns:
string: A string representing the title
"""
return self.__title
def set_title(self, title):
"""
The method to set the value to title
Parameters:
title (string) : A string representing the title
"""
if title is not None and not isinstance(title, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: title EXPECTED TYPE: str', None, None)
self.__title = title
self.__key_modified['title'] = 1
def get_lang(self):
"""
The method to get the lang
Returns:
string: A string representing the lang
"""
return self.__lang
def set_lang(self, lang):
"""
The method to set the value to lang
Parameters:
lang (string) : A string representing the lang
"""
if lang is not None and not isinstance(lang, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: lang EXPECTED TYPE: str', None, None)
self.__lang = lang
self.__key_modified['lang'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/compare_document_parameters.py | compare_document_parameters.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import StreamWrapper, Constants
except Exception:
from ...exception import SDKException
from ...util import StreamWrapper, Constants
class SheetConversionParameters(object):
def __init__(self):
"""Creates an instance of SheetConversionParameters"""
self.__url = None
self.__document = None
self.__output_options = None
self.__key_modified = dict()
def get_url(self):
"""
The method to get the url
Returns:
string: A string representing the url
"""
return self.__url
def set_url(self, url):
"""
The method to set the value to url
Parameters:
url (string) : A string representing the url
"""
if url is not None and not isinstance(url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: url EXPECTED TYPE: str', None, None)
self.__url = url
self.__key_modified['url'] = 1
def get_document(self):
"""
The method to get the document
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__document
def set_document(self, document):
"""
The method to set the value to document
Parameters:
document (StreamWrapper) : An instance of StreamWrapper
"""
if document is not None and not isinstance(document, StreamWrapper):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document EXPECTED TYPE: StreamWrapper', None, None)
self.__document = document
self.__key_modified['document'] = 1
def get_output_options(self):
"""
The method to get the output_options
Returns:
SheetConversionOutputOptions: An instance of SheetConversionOutputOptions
"""
return self.__output_options
def set_output_options(self, output_options):
"""
The method to set the value to output_options
Parameters:
output_options (SheetConversionOutputOptions) : An instance of SheetConversionOutputOptions
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_conversion_output_options import SheetConversionOutputOptions
except Exception:
from .sheet_conversion_output_options import SheetConversionOutputOptions
if output_options is not None and not isinstance(output_options, SheetConversionOutputOptions):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: output_options EXPECTED TYPE: SheetConversionOutputOptions', None, None)
self.__output_options = output_options
self.__key_modified['output_options'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/sheet_conversion_parameters.py | sheet_conversion_parameters.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class EditorSettings(object):
def __init__(self):
"""Creates an instance of EditorSettings"""
self.__unit = None
self.__language = None
self.__view = None
self.__key_modified = dict()
def get_unit(self):
"""
The method to get the unit
Returns:
string: A string representing the unit
"""
return self.__unit
def set_unit(self, unit):
"""
The method to set the value to unit
Parameters:
unit (string) : A string representing the unit
"""
if unit is not None and not isinstance(unit, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: unit EXPECTED TYPE: str', None, None)
self.__unit = unit
self.__key_modified['unit'] = 1
def get_language(self):
"""
The method to get the language
Returns:
string: A string representing the language
"""
return self.__language
def set_language(self, language):
"""
The method to set the value to language
Parameters:
language (string) : A string representing the language
"""
if language is not None and not isinstance(language, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: language EXPECTED TYPE: str', None, None)
self.__language = language
self.__key_modified['language'] = 1
def get_view(self):
"""
The method to get the view
Returns:
string: A string representing the view
"""
return self.__view
def set_view(self, view):
"""
The method to set the value to view
Parameters:
view (string) : A string representing the view
"""
if view is not None and not isinstance(view, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: view EXPECTED TYPE: str', None, None)
self.__view = view
self.__key_modified['view'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/editor_settings.py | editor_settings.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
from zohosdk.src.com.zoho.officeintegrator.v1.show_response_handler import ShowResponseHandler
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from ...exception import SDKException
from ...util import Constants
from .show_response_handler import ShowResponseHandler
from .writer_response_handler import WriterResponseHandler
class CreateDocumentResponse(WriterResponseHandler, ShowResponseHandler):
def __init__(self):
"""Creates an instance of CreateDocumentResponse"""
super().__init__()
self.__document_url = None
self.__document_id = None
self.__save_url = None
self.__session_id = None
self.__session_delete_url = None
self.__document_delete_url = None
self.__key_modified = dict()
def get_document_url(self):
"""
The method to get the document_url
Returns:
string: A string representing the document_url
"""
return self.__document_url
def set_document_url(self, document_url):
"""
The method to set the value to document_url
Parameters:
document_url (string) : A string representing the document_url
"""
if document_url is not None and not isinstance(document_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_url EXPECTED TYPE: str', None, None)
self.__document_url = document_url
self.__key_modified['document_url'] = 1
def get_document_id(self):
"""
The method to get the document_id
Returns:
string: A string representing the document_id
"""
return self.__document_id
def set_document_id(self, document_id):
"""
The method to set the value to document_id
Parameters:
document_id (string) : A string representing the document_id
"""
if document_id is not None and not isinstance(document_id, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_id EXPECTED TYPE: str', None, None)
self.__document_id = document_id
self.__key_modified['document_id'] = 1
def get_save_url(self):
"""
The method to get the save_url
Returns:
string: A string representing the save_url
"""
return self.__save_url
def set_save_url(self, save_url):
"""
The method to set the value to save_url
Parameters:
save_url (string) : A string representing the save_url
"""
if save_url is not None and not isinstance(save_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: save_url EXPECTED TYPE: str', None, None)
self.__save_url = save_url
self.__key_modified['save_url'] = 1
def get_session_id(self):
"""
The method to get the session_id
Returns:
string: A string representing the session_id
"""
return self.__session_id
def set_session_id(self, session_id):
"""
The method to set the value to session_id
Parameters:
session_id (string) : A string representing the session_id
"""
if session_id is not None and not isinstance(session_id, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: session_id EXPECTED TYPE: str', None, None)
self.__session_id = session_id
self.__key_modified['session_id'] = 1
def get_session_delete_url(self):
"""
The method to get the session_delete_url
Returns:
string: A string representing the session_delete_url
"""
return self.__session_delete_url
def set_session_delete_url(self, session_delete_url):
"""
The method to set the value to session_delete_url
Parameters:
session_delete_url (string) : A string representing the session_delete_url
"""
if session_delete_url is not None and not isinstance(session_delete_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: session_delete_url EXPECTED TYPE: str', None, None)
self.__session_delete_url = session_delete_url
self.__key_modified['session_delete_url'] = 1
def get_document_delete_url(self):
"""
The method to get the document_delete_url
Returns:
string: A string representing the document_delete_url
"""
return self.__document_delete_url
def set_document_delete_url(self, document_delete_url):
"""
The method to set the value to document_delete_url
Parameters:
document_delete_url (string) : A string representing the document_delete_url
"""
if document_delete_url is not None and not isinstance(document_delete_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_delete_url EXPECTED TYPE: str', None, None)
self.__document_delete_url = document_delete_url
self.__key_modified['document_delete_url'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/create_document_response.py | create_document_response.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import StreamWrapper, Constants
except Exception:
from ...exception import SDKException
from ...util import StreamWrapper, Constants
class SheetPreviewParameters(object):
def __init__(self):
"""Creates an instance of SheetPreviewParameters"""
self.__url = None
self.__document = None
self.__language = None
self.__permissions = None
self.__key_modified = dict()
def get_url(self):
"""
The method to get the url
Returns:
string: A string representing the url
"""
return self.__url
def set_url(self, url):
"""
The method to set the value to url
Parameters:
url (string) : A string representing the url
"""
if url is not None and not isinstance(url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: url EXPECTED TYPE: str', None, None)
self.__url = url
self.__key_modified['url'] = 1
def get_document(self):
"""
The method to get the document
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__document
def set_document(self, document):
"""
The method to set the value to document
Parameters:
document (StreamWrapper) : An instance of StreamWrapper
"""
if document is not None and not isinstance(document, StreamWrapper):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document EXPECTED TYPE: StreamWrapper', None, None)
self.__document = document
self.__key_modified['document'] = 1
def get_language(self):
"""
The method to get the language
Returns:
string: A string representing the language
"""
return self.__language
def set_language(self, language):
"""
The method to set the value to language
Parameters:
language (string) : A string representing the language
"""
if language is not None and not isinstance(language, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: language EXPECTED TYPE: str', None, None)
self.__language = language
self.__key_modified['language'] = 1
def get_permissions(self):
"""
The method to get the permissions
Returns:
dict: An instance of dict
"""
return self.__permissions
def set_permissions(self, permissions):
"""
The method to set the value to permissions
Parameters:
permissions (dict) : An instance of dict
"""
if permissions is not None and not isinstance(permissions, dict):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: permissions EXPECTED TYPE: dict', None, None)
self.__permissions = permissions
self.__key_modified['permissions'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/sheet_preview_parameters.py | sheet_preview_parameters.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class SessionUserInfo(object):
def __init__(self):
"""Creates an instance of SessionUserInfo"""
self.__display_name = None
self.__user_id = None
self.__key_modified = dict()
def get_display_name(self):
"""
The method to get the display_name
Returns:
string: A string representing the display_name
"""
return self.__display_name
def set_display_name(self, display_name):
"""
The method to set the value to display_name
Parameters:
display_name (string) : A string representing the display_name
"""
if display_name is not None and not isinstance(display_name, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: display_name EXPECTED TYPE: str', None, None)
self.__display_name = display_name
self.__key_modified['display_name'] = 1
def get_user_id(self):
"""
The method to get the user_id
Returns:
string: A string representing the user_id
"""
return self.__user_id
def set_user_id(self, user_id):
"""
The method to set the value to user_id
Parameters:
user_id (string) : A string representing the user_id
"""
if user_id is not None and not isinstance(user_id, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: user_id EXPECTED TYPE: str', None, None)
self.__user_id = user_id
self.__key_modified['user_id'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/session_user_info.py | session_user_info.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from ...exception import SDKException
from ...util import Constants
from .writer_response_handler import WriterResponseHandler
class DocumentSessionDeleteSuccessResponse(WriterResponseHandler):
def __init__(self):
"""Creates an instance of DocumentSessionDeleteSuccessResponse"""
super().__init__()
self.__session_deleted = None
self.__key_modified = dict()
def get_session_deleted(self):
"""
The method to get the session_deleted
Returns:
bool: A bool representing the session_deleted
"""
return self.__session_deleted
def set_session_deleted(self, session_deleted):
"""
The method to set the value to session_deleted
Parameters:
session_deleted (bool) : A bool representing the session_deleted
"""
if session_deleted is not None and not isinstance(session_deleted, bool):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: session_deleted EXPECTED TYPE: bool', None, None)
self.__session_deleted = session_deleted
self.__key_modified['session_deleted'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/document_session_delete_success_response.py | document_session_delete_success_response.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class PreviewDocumentInfo(object):
def __init__(self):
"""Creates an instance of PreviewDocumentInfo"""
self.__document_name = None
self.__key_modified = dict()
def get_document_name(self):
"""
The method to get the document_name
Returns:
string: A string representing the document_name
"""
return self.__document_name
def set_document_name(self, document_name):
"""
The method to set the value to document_name
Parameters:
document_name (string) : A string representing the document_name
"""
if document_name is not None and not isinstance(document_name, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_name EXPECTED TYPE: str', None, None)
self.__document_name = document_name
self.__key_modified['document_name'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/preview_document_info.py | preview_document_info.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import StreamWrapper, Constants
except Exception:
from ...exception import SDKException
from ...util import StreamWrapper, Constants
class ConvertPresentationParameters(object):
def __init__(self):
"""Creates an instance of ConvertPresentationParameters"""
self.__url = None
self.__document = None
self.__format = None
self.__key_modified = dict()
def get_url(self):
"""
The method to get the url
Returns:
string: A string representing the url
"""
return self.__url
def set_url(self, url):
"""
The method to set the value to url
Parameters:
url (string) : A string representing the url
"""
if url is not None and not isinstance(url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: url EXPECTED TYPE: str', None, None)
self.__url = url
self.__key_modified['url'] = 1
def get_document(self):
"""
The method to get the document
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__document
def set_document(self, document):
"""
The method to set the value to document
Parameters:
document (StreamWrapper) : An instance of StreamWrapper
"""
if document is not None and not isinstance(document, StreamWrapper):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document EXPECTED TYPE: StreamWrapper', None, None)
self.__document = document
self.__key_modified['document'] = 1
def get_format(self):
"""
The method to get the format
Returns:
string: A string representing the format
"""
return self.__format
def set_format(self, format):
"""
The method to set the value to format
Parameters:
format (string) : A string representing the format
"""
if format is not None and not isinstance(format, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: format EXPECTED TYPE: str', None, None)
self.__format = format
self.__key_modified['format'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/convert_presentation_parameters.py | convert_presentation_parameters.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class MergeAndDeliverRecordsMeta(object):
def __init__(self):
"""Creates an instance of MergeAndDeliverRecordsMeta"""
self.__download_link = None
self.__email = None
self.__name = None
self.__status = None
self.__key_modified = dict()
def get_download_link(self):
"""
The method to get the download_link
Returns:
string: A string representing the download_link
"""
return self.__download_link
def set_download_link(self, download_link):
"""
The method to set the value to download_link
Parameters:
download_link (string) : A string representing the download_link
"""
if download_link is not None and not isinstance(download_link, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: download_link EXPECTED TYPE: str', None, None)
self.__download_link = download_link
self.__key_modified['download_link'] = 1
def get_email(self):
"""
The method to get the email
Returns:
string: A string representing the email
"""
return self.__email
def set_email(self, email):
"""
The method to set the value to email
Parameters:
email (string) : A string representing the email
"""
if email is not None and not isinstance(email, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: email EXPECTED TYPE: str', None, None)
self.__email = email
self.__key_modified['email'] = 1
def get_name(self):
"""
The method to get the name
Returns:
string: A string representing the name
"""
return self.__name
def set_name(self, name):
"""
The method to set the value to name
Parameters:
name (string) : A string representing the name
"""
if name is not None and not isinstance(name, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: name EXPECTED TYPE: str', None, None)
self.__name = name
self.__key_modified['name'] = 1
def get_status(self):
"""
The method to get the status
Returns:
string: A string representing the status
"""
return self.__status
def set_status(self, status):
"""
The method to set the value to status
Parameters:
status (string) : A string representing the status
"""
if status is not None and not isinstance(status, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: status EXPECTED TYPE: str', None, None)
self.__status = status
self.__key_modified['status'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/merge_and_deliver_records_meta.py | merge_and_deliver_records_meta.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import StreamWrapper, Constants
except Exception:
from ...exception import SDKException
from ...util import StreamWrapper, Constants
class FillableLinkParameters(object):
def __init__(self):
"""Creates an instance of FillableLinkParameters"""
self.__document = None
self.__url = None
self.__document_info = None
self.__user_info = None
self.__prefill_data = None
self.__form_language = None
self.__submit_settings = None
self.__form_options = None
self.__key_modified = dict()
def get_document(self):
"""
The method to get the document
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__document
def set_document(self, document):
"""
The method to set the value to document
Parameters:
document (StreamWrapper) : An instance of StreamWrapper
"""
if document is not None and not isinstance(document, StreamWrapper):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document EXPECTED TYPE: StreamWrapper', None, None)
self.__document = document
self.__key_modified['document'] = 1
def get_url(self):
"""
The method to get the url
Returns:
string: A string representing the url
"""
return self.__url
def set_url(self, url):
"""
The method to set the value to url
Parameters:
url (string) : A string representing the url
"""
if url is not None and not isinstance(url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: url EXPECTED TYPE: str', None, None)
self.__url = url
self.__key_modified['url'] = 1
def get_document_info(self):
"""
The method to get the document_info
Returns:
DocumentInfo: An instance of DocumentInfo
"""
return self.__document_info
def set_document_info(self, document_info):
"""
The method to set the value to document_info
Parameters:
document_info (DocumentInfo) : An instance of DocumentInfo
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.document_info import DocumentInfo
except Exception:
from .document_info import DocumentInfo
if document_info is not None and not isinstance(document_info, DocumentInfo):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_info EXPECTED TYPE: DocumentInfo', None, None)
self.__document_info = document_info
self.__key_modified['document_info'] = 1
def get_user_info(self):
"""
The method to get the user_info
Returns:
UserInfo: An instance of UserInfo
"""
return self.__user_info
def set_user_info(self, user_info):
"""
The method to set the value to user_info
Parameters:
user_info (UserInfo) : An instance of UserInfo
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.user_info import UserInfo
except Exception:
from .user_info import UserInfo
if user_info is not None and not isinstance(user_info, UserInfo):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: user_info EXPECTED TYPE: UserInfo', None, None)
self.__user_info = user_info
self.__key_modified['user_info'] = 1
def get_prefill_data(self):
"""
The method to get the prefill_data
Returns:
dict: An instance of dict
"""
return self.__prefill_data
def set_prefill_data(self, prefill_data):
"""
The method to set the value to prefill_data
Parameters:
prefill_data (dict) : An instance of dict
"""
if prefill_data is not None and not isinstance(prefill_data, dict):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: prefill_data EXPECTED TYPE: dict', None, None)
self.__prefill_data = prefill_data
self.__key_modified['prefill_data'] = 1
def get_form_language(self):
"""
The method to get the form_language
Returns:
string: A string representing the form_language
"""
return self.__form_language
def set_form_language(self, form_language):
"""
The method to set the value to form_language
Parameters:
form_language (string) : A string representing the form_language
"""
if form_language is not None and not isinstance(form_language, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: form_language EXPECTED TYPE: str', None, None)
self.__form_language = form_language
self.__key_modified['form_language'] = 1
def get_submit_settings(self):
"""
The method to get the submit_settings
Returns:
FillableSubmissionSettings: An instance of FillableSubmissionSettings
"""
return self.__submit_settings
def set_submit_settings(self, submit_settings):
"""
The method to set the value to submit_settings
Parameters:
submit_settings (FillableSubmissionSettings) : An instance of FillableSubmissionSettings
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.fillable_submission_settings import FillableSubmissionSettings
except Exception:
from .fillable_submission_settings import FillableSubmissionSettings
if submit_settings is not None and not isinstance(submit_settings, FillableSubmissionSettings):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: submit_settings EXPECTED TYPE: FillableSubmissionSettings', None, None)
self.__submit_settings = submit_settings
self.__key_modified['submit_settings'] = 1
def get_form_options(self):
"""
The method to get the form_options
Returns:
FillableFormOptions: An instance of FillableFormOptions
"""
return self.__form_options
def set_form_options(self, form_options):
"""
The method to set the value to form_options
Parameters:
form_options (FillableFormOptions) : An instance of FillableFormOptions
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.fillable_form_options import FillableFormOptions
except Exception:
from .fillable_form_options import FillableFormOptions
if form_options is not None and not isinstance(form_options, FillableFormOptions):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: form_options EXPECTED TYPE: FillableFormOptions', None, None)
self.__form_options = form_options
self.__key_modified['form_options'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/fillable_link_parameters.py | fillable_link_parameters.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import StreamWrapper, Constants
except Exception:
from ...exception import SDKException
from ...util import StreamWrapper, Constants
class WatermarkParameters(object):
def __init__(self):
"""Creates an instance of WatermarkParameters"""
self.__url = None
self.__document = None
self.__watermark_settings = None
self.__key_modified = dict()
def get_url(self):
"""
The method to get the url
Returns:
string: A string representing the url
"""
return self.__url
def set_url(self, url):
"""
The method to set the value to url
Parameters:
url (string) : A string representing the url
"""
if url is not None and not isinstance(url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: url EXPECTED TYPE: str', None, None)
self.__url = url
self.__key_modified['url'] = 1
def get_document(self):
"""
The method to get the document
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__document
def set_document(self, document):
"""
The method to set the value to document
Parameters:
document (StreamWrapper) : An instance of StreamWrapper
"""
if document is not None and not isinstance(document, StreamWrapper):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document EXPECTED TYPE: StreamWrapper', None, None)
self.__document = document
self.__key_modified['document'] = 1
def get_watermark_settings(self):
"""
The method to get the watermark_settings
Returns:
WatermarkSettings: An instance of WatermarkSettings
"""
return self.__watermark_settings
def set_watermark_settings(self, watermark_settings):
"""
The method to set the value to watermark_settings
Parameters:
watermark_settings (WatermarkSettings) : An instance of WatermarkSettings
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.watermark_settings import WatermarkSettings
except Exception:
from .watermark_settings import WatermarkSettings
if watermark_settings is not None and not isinstance(watermark_settings, WatermarkSettings):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: watermark_settings EXPECTED TYPE: WatermarkSettings', None, None)
self.__watermark_settings = watermark_settings
self.__key_modified['watermark_settings'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/watermark_parameters.py | watermark_parameters.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import StreamWrapper, Constants
except Exception:
from ...exception import SDKException
from ...util import StreamWrapper, Constants
class PreviewParameters(object):
def __init__(self):
"""Creates an instance of PreviewParameters"""
self.__url = None
self.__document = None
self.__document_info = None
self.__permissions = None
self.__key_modified = dict()
def get_url(self):
"""
The method to get the url
Returns:
string: A string representing the url
"""
return self.__url
def set_url(self, url):
"""
The method to set the value to url
Parameters:
url (string) : A string representing the url
"""
if url is not None and not isinstance(url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: url EXPECTED TYPE: str', None, None)
self.__url = url
self.__key_modified['url'] = 1
def get_document(self):
"""
The method to get the document
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__document
def set_document(self, document):
"""
The method to set the value to document
Parameters:
document (StreamWrapper) : An instance of StreamWrapper
"""
if document is not None and not isinstance(document, StreamWrapper):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document EXPECTED TYPE: StreamWrapper', None, None)
self.__document = document
self.__key_modified['document'] = 1
def get_document_info(self):
"""
The method to get the document_info
Returns:
PreviewDocumentInfo: An instance of PreviewDocumentInfo
"""
return self.__document_info
def set_document_info(self, document_info):
"""
The method to set the value to document_info
Parameters:
document_info (PreviewDocumentInfo) : An instance of PreviewDocumentInfo
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.preview_document_info import PreviewDocumentInfo
except Exception:
from .preview_document_info import PreviewDocumentInfo
if document_info is not None and not isinstance(document_info, PreviewDocumentInfo):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_info EXPECTED TYPE: PreviewDocumentInfo', None, None)
self.__document_info = document_info
self.__key_modified['document_info'] = 1
def get_permissions(self):
"""
The method to get the permissions
Returns:
dict: An instance of dict
"""
return self.__permissions
def set_permissions(self, permissions):
"""
The method to set the value to permissions
Parameters:
permissions (dict) : An instance of dict
"""
if permissions is not None and not isinstance(permissions, dict):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: permissions EXPECTED TYPE: dict', None, None)
self.__permissions = permissions
self.__key_modified['permissions'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/preview_parameters.py | preview_parameters.py |
from .editor_settings import EditorSettings
from .show_response_handler import ShowResponseHandler
from .document_session_delete_success_response import DocumentSessionDeleteSuccessResponse
from .presentation_preview_parameters import PresentationPreviewParameters
from .watermark_parameters import WatermarkParameters
from .fillable_callback_settings import FillableCallbackSettings
from .document_delete_success_response import DocumentDeleteSuccessResponse
from .create_document_response import CreateDocumentResponse
from .user_info import UserInfo
from .sheet_preview_response import SheetPreviewResponse
from .compare_document_parameters import CompareDocumentParameters
from .session_meta import SessionMeta
from .fillable_submission_settings import FillableSubmissionSettings
from .file_delete_success_response import FileDeleteSuccessResponse
from .preview_response import PreviewResponse
from .writer_response_handler import WriterResponseHandler
from .fillable_link_parameters import FillableLinkParameters
from .merge_and_deliver_via_webhook_parameters import MergeAndDeliverViaWebhookParameters
from .fillable_link_response import FillableLinkResponse
from .mail_merge_webhook_settings import MailMergeWebhookSettings
from .get_merge_fields_parameters import GetMergeFieldsParameters
from .sheet_ui_options import SheetUiOptions
from .margin import Margin
from .session_info import SessionInfo
from .sheet_response_handler import SheetResponseHandler
from .merge_fields_response import MergeFieldsResponse
from .sheet_user_settings import SheetUserSettings
from .document_info import DocumentInfo
from .session_delete_success_response import SessionDeleteSuccessResponse
from .v1_operations import V1Operations
from .merge_and_deliver_via_webhook_success_response import MergeAndDeliverViaWebhookSuccessResponse
from .session_user_info import SessionUserInfo
from .create_presentation_parameters import CreatePresentationParameters
from .watermark_settings import WatermarkSettings
from .merge_and_deliver_records_meta import MergeAndDeliverRecordsMeta
from .invalid_configuration_exception import InvalidConfigurationException
from .sheet_callback_settings import SheetCallbackSettings
from .compare_document_response import CompareDocumentResponse
from .sheet_preview_parameters import SheetPreviewParameters
from .create_document_parameters import CreateDocumentParameters
from .fillable_form_options import FillableFormOptions
from .mail_merge_template_parameters import MailMergeTemplateParameters
from .zoho_show_editor_settings import ZohoShowEditorSettings
from .callback_settings import CallbackSettings
from .merge_fields import MergeFields
from .ui_options import UiOptions
from .sheet_conversion_parameters import SheetConversionParameters
from .show_callback_settings import ShowCallbackSettings
from .response_handler import ResponseHandler
from .file_body_wrapper import FileBodyWrapper
from .document_meta import DocumentMeta
from .convert_presentation_parameters import ConvertPresentationParameters
from .sheet_editor_settings import SheetEditorSettings
from .preview_parameters import PreviewParameters
from .document_conversion_output_options import DocumentConversionOutputOptions
from .merge_and_download_document_parameters import MergeAndDownloadDocumentParameters
from .create_sheet_parameters import CreateSheetParameters
from .fillable_link_output_settings import FillableLinkOutputSettings
from .preview_document_info import PreviewDocumentInfo
from .all_sessions_response import AllSessionsResponse
from .document_conversion_parameters import DocumentConversionParameters
from .plan_details import PlanDetails
from .sheet_conversion_output_options import SheetConversionOutputOptions
from .create_sheet_response import CreateSheetResponse
from .document_defaults import DocumentDefaults | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/__init__.py | __init__.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import StreamWrapper, Constants
except Exception:
from ...exception import SDKException
from ...util import StreamWrapper, Constants
class CreateSheetParameters(object):
def __init__(self):
"""Creates an instance of CreateSheetParameters"""
self.__url = None
self.__document = None
self.__callback_settings = None
self.__editor_settings = None
self.__permissions = None
self.__document_info = None
self.__user_info = None
self.__ui_options = None
self.__key_modified = dict()
def get_url(self):
"""
The method to get the url
Returns:
string: A string representing the url
"""
return self.__url
def set_url(self, url):
"""
The method to set the value to url
Parameters:
url (string) : A string representing the url
"""
if url is not None and not isinstance(url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: url EXPECTED TYPE: str', None, None)
self.__url = url
self.__key_modified['url'] = 1
def get_document(self):
"""
The method to get the document
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__document
def set_document(self, document):
"""
The method to set the value to document
Parameters:
document (StreamWrapper) : An instance of StreamWrapper
"""
if document is not None and not isinstance(document, StreamWrapper):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document EXPECTED TYPE: StreamWrapper', None, None)
self.__document = document
self.__key_modified['document'] = 1
def get_callback_settings(self):
"""
The method to get the callback_settings
Returns:
SheetCallbackSettings: An instance of SheetCallbackSettings
"""
return self.__callback_settings
def set_callback_settings(self, callback_settings):
"""
The method to set the value to callback_settings
Parameters:
callback_settings (SheetCallbackSettings) : An instance of SheetCallbackSettings
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_callback_settings import SheetCallbackSettings
except Exception:
from .sheet_callback_settings import SheetCallbackSettings
if callback_settings is not None and not isinstance(callback_settings, SheetCallbackSettings):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: callback_settings EXPECTED TYPE: SheetCallbackSettings', None, None)
self.__callback_settings = callback_settings
self.__key_modified['callback_settings'] = 1
def get_editor_settings(self):
"""
The method to get the editor_settings
Returns:
SheetEditorSettings: An instance of SheetEditorSettings
"""
return self.__editor_settings
def set_editor_settings(self, editor_settings):
"""
The method to set the value to editor_settings
Parameters:
editor_settings (SheetEditorSettings) : An instance of SheetEditorSettings
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_editor_settings import SheetEditorSettings
except Exception:
from .sheet_editor_settings import SheetEditorSettings
if editor_settings is not None and not isinstance(editor_settings, SheetEditorSettings):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: editor_settings EXPECTED TYPE: SheetEditorSettings', None, None)
self.__editor_settings = editor_settings
self.__key_modified['editor_settings'] = 1
def get_permissions(self):
"""
The method to get the permissions
Returns:
dict: An instance of dict
"""
return self.__permissions
def set_permissions(self, permissions):
"""
The method to set the value to permissions
Parameters:
permissions (dict) : An instance of dict
"""
if permissions is not None and not isinstance(permissions, dict):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: permissions EXPECTED TYPE: dict', None, None)
self.__permissions = permissions
self.__key_modified['permissions'] = 1
def get_document_info(self):
"""
The method to get the document_info
Returns:
DocumentInfo: An instance of DocumentInfo
"""
return self.__document_info
def set_document_info(self, document_info):
"""
The method to set the value to document_info
Parameters:
document_info (DocumentInfo) : An instance of DocumentInfo
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.document_info import DocumentInfo
except Exception:
from .document_info import DocumentInfo
if document_info is not None and not isinstance(document_info, DocumentInfo):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_info EXPECTED TYPE: DocumentInfo', None, None)
self.__document_info = document_info
self.__key_modified['document_info'] = 1
def get_user_info(self):
"""
The method to get the user_info
Returns:
SheetUserSettings: An instance of SheetUserSettings
"""
return self.__user_info
def set_user_info(self, user_info):
"""
The method to set the value to user_info
Parameters:
user_info (SheetUserSettings) : An instance of SheetUserSettings
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_user_settings import SheetUserSettings
except Exception:
from .sheet_user_settings import SheetUserSettings
if user_info is not None and not isinstance(user_info, SheetUserSettings):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: user_info EXPECTED TYPE: SheetUserSettings', None, None)
self.__user_info = user_info
self.__key_modified['user_info'] = 1
def get_ui_options(self):
"""
The method to get the ui_options
Returns:
SheetUiOptions: An instance of SheetUiOptions
"""
return self.__ui_options
def set_ui_options(self, ui_options):
"""
The method to set the value to ui_options
Parameters:
ui_options (SheetUiOptions) : An instance of SheetUiOptions
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_ui_options import SheetUiOptions
except Exception:
from .sheet_ui_options import SheetUiOptions
if ui_options is not None and not isinstance(ui_options, SheetUiOptions):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: ui_options EXPECTED TYPE: SheetUiOptions', None, None)
self.__ui_options = ui_options
self.__key_modified['ui_options'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/create_sheet_parameters.py | create_sheet_parameters.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import StreamWrapper, Constants
except Exception:
from ...exception import SDKException
from ...util import StreamWrapper, Constants
class DocumentConversionParameters(object):
def __init__(self):
"""Creates an instance of DocumentConversionParameters"""
self.__document = None
self.__url = None
self.__password = None
self.__output_options = None
self.__key_modified = dict()
def get_document(self):
"""
The method to get the document
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__document
def set_document(self, document):
"""
The method to set the value to document
Parameters:
document (StreamWrapper) : An instance of StreamWrapper
"""
if document is not None and not isinstance(document, StreamWrapper):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document EXPECTED TYPE: StreamWrapper', None, None)
self.__document = document
self.__key_modified['document'] = 1
def get_url(self):
"""
The method to get the url
Returns:
string: A string representing the url
"""
return self.__url
def set_url(self, url):
"""
The method to set the value to url
Parameters:
url (string) : A string representing the url
"""
if url is not None and not isinstance(url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: url EXPECTED TYPE: str', None, None)
self.__url = url
self.__key_modified['url'] = 1
def get_password(self):
"""
The method to get the password
Returns:
string: A string representing the password
"""
return self.__password
def set_password(self, password):
"""
The method to set the value to password
Parameters:
password (string) : A string representing the password
"""
if password is not None and not isinstance(password, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: password EXPECTED TYPE: str', None, None)
self.__password = password
self.__key_modified['password'] = 1
def get_output_options(self):
"""
The method to get the output_options
Returns:
DocumentConversionOutputOptions: An instance of DocumentConversionOutputOptions
"""
return self.__output_options
def set_output_options(self, output_options):
"""
The method to set the value to output_options
Parameters:
output_options (DocumentConversionOutputOptions) : An instance of DocumentConversionOutputOptions
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.document_conversion_output_options import DocumentConversionOutputOptions
except Exception:
from .document_conversion_output_options import DocumentConversionOutputOptions
if output_options is not None and not isinstance(output_options, DocumentConversionOutputOptions):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: output_options EXPECTED TYPE: DocumentConversionOutputOptions', None, None)
self.__output_options = output_options
self.__key_modified['output_options'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/document_conversion_parameters.py | document_conversion_parameters.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
from zohosdk.src.com.zoho.officeintegrator.v1.response_handler import ResponseHandler
from zohosdk.src.com.zoho.officeintegrator.v1.show_response_handler import ShowResponseHandler
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_response_handler import SheetResponseHandler
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from ...exception import SDKException
from ...util import Constants
from .response_handler import ResponseHandler
from .show_response_handler import ShowResponseHandler
from .sheet_response_handler import SheetResponseHandler
from .writer_response_handler import WriterResponseHandler
class InvalidConfigurationException(WriterResponseHandler, SheetResponseHandler, ShowResponseHandler, ResponseHandler):
def __init__(self):
"""Creates an instance of InvalidConfigurationException"""
super().__init__()
self.__key_name = None
self.__code = None
self.__parameter_name = None
self.__message = None
self.__key_modified = dict()
def get_key_name(self):
"""
The method to get the key_name
Returns:
string: A string representing the key_name
"""
return self.__key_name
def set_key_name(self, key_name):
"""
The method to set the value to key_name
Parameters:
key_name (string) : A string representing the key_name
"""
if key_name is not None and not isinstance(key_name, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key_name EXPECTED TYPE: str', None, None)
self.__key_name = key_name
self.__key_modified['key_name'] = 1
def get_code(self):
"""
The method to get the code
Returns:
int: An int representing the code
"""
return self.__code
def set_code(self, code):
"""
The method to set the value to code
Parameters:
code (int) : An int representing the code
"""
if code is not None and not isinstance(code, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: code EXPECTED TYPE: int', None, None)
self.__code = code
self.__key_modified['code'] = 1
def get_parameter_name(self):
"""
The method to get the parameter_name
Returns:
string: A string representing the parameter_name
"""
return self.__parameter_name
def set_parameter_name(self, parameter_name):
"""
The method to set the value to parameter_name
Parameters:
parameter_name (string) : A string representing the parameter_name
"""
if parameter_name is not None and not isinstance(parameter_name, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: parameter_name EXPECTED TYPE: str', None, None)
self.__parameter_name = parameter_name
self.__key_modified['parameter_name'] = 1
def get_message(self):
"""
The method to get the message
Returns:
string: A string representing the message
"""
return self.__message
def set_message(self, message):
"""
The method to set the value to message
Parameters:
message (string) : A string representing the message
"""
if message is not None and not isinstance(message, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: message EXPECTED TYPE: str', None, None)
self.__message = message
self.__key_modified['message'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/invalid_configuration_exception.py | invalid_configuration_exception.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import APIResponse, CommonAPIHandler, Constants
except Exception:
from ...exception import SDKException
from ...util import APIResponse, CommonAPIHandler, Constants
class V1Operations(object):
def __init__(self):
"""Creates an instance of V1Operations"""
pass
def create_document(self, request):
"""
The method to create document
Parameters:
request (CreateDocumentParameters) : An instance of CreateDocumentParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.create_document_parameters import CreateDocumentParameters
except Exception:
from .create_document_parameters import CreateDocumentParameters
if request is not None and not isinstance(request, CreateDocumentParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: CreateDocumentParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/documents'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def create_document_preview(self, request):
"""
The method to create document preview
Parameters:
request (PreviewParameters) : An instance of PreviewParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.preview_parameters import PreviewParameters
except Exception:
from .preview_parameters import PreviewParameters
if request is not None and not isinstance(request, PreviewParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: PreviewParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/document/preview'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def create_watermark_document(self, request):
"""
The method to create watermark document
Parameters:
request (WatermarkParameters) : An instance of WatermarkParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.watermark_parameters import WatermarkParameters
except Exception:
from .watermark_parameters import WatermarkParameters
if request is not None and not isinstance(request, WatermarkParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: WatermarkParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/document/watermark'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def create_mail_merge_template(self, request):
"""
The method to create mail merge template
Parameters:
request (MailMergeTemplateParameters) : An instance of MailMergeTemplateParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.mail_merge_template_parameters import MailMergeTemplateParameters
except Exception:
from .mail_merge_template_parameters import MailMergeTemplateParameters
if request is not None and not isinstance(request, MailMergeTemplateParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: MailMergeTemplateParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/templates'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def get_merge_fields(self, request):
"""
The method to get merge fields
Parameters:
request (GetMergeFieldsParameters) : An instance of GetMergeFieldsParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.get_merge_fields_parameters import GetMergeFieldsParameters
except Exception:
from .get_merge_fields_parameters import GetMergeFieldsParameters
if request is not None and not isinstance(request, GetMergeFieldsParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: GetMergeFieldsParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/fields'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def merge_and_deliver_via_webhook(self, request):
"""
The method to merge and deliver via webhook
Parameters:
request (MergeAndDeliverViaWebhookParameters) : An instance of MergeAndDeliverViaWebhookParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.merge_and_deliver_via_webhook_parameters import MergeAndDeliverViaWebhookParameters
except Exception:
from .merge_and_deliver_via_webhook_parameters import MergeAndDeliverViaWebhookParameters
if request is not None and not isinstance(request, MergeAndDeliverViaWebhookParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: MergeAndDeliverViaWebhookParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/document/merge/webhook'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def merge_and_download_document(self, request):
"""
The method to merge and download document
Parameters:
request (MergeAndDownloadDocumentParameters) : An instance of MergeAndDownloadDocumentParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.merge_and_download_document_parameters import MergeAndDownloadDocumentParameters
except Exception:
from .merge_and_download_document_parameters import MergeAndDownloadDocumentParameters
if request is not None and not isinstance(request, MergeAndDownloadDocumentParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: MergeAndDownloadDocumentParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/document/merge'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def create_fillable_template_document(self, request):
"""
The method to create fillable template document
Parameters:
request (CreateDocumentParameters) : An instance of CreateDocumentParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.create_document_parameters import CreateDocumentParameters
except Exception:
from .create_document_parameters import CreateDocumentParameters
if request is not None and not isinstance(request, CreateDocumentParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: CreateDocumentParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/fillabletemplates'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def create_fillable_link(self, request):
"""
The method to create fillable link
Parameters:
request (FillableLinkParameters) : An instance of FillableLinkParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.fillable_link_parameters import FillableLinkParameters
except Exception:
from .fillable_link_parameters import FillableLinkParameters
if request is not None and not isinstance(request, FillableLinkParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: FillableLinkParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/fillabletemplates/fillablelink'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def convert_document(self, request):
"""
The method to convert document
Parameters:
request (DocumentConversionParameters) : An instance of DocumentConversionParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.document_conversion_parameters import DocumentConversionParameters
except Exception:
from .document_conversion_parameters import DocumentConversionParameters
if request is not None and not isinstance(request, DocumentConversionParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: DocumentConversionParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/document/convert'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def compare_document(self, request):
"""
The method to compare document
Parameters:
request (CompareDocumentParameters) : An instance of CompareDocumentParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.compare_document_parameters import CompareDocumentParameters
except Exception:
from .compare_document_parameters import CompareDocumentParameters
if request is not None and not isinstance(request, CompareDocumentParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: CompareDocumentParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/document/compare'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def get_all_sessions(self, documentid):
"""
The method to get all sessions
Parameters:
documentid (string) : A string representing the documentid
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
if not isinstance(documentid, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: documentid EXPECTED TYPE: str', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/documents/'
api_path = api_path + str(documentid)
api_path = api_path + '/sessions'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_GET)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def get_session(self, sessionid):
"""
The method to get session
Parameters:
sessionid (string) : A string representing the sessionid
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
if not isinstance(sessionid, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: sessionid EXPECTED TYPE: str', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/sessions/'
api_path = api_path + str(sessionid)
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_GET)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def delete_session(self, sessionid):
"""
The method to delete session
Parameters:
sessionid (string) : A string representing the sessionid
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
if not isinstance(sessionid, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: sessionid EXPECTED TYPE: str', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/sessions/'
api_path = api_path + str(sessionid)
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_DELETE)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def get_document_info(self, documentid):
"""
The method to get document info
Parameters:
documentid (string) : A string representing the documentid
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
if not isinstance(documentid, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: documentid EXPECTED TYPE: str', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/documents/'
api_path = api_path + str(documentid)
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_GET)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def delete_document(self, documentid):
"""
The method to delete document
Parameters:
documentid (string) : A string representing the documentid
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
if not isinstance(documentid, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: documentid EXPECTED TYPE: str', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/writer/officeapi/v1/documents/'
api_path = api_path + str(documentid)
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_DELETE)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from .writer_response_handler import WriterResponseHandler
return handler_instance.api_call(WriterResponseHandler.__module__, 'application/json')
def create_sheet(self, request):
"""
The method to create sheet
Parameters:
request (CreateSheetParameters) : An instance of CreateSheetParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.create_sheet_parameters import CreateSheetParameters
except Exception:
from .create_sheet_parameters import CreateSheetParameters
if request is not None and not isinstance(request, CreateSheetParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: CreateSheetParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/sheet/officeapi/v1/spreadsheet'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_response_handler import SheetResponseHandler
except Exception:
from .sheet_response_handler import SheetResponseHandler
return handler_instance.api_call(SheetResponseHandler.__module__, 'application/json')
def create_sheet_preview(self, request):
"""
The method to create sheet preview
Parameters:
request (SheetPreviewParameters) : An instance of SheetPreviewParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_preview_parameters import SheetPreviewParameters
except Exception:
from .sheet_preview_parameters import SheetPreviewParameters
if request is not None and not isinstance(request, SheetPreviewParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: SheetPreviewParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/sheet/officeapi/v1/spreadsheet/preview'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_response_handler import SheetResponseHandler
except Exception:
from .sheet_response_handler import SheetResponseHandler
return handler_instance.api_call(SheetResponseHandler.__module__, 'application/json')
def convert_sheet(self, request):
"""
The method to convert sheet
Parameters:
request (SheetConversionParameters) : An instance of SheetConversionParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_conversion_parameters import SheetConversionParameters
except Exception:
from .sheet_conversion_parameters import SheetConversionParameters
if request is not None and not isinstance(request, SheetConversionParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: SheetConversionParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/sheet/officeapi/v1/spreadsheet/convert'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_response_handler import SheetResponseHandler
except Exception:
from .sheet_response_handler import SheetResponseHandler
return handler_instance.api_call(SheetResponseHandler.__module__, 'application/json')
def get_sheet_session(self, sessionid):
"""
The method to get sheet session
Parameters:
sessionid (string) : A string representing the sessionid
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
if not isinstance(sessionid, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: sessionid EXPECTED TYPE: str', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/sheet/officeapi/v1/sessions/'
api_path = api_path + str(sessionid)
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_GET)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_response_handler import SheetResponseHandler
except Exception:
from .sheet_response_handler import SheetResponseHandler
return handler_instance.api_call(SheetResponseHandler.__module__, 'application/json')
def delete_sheet_session(self, sessionid):
"""
The method to delete sheet session
Parameters:
sessionid (string) : A string representing the sessionid
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
if not isinstance(sessionid, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: sessionid EXPECTED TYPE: str', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/sheet/officeapi/v1/session/'
api_path = api_path + str(sessionid)
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_DELETE)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_response_handler import SheetResponseHandler
except Exception:
from .sheet_response_handler import SheetResponseHandler
return handler_instance.api_call(SheetResponseHandler.__module__, 'application/json')
def delete_sheet(self, documentid):
"""
The method to delete sheet
Parameters:
documentid (string) : A string representing the documentid
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
if not isinstance(documentid, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: documentid EXPECTED TYPE: str', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/sheet/officeapi/v1/spreadsheet/'
api_path = api_path + str(documentid)
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_DELETE)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.sheet_response_handler import SheetResponseHandler
except Exception:
from .sheet_response_handler import SheetResponseHandler
return handler_instance.api_call(SheetResponseHandler.__module__, 'application/json')
def create_presentation(self, request):
"""
The method to create presentation
Parameters:
request (CreatePresentationParameters) : An instance of CreatePresentationParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.create_presentation_parameters import CreatePresentationParameters
except Exception:
from .create_presentation_parameters import CreatePresentationParameters
if request is not None and not isinstance(request, CreatePresentationParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: CreatePresentationParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/show/officeapi/v1/presentation'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.show_response_handler import ShowResponseHandler
except Exception:
from .show_response_handler import ShowResponseHandler
return handler_instance.api_call(ShowResponseHandler.__module__, 'application/json')
def convert_presentation(self, request):
"""
The method to convert presentation
Parameters:
request (ConvertPresentationParameters) : An instance of ConvertPresentationParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.convert_presentation_parameters import ConvertPresentationParameters
except Exception:
from .convert_presentation_parameters import ConvertPresentationParameters
if request is not None and not isinstance(request, ConvertPresentationParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: ConvertPresentationParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/show/officeapi/v1/presentation/convert'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.show_response_handler import ShowResponseHandler
except Exception:
from .show_response_handler import ShowResponseHandler
return handler_instance.api_call(ShowResponseHandler.__module__, 'application/json')
def create_presentation_preview(self, request):
"""
The method to create presentation preview
Parameters:
request (PresentationPreviewParameters) : An instance of PresentationPreviewParameters
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.presentation_preview_parameters import PresentationPreviewParameters
except Exception:
from .presentation_preview_parameters import PresentationPreviewParameters
if request is not None and not isinstance(request, PresentationPreviewParameters):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: request EXPECTED TYPE: PresentationPreviewParameters', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/show/officeapi/v1/presentation/preview'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_POST)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
handler_instance.set_content_type('multipart/form-data')
handler_instance.set_request(request)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.show_response_handler import ShowResponseHandler
except Exception:
from .show_response_handler import ShowResponseHandler
return handler_instance.api_call(ShowResponseHandler.__module__, 'application/json')
def get_presentation_session(self, sessionid):
"""
The method to get presentation session
Parameters:
sessionid (string) : A string representing the sessionid
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
if not isinstance(sessionid, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: sessionid EXPECTED TYPE: str', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/show/officeapi/v1/sessions/'
api_path = api_path + str(sessionid)
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_GET)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.show_response_handler import ShowResponseHandler
except Exception:
from .show_response_handler import ShowResponseHandler
return handler_instance.api_call(ShowResponseHandler.__module__, 'application/json')
def delete_presentation_session(self, sessionid):
"""
The method to delete presentation session
Parameters:
sessionid (string) : A string representing the sessionid
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
if not isinstance(sessionid, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: sessionid EXPECTED TYPE: str', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/show/officeapi/v1/session/'
api_path = api_path + str(sessionid)
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_DELETE)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.show_response_handler import ShowResponseHandler
except Exception:
from .show_response_handler import ShowResponseHandler
return handler_instance.api_call(ShowResponseHandler.__module__, 'application/json')
def delete_presentation(self, documentid):
"""
The method to delete presentation
Parameters:
documentid (string) : A string representing the documentid
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
if not isinstance(documentid, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: documentid EXPECTED TYPE: str', None, None)
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/show/officeapi/v1/presentation/'
api_path = api_path + str(documentid)
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_DELETE)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.show_response_handler import ShowResponseHandler
except Exception:
from .show_response_handler import ShowResponseHandler
return handler_instance.api_call(ShowResponseHandler.__module__, 'application/json')
def get_plan_details(self):
"""
The method to get plan details
Returns:
APIResponse: An instance of APIResponse
Raises:
SDKException
"""
handler_instance = CommonAPIHandler()
api_path = ''
api_path = api_path + '/api/v1/plan'
handler_instance.set_api_path(api_path)
handler_instance.set_http_method(Constants.REQUEST_METHOD_GET)
handler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)
try:
from zohosdk.src.com.zoho.officeintegrator.v1.response_handler import ResponseHandler
except Exception:
from .response_handler import ResponseHandler
return handler_instance.api_call(ResponseHandler.__module__, 'application/json') | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/v1_operations.py | v1_operations.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
from zohosdk.src.com.zoho.officeintegrator.v1.writer_response_handler import WriterResponseHandler
except Exception:
from ...exception import SDKException
from ...util import Constants
from .writer_response_handler import WriterResponseHandler
class DocumentMeta(WriterResponseHandler):
def __init__(self):
"""Creates an instance of DocumentMeta"""
super().__init__()
self.__document_id = None
self.__collaborators_count = None
self.__active_sessions_count = None
self.__document_name = None
self.__document_type = None
self.__created_time = None
self.__created_time_ms = None
self.__expires_on = None
self.__expires_on_ms = None
self.__key_modified = dict()
def get_document_id(self):
"""
The method to get the document_id
Returns:
string: A string representing the document_id
"""
return self.__document_id
def set_document_id(self, document_id):
"""
The method to set the value to document_id
Parameters:
document_id (string) : A string representing the document_id
"""
if document_id is not None and not isinstance(document_id, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_id EXPECTED TYPE: str', None, None)
self.__document_id = document_id
self.__key_modified['document_id'] = 1
def get_collaborators_count(self):
"""
The method to get the collaborators_count
Returns:
int: An int representing the collaborators_count
"""
return self.__collaborators_count
def set_collaborators_count(self, collaborators_count):
"""
The method to set the value to collaborators_count
Parameters:
collaborators_count (int) : An int representing the collaborators_count
"""
if collaborators_count is not None and not isinstance(collaborators_count, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: collaborators_count EXPECTED TYPE: int', None, None)
self.__collaborators_count = collaborators_count
self.__key_modified['collaborators_count'] = 1
def get_active_sessions_count(self):
"""
The method to get the active_sessions_count
Returns:
int: An int representing the active_sessions_count
"""
return self.__active_sessions_count
def set_active_sessions_count(self, active_sessions_count):
"""
The method to set the value to active_sessions_count
Parameters:
active_sessions_count (int) : An int representing the active_sessions_count
"""
if active_sessions_count is not None and not isinstance(active_sessions_count, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: active_sessions_count EXPECTED TYPE: int', None, None)
self.__active_sessions_count = active_sessions_count
self.__key_modified['active_sessions_count'] = 1
def get_document_name(self):
"""
The method to get the document_name
Returns:
string: A string representing the document_name
"""
return self.__document_name
def set_document_name(self, document_name):
"""
The method to set the value to document_name
Parameters:
document_name (string) : A string representing the document_name
"""
if document_name is not None and not isinstance(document_name, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_name EXPECTED TYPE: str', None, None)
self.__document_name = document_name
self.__key_modified['document_name'] = 1
def get_document_type(self):
"""
The method to get the document_type
Returns:
string: A string representing the document_type
"""
return self.__document_type
def set_document_type(self, document_type):
"""
The method to set the value to document_type
Parameters:
document_type (string) : A string representing the document_type
"""
if document_type is not None and not isinstance(document_type, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: document_type EXPECTED TYPE: str', None, None)
self.__document_type = document_type
self.__key_modified['document_type'] = 1
def get_created_time(self):
"""
The method to get the created_time
Returns:
string: A string representing the created_time
"""
return self.__created_time
def set_created_time(self, created_time):
"""
The method to set the value to created_time
Parameters:
created_time (string) : A string representing the created_time
"""
if created_time is not None and not isinstance(created_time, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: created_time EXPECTED TYPE: str', None, None)
self.__created_time = created_time
self.__key_modified['created_time'] = 1
def get_created_time_ms(self):
"""
The method to get the created_time_ms
Returns:
int: An int representing the created_time_ms
"""
return self.__created_time_ms
def set_created_time_ms(self, created_time_ms):
"""
The method to set the value to created_time_ms
Parameters:
created_time_ms (int) : An int representing the created_time_ms
"""
if created_time_ms is not None and not isinstance(created_time_ms, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: created_time_ms EXPECTED TYPE: int', None, None)
self.__created_time_ms = created_time_ms
self.__key_modified['created_time_ms'] = 1
def get_expires_on(self):
"""
The method to get the expires_on
Returns:
string: A string representing the expires_on
"""
return self.__expires_on
def set_expires_on(self, expires_on):
"""
The method to set the value to expires_on
Parameters:
expires_on (string) : A string representing the expires_on
"""
if expires_on is not None and not isinstance(expires_on, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: expires_on EXPECTED TYPE: str', None, None)
self.__expires_on = expires_on
self.__key_modified['expires_on'] = 1
def get_expires_on_ms(self):
"""
The method to get the expires_on_ms
Returns:
int: An int representing the expires_on_ms
"""
return self.__expires_on_ms
def set_expires_on_ms(self, expires_on_ms):
"""
The method to set the value to expires_on_ms
Parameters:
expires_on_ms (int) : An int representing the expires_on_ms
"""
if expires_on_ms is not None and not isinstance(expires_on_ms, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: expires_on_ms EXPECTED TYPE: int', None, None)
self.__expires_on_ms = expires_on_ms
self.__key_modified['expires_on_ms'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/document_meta.py | document_meta.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class DocumentDefaults(object):
def __init__(self):
"""Creates an instance of DocumentDefaults"""
self.__orientation = None
self.__paper_size = None
self.__font_name = None
self.__font_size = None
self.__track_changes = None
self.__language = None
self.__margin = None
self.__key_modified = dict()
def get_orientation(self):
"""
The method to get the orientation
Returns:
string: A string representing the orientation
"""
return self.__orientation
def set_orientation(self, orientation):
"""
The method to set the value to orientation
Parameters:
orientation (string) : A string representing the orientation
"""
if orientation is not None and not isinstance(orientation, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: orientation EXPECTED TYPE: str', None, None)
self.__orientation = orientation
self.__key_modified['orientation'] = 1
def get_paper_size(self):
"""
The method to get the paper_size
Returns:
string: A string representing the paper_size
"""
return self.__paper_size
def set_paper_size(self, paper_size):
"""
The method to set the value to paper_size
Parameters:
paper_size (string) : A string representing the paper_size
"""
if paper_size is not None and not isinstance(paper_size, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: paper_size EXPECTED TYPE: str', None, None)
self.__paper_size = paper_size
self.__key_modified['paper_size'] = 1
def get_font_name(self):
"""
The method to get the font_name
Returns:
string: A string representing the font_name
"""
return self.__font_name
def set_font_name(self, font_name):
"""
The method to set the value to font_name
Parameters:
font_name (string) : A string representing the font_name
"""
if font_name is not None and not isinstance(font_name, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: font_name EXPECTED TYPE: str', None, None)
self.__font_name = font_name
self.__key_modified['font_name'] = 1
def get_font_size(self):
"""
The method to get the font_size
Returns:
int: An int representing the font_size
"""
return self.__font_size
def set_font_size(self, font_size):
"""
The method to set the value to font_size
Parameters:
font_size (int) : An int representing the font_size
"""
if font_size is not None and not isinstance(font_size, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: font_size EXPECTED TYPE: int', None, None)
self.__font_size = font_size
self.__key_modified['font_size'] = 1
def get_track_changes(self):
"""
The method to get the track_changes
Returns:
string: A string representing the track_changes
"""
return self.__track_changes
def set_track_changes(self, track_changes):
"""
The method to set the value to track_changes
Parameters:
track_changes (string) : A string representing the track_changes
"""
if track_changes is not None and not isinstance(track_changes, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: track_changes EXPECTED TYPE: str', None, None)
self.__track_changes = track_changes
self.__key_modified['track_changes'] = 1
def get_language(self):
"""
The method to get the language
Returns:
string: A string representing the language
"""
return self.__language
def set_language(self, language):
"""
The method to set the value to language
Parameters:
language (string) : A string representing the language
"""
if language is not None and not isinstance(language, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: language EXPECTED TYPE: str', None, None)
self.__language = language
self.__key_modified['language'] = 1
def get_margin(self):
"""
The method to get the margin
Returns:
Margin: An instance of Margin
"""
return self.__margin
def set_margin(self, margin):
"""
The method to set the value to margin
Parameters:
margin (Margin) : An instance of Margin
"""
try:
from zohosdk.src.com.zoho.officeintegrator.v1.margin import Margin
except Exception:
from .margin import Margin
if margin is not None and not isinstance(margin, Margin):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: margin EXPECTED TYPE: Margin', None, None)
self.__margin = margin
self.__key_modified['margin'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/document_defaults.py | document_defaults.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class SheetUiOptions(object):
def __init__(self):
"""Creates an instance of SheetUiOptions"""
self.__save_button = None
self.__key_modified = dict()
def get_save_button(self):
"""
The method to get the save_button
Returns:
string: A string representing the save_button
"""
return self.__save_button
def set_save_button(self, save_button):
"""
The method to set the value to save_button
Parameters:
save_button (string) : A string representing the save_button
"""
if save_button is not None and not isinstance(save_button, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: save_button EXPECTED TYPE: str', None, None)
self.__save_button = save_button
self.__key_modified['save_button'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/sheet_ui_options.py | sheet_ui_options.py |
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util import Constants
except Exception:
from ...exception import SDKException
from ...util import Constants
class MailMergeWebhookSettings(object):
def __init__(self):
"""Creates an instance of MailMergeWebhookSettings"""
self.__invoke_url = None
self.__invoke_period = None
self.__key_modified = dict()
def get_invoke_url(self):
"""
The method to get the invoke_url
Returns:
string: A string representing the invoke_url
"""
return self.__invoke_url
def set_invoke_url(self, invoke_url):
"""
The method to set the value to invoke_url
Parameters:
invoke_url (string) : A string representing the invoke_url
"""
if invoke_url is not None and not isinstance(invoke_url, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: invoke_url EXPECTED TYPE: str', None, None)
self.__invoke_url = invoke_url
self.__key_modified['invoke_url'] = 1
def get_invoke_period(self):
"""
The method to get the invoke_period
Returns:
string: A string representing the invoke_period
"""
return self.__invoke_period
def set_invoke_period(self, invoke_period):
"""
The method to set the value to invoke_period
Parameters:
invoke_period (string) : A string representing the invoke_period
"""
if invoke_period is not None and not isinstance(invoke_period, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: invoke_period EXPECTED TYPE: str', None, None)
self.__invoke_period = invoke_period
self.__key_modified['invoke_period'] = 1
def is_key_modified(self, key):
"""
The method to check if the user has modified the given key
Parameters:
key (string) : A string representing the key
Returns:
int: An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if key in self.__key_modified:
return self.__key_modified.get(key)
return None
def set_key_modified(self, key, modification):
"""
The method to mark the given key as modified
Parameters:
key (string) : A string representing the key
modification (int) : An int representing the modification
"""
if key is not None and not isinstance(key, str):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)
if modification is not None and not isinstance(modification, int):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)
self.__key_modified[key] = modification | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/officeintegrator/v1/mail_merge_webhook_settings.py | mail_merge_webhook_settings.py |
try:
import threading
import logging
import enum
import json
import time
import requests
from .token import Token
from zohosdk.src.com.zoho.exception import SDKException
from ...util.constants import Constants
except Exception as e:
import threading
import logging
import enum
import json
import time
import requests
from .token import Token
from zohosdk.src.com.zoho.exception import SDKException
from ...util.constants import Constants
class OAuthToken(Token):
"""
This class maintains the tokens and authenticates every request.
"""
logger = logging.getLogger('SDKLogger')
lock = threading.Lock()
def __init__(self, client_id=None, client_secret=None, grant_token=None, refresh_token=None, redirect_url=None, id=None, access_token=None):
"""
Creates an OAuthToken class instance with the specified parameters.
Parameters:
client_id (str) : A string containing the OAuth client id.
client_secret (str) : A string containing the OAuth client secret.
grant_token (str) : A string containing the GRANT token.
refresh_token (str) : A string containing the REFRESH token.
redirect_url (str) : A string containing the OAuth redirect URL. Default value is None
id (str) : A string containing the Id. Default value is None
"""
error = {}
if grant_token is None and refresh_token is None and id is None and access_token is None:
raise SDKException(code=Constants.MANDATORY_VALUE_ERROR, message=Constants.MANDATORY_KEY_ERROR, details=Constants.OAUTH_MANDATORY_KEYS)
if id is None and access_token is None:
if not isinstance(client_id, str):
error[Constants.FIELD] = Constants.CLIENT_ID
error[Constants.EXPECTED_TYPE] = Constants.STRING
error[Constants.CLASS] = OAuthToken.__name__
raise SDKException(code=Constants.TOKEN_ERROR, details=error)
if not isinstance(client_secret, str):
error[Constants.FIELD] = Constants.CLIENT_SECRET
error[Constants.EXPECTED_TYPE] = Constants.STRING
error[Constants.CLASS] = OAuthToken.__name__
raise SDKException(code=Constants.TOKEN_ERROR, details=error)
if grant_token is not None and not isinstance(grant_token, str):
error[Constants.FIELD] = Constants.GRANT_TOKEN
error[Constants.EXPECTED_TYPE] = Constants.STRING
error[Constants.CLASS] = OAuthToken.__name__
raise SDKException(code=Constants.TOKEN_ERROR, details=error)
if refresh_token is not None and not isinstance(refresh_token, str):
error[Constants.FIELD] = Constants.REFRESH_TOKEN
error[Constants.EXPECTED_TYPE] = Constants.STRING
error[Constants.CLASS] = OAuthToken.__name__
raise SDKException(code=Constants.TOKEN_ERROR, details=error)
if redirect_url is not None and not isinstance(redirect_url, str):
error[Constants.FIELD] = Constants.REDIRECT_URI
error[Constants.EXPECTED_TYPE] = Constants.STRING
error[Constants.CLASS] = OAuthToken.__name__
raise SDKException(code=Constants.TOKEN_ERROR, details=error)
if id is not None and not isinstance(id, str):
error[Constants.FIELD] = Constants.ID
error[Constants.EXPECTED_TYPE] = Constants.STRING
error[Constants.CLASS] = OAuthToken.__name__
raise SDKException(code=Constants.TOKEN_ERROR, details=error)
if access_token is not None and not isinstance(access_token, str):
error[Constants.FIELD] = Constants.ACCESS_TOKEN
error[Constants.EXPECTED_TYPE] = Constants.STRING
error[Constants.CLASS] = OAuthToken.__name__
raise SDKException(code=Constants.TOKEN_ERROR, details=error)
self.__client_id = client_id
self.__client_secret = client_secret
self.__redirect_url = redirect_url
self.__grant_token = grant_token
self.__refresh_token = refresh_token
self.__id = id
self.__access_token = access_token
self.__expires_in = None
self.__user_mail = None
def get_client_id(self):
"""
This is a getter method to get __client_id.
Returns:
string: A string representing __client_id
"""
return self.__client_id
def get_client_secret(self):
"""
This is a getter method to get __client_secret.
Returns:
string: A string representing __client_secret
"""
return self.__client_secret
def get_redirect_url(self):
"""
This is a getter method to get __redirect_url.
Returns:
string: A string representing __redirect_url
"""
return self.__redirect_url
def get_grant_token(self):
"""
This is a getter method to get __grant_token.
Returns:
string: A string representing __grant_token
"""
return self.__grant_token
def get_refresh_token(self):
"""
This is a getter method to get __refresh_token.
Returns:
string: A string representing __refresh_token
"""
return self.__refresh_token
def get_access_token(self):
"""
This is a getter method to get __access_token.
Returns:
string: A string representing __access_token
"""
return self.__access_token
def get_id(self):
"""
This is a getter method to get __id.
Returns:
string: A string representing __id
"""
return self.__id
def get_expires_in(self):
"""
This is a getter method to get __expires_in.
Returns:
string: A string representing __expires_in
"""
return self.__expires_in
def get_user_mail(self):
"""
This is a getter method to get __user_mail.
Returns:
string: A string representing __user_mail
"""
return self.__user_mail
def set_grant_token(self, grant_token):
"""
This is a setter method to set __grant_token.
"""
self.__grant_token = grant_token
def set_refresh_token(self, refresh_token):
"""
This is a setter method to set __refresh_token.
"""
self.__refresh_token = refresh_token
def set_redirect_url(self, redirect_url):
"""
This is a setter method to set __redirect_url.
"""
self.__redirect_url = redirect_url
def set_access_token(self, access_token):
"""
This is a setter method to set __access_token.
"""
self.__access_token = access_token
def set_client_id(self, client_id):
"""
This is a setter method to set __client_id.
"""
self.__client_id = client_id
def set_client_secret(self, client_secret):
"""
This is a setter method to set __client_secret.
"""
self.__client_secret = client_secret
def set_id(self, id):
"""
This is a setter method to set __id.
"""
self.__id = id
def set_expires_in(self, expires_in):
"""
This is a setter method to set __expires_in.
"""
self.__expires_in = expires_in
def set_user_mail(self, user_mail):
"""
This is a setter method to set __user_mail.
"""
self.__user_mail = user_mail
def authenticate(self, url_connection):
with OAuthToken.lock:
try:
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from zohosdk.src.com.zoho.initializer import Initializer
initializer = Initializer.get_initializer()
store = initializer.store
user = initializer.user
if self.__access_token is None:
if self.__id is not None:
oauth_token = initializer.store.get_token_by_id(self.__id, self)
else:
oauth_token = initializer.store.get_token(user, self)
else:
oauth_token = self
if oauth_token is None:
token = self.generate_access_token(user, store).get_access_token() if (
self.__refresh_token is None) else self.refresh_access_token(user, store).get_access_token()
elif oauth_token.get_expires_in() is not None and int(oauth_token.get_expires_in()) - int(time.time() * 1000) < 5000:
OAuthToken.logger.info(Constants.REFRESH_TOKEN_MESSAGE)
token = oauth_token.refresh_access_token(user, store).get_access_token()
else:
token = oauth_token.get_access_token()
url_connection.add_header(Constants.AUTHORIZATION, Constants.OAUTH_HEADER_PREFIX + token)
def refresh_access_token(self, user, store):
try:
try:
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from zohosdk.src.com.zoho.initializer import Initializer
url = Initializer.get_initializer().environment.accounts_url
body = {
Constants.REFRESH_TOKEN: self.__refresh_token,
Constants.CLIENT_ID: self.__client_id,
Constants.CLIENT_SECRET: self.__client_secret,
Constants.GRANT_TYPE: Constants.REFRESH_TOKEN
}
response = requests.post(url, data=body, params=None, headers=None, allow_redirects=False).json()
self.parse_response(response)
if self.__id is None:
self.generate_id()
store.save_token(user, self)
except SDKException as ex:
raise ex
except Exception as ex:
raise SDKException(code=Constants.SAVE_TOKEN_ERROR, cause=ex)
return self
def generate_access_token(self, user, store):
try:
try:
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from zohosdk.src.com.zoho.initializer import Initializer
url = Initializer.get_initializer().environment.accounts_url
body = {
Constants.CLIENT_ID: self.__client_id,
Constants.CLIENT_SECRET: self.__client_secret,
Constants.REDIRECT_URI: self.__redirect_url if self.__redirect_url is not None else None,
Constants.GRANT_TYPE: Constants.GRANT_TYPE_AUTH_CODE,
Constants.CODE: self.__grant_token
}
headers = dict()
headers[Constants.USER_AGENT_KEY] = Constants.USER_AGENT
response = requests.post(url, data=body, params=None, headers=headers, allow_redirects=True).json()
self.parse_response(response)
self.generate_id()
store.save_token(user, self)
except SDKException as ex:
raise ex
except Exception as ex:
raise SDKException(code=Constants.SAVE_TOKEN_ERROR, cause=ex)
return self
def parse_response(self, response):
response_json = dict(response)
if Constants.ACCESS_TOKEN not in response_json:
raise SDKException(code=Constants.INVALID_TOKEN_ERROR, message=str(response_json.get(Constants.ERROR_KEY))if Constants.ERROR_KEY in response_json else Constants.NO_ACCESS_TOKEN_ERROR)
self.__access_token = response_json.get(Constants.ACCESS_TOKEN)
self.__expires_in = str(int(time.time() * 1000) + self.get_token_expires_in(response=response_json))
if Constants.REFRESH_TOKEN in response_json:
self.__refresh_token = response_json.get(Constants.REFRESH_TOKEN)
return self
@staticmethod
def get_token_expires_in(response):
return int(response[Constants.EXPIRES_IN]) if Constants.EXPIRES_IN_SEC in response else int(
response[Constants.EXPIRES_IN]) * 1000
def generate_id(self):
try:
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from zohosdk.src.com.zoho.initializer import Initializer
id = ""
email = str(Initializer.get_initializer().user.get_email())
environment = str(Initializer.get_initializer().environment.name)
id += Constants.PYTHON + email[0:email.find(Constants.AT)] + Constants.UNDERSCORE
id += environment + Constants.UNDERSCORE + self.__refresh_token[len(self.__refresh_token)-4:]
self.__id = id
return self.__id
def remove(self):
try:
try:
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from zohosdk.src.com.zoho.initializer import Initializer
Initializer.get_initializer().store.delete_token(self)
return True
except Exception:
return False | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/api/authenticator/oauth_token.py | oauth_token.py |
try:
import os
import csv
from zohosdk.src.com.zoho.api.authenticator.store.token_store import TokenStore
from zohosdk.src.com.zoho.api.authenticator.oauth_token import OAuthToken
from ....util.constants import Constants
from zohosdk.src.com.zoho.exception.sdk_exception import SDKException
except Exception as e:
import os
import csv
from .token_store import TokenStore
from ..oauth_token import OAuthToken
from ....util.constants import Constants
from zohosdk.src.com.zoho.exception.sdk_exception import SDKException
class FileStore(TokenStore):
"""
The class to store user token details to the file.
"""
def __init__(self, file_path):
"""
Creates an FileStore class instance with the specified parameters.
Parameters:
file_path (str) : A string containing the absolute file path of the file to store tokens
"""
self.file_path = file_path
self.headers = [Constants.ID, Constants.USER_MAIL, Constants.CLIENT_ID, Constants.CLIENT_SECRET, Constants.REFRESH_TOKEN, Constants.ACCESS_TOKEN, Constants.GRANT_TOKEN, Constants.EXPIRY_TIME, Constants.REDIRECT_URI]
if (os.path.exists(file_path) and os.stat(file_path).st_size == 0) or not os.path.exists(file_path):
with open(self.file_path, mode='w') as token_file:
csv_writer = csv.writer(token_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csv_writer.writerow(self.headers)
def get_token(self, user, token):
try:
if isinstance(token, OAuthToken):
with open(self.file_path, mode='r') as f:
data = csv.reader(f, delimiter=',')
next(data, None)
for next_record in data:
if len(next_record) == 0:
continue
if self.check_token_exists(user.get_email(), token, next_record):
grant_token = next_record[6] if next_record[6] is not None and len(
next_record[6]) > 0 else None
redirect_url = next_record[8] if next_record[8] is not None and len(
next_record[8]) > 0 else None
oauthtoken = token
oauthtoken.set_id(next_record[0])
oauthtoken.set_user_mail(next_record[1])
oauthtoken.set_client_id(next_record[2])
oauthtoken.set_client_secret(next_record[3])
oauthtoken.set_refresh_token(next_record[4])
oauthtoken.set_access_token(next_record[5])
oauthtoken.set_grant_token(grant_token)
oauthtoken.set_expires_in(next_record[7])
oauthtoken.set_redirect_url(redirect_url)
return oauthtoken
except IOError as ex:
raise SDKException(code=Constants.TOKEN_STORE, message=Constants.GET_TOKEN_FILE_ERROR, cause=ex)
return None
def save_token(self, user, token):
if isinstance(token, OAuthToken):
token.set_user_mail(user.get_email())
self.delete_token(token)
try:
with open(self.file_path, mode='a+') as f:
csv_writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csv_writer.writerow([token.get_id(), user.get_email(), token.get_client_id(), token.get_client_secret(), token.get_refresh_token(), token.get_access_token(), token.get_grant_token(), token.get_expires_in(), token.get_redirect_url()])
except IOError as ex:
raise SDKException(code=Constants.TOKEN_STORE, message=Constants.SAVE_TOKEN_FILE_ERROR, cause=ex)
def delete_token(self, token):
lines = list()
if isinstance(token, OAuthToken):
try:
with open(self.file_path, mode='r') as f:
data = csv.reader(f, delimiter=',')
for next_record in data:
if len(next_record) == 0:
continue
lines.append(next_record)
if self.check_token_exists(token.get_user_mail(), token, next_record):
lines.remove(next_record)
with open(self.file_path, mode='w') as f:
csv_writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csv_writer.writerows(lines)
except IOError as ex:
raise SDKException(code=Constants.TOKEN_STORE, message=Constants.DELETE_TOKEN_FILE_ERROR, cause=ex)
def get_tokens(self):
tokens = []
try:
with open(self.file_path, mode='r') as f:
data = csv.reader(f, delimiter=',')
next(data, None)
for next_record in data:
if len(next_record) == 0:
continue
grant_token = next_record[6] if next_record[6] is not None and len(
next_record[6]) > 0 else None
redirect_url = next_record[8] if next_record[8] is not None and len(
next_record[8]) > 0 else None
token = OAuthToken(client_id=next_record[2], client_secret=next_record[3], grant_token=grant_token, refresh_token=next_record[4])
token.set_id(next_record[0])
token.set_user_mail(next_record[1])
token.set_access_token(next_record[5])
token.set_expires_in(next_record[7])
token.set_redirect_url(redirect_url)
tokens.append(token)
return tokens
except Exception as ex:
raise SDKException(code=Constants.TOKEN_STORE, message=Constants.GET_TOKENS_FILE_ERROR, cause=ex)
def delete_tokens(self):
try:
with open(self.file_path, mode='w') as token_file:
csv_writer = csv.writer(token_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csv_writer.writerow(self.headers)
except Exception as ex:
raise SDKException(code=Constants.TOKEN_STORE, message=Constants.DELETE_TOKENS_FILE_ERROR, cause=ex)
def get_token_by_id(self, id, token):
try:
if isinstance(token, OAuthToken):
is_row_present = False
with open(self.file_path, mode='r') as f:
data = csv.reader(f, delimiter=',')
next(data, None)
for next_record in data:
if len(next_record) == 0:
continue
if next_record[0] == id:
is_row_present = True
grant_token = next_record[6] if next_record[6] is not None and len(
next_record[6]) > 0 else None
redirect_url = next_record[8] if next_record[8] is not None and len(
next_record[8]) > 0 else None
oauthtoken = token
oauthtoken.set_id(next_record[0])
oauthtoken.set_user_mail(next_record[1])
oauthtoken.set_client_id(next_record[2])
oauthtoken.set_client_secret(next_record[3])
oauthtoken.set_refresh_token(next_record[4])
oauthtoken.set_access_token(next_record[5])
oauthtoken.set_grant_token(grant_token)
oauthtoken.set_expires_in(next_record[7])
oauthtoken.set_redirect_url(redirect_url)
return oauthtoken
if not is_row_present:
raise SDKException(code=Constants.TOKEN_STORE, message=Constants.GET_TOKEN_BY_ID_FILE_ERROR)
except IOError as ex:
raise SDKException(code=Constants.TOKEN_STORE, message=Constants.GET_TOKEN_BY_ID_FILE_ERROR, cause=ex)
return None
@staticmethod
def check_token_exists(email, token, row):
if email is None:
raise SDKException(Constants.USER_MAIL_NULL_ERROR, Constants.USER_MAIL_NULL_ERROR_MESSAGE)
client_id = token.get_client_id()
grant_token = token.get_grant_token()
refresh_token = token.get_refresh_token()
token_check = grant_token == row[6] if grant_token is not None else refresh_token == row[4]
if row[1] == email and row[2] == client_id and token_check:
return True
return False | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/api/authenticator/store/file_store.py | file_store.py |
try:
import mysql.connector
from mysql.connector import Error
from zohosdk.src.com.zoho.api.authenticator.store.token_store import TokenStore
from zohosdk.src.com.zoho.api.authenticator.oauth_token import OAuthToken
from zohosdk.src.com.zoho.util.constants import Constants
from zohosdk.src.com.zoho.exception.sdk_exception import SDKException
except Exception as e:
import mysql.connector
from mysql.connector import Error
from .token_store import TokenStore
from ..oauth_token import OAuthToken
from ....util.constants import Constants
from zohosdk.src.com.zoho.exception.sdk_exception import SDKException
class DBStore(TokenStore):
"""
This class to store user token details to the MySQL DataBase.
"""
def __init__(self, host=Constants.MYSQL_HOST, database_name=Constants.MYSQL_DATABASE_NAME,
user_name=Constants.MYSQL_USER_NAME, password="", port_number=Constants.MYSQL_PORT_NUMBER,
table_name=Constants.MYSQL_TABLE_NAME):
"""
Creates a DBStore class instance with the specified parameters.
Parameters:
host (str) : A string containing the DataBase host name. Default value is localhost
database_name (str) : A string containing the DataBase name. Default value is zohooauth
user_name (str) : A string containing the DataBase user name. Default value is root
password (str) : A string containing the DataBase password. Default value is an empty string
port_number (str) : A string containing the DataBase port number. Default value is 3306
"""
self.__host = host
self.__database_name = database_name
self.__user_name = user_name
self.__password = password
self.__port_number = port_number
self.__table_name = table_name
def get_host(self):
"""
This is a getter method to get __host.
Returns:
string: A string representing __host
"""
return self.__host
def get_database_name(self):
"""
This is a getter method to get __database_name.
Returns:
string: A string representing __database_name
"""
return self.__database_name
def get_user_name(self):
"""
This is a getter method to get __user_name.
Returns:
string: A string representing __user_name
"""
return self.__user_name
def get_password(self):
"""
This is a getter method to get __password.
Returns:
string: A string representing __password
"""
return self.__password
def get_port_number(self):
"""
This is a getter method to get __port_number.
Returns:
string: A string representing __port_number
"""
return self.__port_number
def get_table_name(self):
"""
This is a getter method to get __table_name.
Returns:
string: A string representing __table_name
"""
return self.__table_name
def get_token(self, user, token):
cursor = None
try:
connection = mysql.connector.connect(host=self.__host, database=self.__database_name, user=self.__user_name, password=self.__password, port=self.__port_number)
try:
if isinstance(token, OAuthToken):
cursor = connection.cursor()
query = self.construct_dbquery(user.get_email(), token, False)
cursor.execute(query)
result = cursor.fetchone()
if result is not None:
oauthtoken = token
oauthtoken.set_id(result[0])
oauthtoken.set_user_mail(result[1])
oauthtoken.set_client_id(result[2])
oauthtoken.set_client_secret(result[3])
oauthtoken.set_refresh_token(result[4])
oauthtoken.set_access_token(result[5])
oauthtoken.set_grant_token(result[6])
oauthtoken.set_expires_in(str(result[7]))
oauthtoken.set_redirect_url(result[8])
return oauthtoken
except Error as ex:
raise ex
finally:
cursor.close() if cursor is not None else None
connection.close() if connection is not None else None
except Error as ex:
raise SDKException(code=Constants.TOKEN_STORE, message=Constants.GET_TOKEN_DB_ERROR, cause=ex)
def save_token(self, user, token):
cursor = None
try:
connection = mysql.connector.connect(host=self.__host, database=self.__database_name, user=self.__user_name, password=self.__password, port=self.__port_number)
try:
if isinstance(token, OAuthToken):
token.set_user_mail(user.get_email())
self.delete_token(token)
cursor = connection.cursor()
query = "insert into " + self.__table_name + " (id,user_mail,client_id,client_secret,refresh_token,access_token,grant_token,expiry_time,redirect_url) values (%s,%s,%s,%s,%s,%s,%s,%s,%s);"
val = (token.get_id(), user.get_email(), token.get_client_id(), token.get_client_secret(), token.get_refresh_token(), token.get_access_token(), token.get_grant_token(), token.get_expires_in(), token.get_redirect_url())
cursor.execute(query, val)
connection.commit()
except Error as ex:
raise ex
finally:
cursor.close() if cursor is not None else None
connection.close() if connection is not None else None
except Error as ex:
raise SDKException(code=Constants.TOKEN_STORE, message=Constants.SAVE_TOKEN_DB_ERROR, cause=ex)
def delete_token(self, token):
cursor = None
try:
connection = mysql.connector.connect(host=self.__host, database=self.__database_name, user=self.__user_name, password=self.__password, port=self.__port_number)
try:
if isinstance(token, OAuthToken):
cursor = connection.cursor()
query = self.construct_dbquery(token.get_user_mail(), token, True)
cursor.execute(query)
connection.commit()
except Error as ex:
raise ex
finally:
cursor.close() if cursor is not None else None
connection.close() if connection is not None else None
except Error as ex:
raise SDKException(code=Constants.TOKEN_STORE, message=Constants.DELETE_TOKEN_DB_ERROR, cause=ex)
def get_tokens(self):
cursor = None
try:
connection = mysql.connector.connect(host=self.__host, database=self.__database_name, user=self.__user_name, password=self.__password, port=self.__port_number)
tokens = []
try:
cursor = connection.cursor()
query = 'select * from ' + self.__table_name + ";"
cursor.execute(query)
results = cursor.fetchall()
for result in results:
token = OAuthToken(client_id=result[2], client_secret=result[3], refresh_token=result[4], grant_token=result[6])
token.set_id(result[0])
token.set_user_mail(result[1])
token.set_access_token(result[5])
token.set_expires_in(str(result[7]))
token.set_redirect_url(result[8])
tokens.append(token)
return tokens
except Error as ex:
raise ex
finally:
cursor.close() if cursor is not None else None
connection.close() if connection is not None else None
except Error as ex:
raise SDKException(code=Constants.TOKEN_STORE, message=Constants.GET_TOKENS_DB_ERROR, cause=ex)
def delete_tokens(self):
cursor = None
try:
connection = mysql.connector.connect(host=self.__host, database=self.__database_name, user=self.__user_name, password=self.__password, port=self.__port_number)
try:
cursor = connection.cursor()
query = 'delete from ' + self.__table_name + ";"
cursor.execute(query)
connection.commit()
except Error as ex:
raise ex
finally:
cursor.close() if cursor is not None else None
connection.close() if connection is not None else None
except Error as ex:
raise SDKException(code=Constants.TOKEN_STORE, message=Constants.DELETE_TOKENS_DB_ERROR, cause=ex)
def get_token_by_id(self, id, token):
cursor = None
try:
connection = mysql.connector.connect(host=self.__host, database=self.__database_name, user=self.__user_name, password=self.__password, port=self.__port_number)
try:
if isinstance(token, OAuthToken):
query = "select * from " + self.__table_name + " where id='" + id + "'"
oauthtoken = token
cursor = connection.cursor()
cursor.execute(query)
results = cursor.fetchall()
for result in results:
if result[0] == id:
oauthtoken.set_id(result[0])
oauthtoken.set_user_mail(result[1])
oauthtoken.set_client_id(result[2])
oauthtoken.set_client_secret(result[3])
oauthtoken.set_refresh_token(result[4])
oauthtoken.set_access_token(result[5])
oauthtoken.set_grant_token(result[6])
oauthtoken.set_expires_in(str(result[7]))
oauthtoken.set_redirect_url(result[8])
return oauthtoken
except Error as ex:
raise ex
finally:
cursor.close() if cursor is not None else None
connection.close() if connection is not None else None
except Error as ex:
raise SDKException(code=Constants.TOKEN_STORE, message=Constants.GET_TOKEN_BY_ID_DB_ERROR, cause=ex)
def construct_dbquery(self, email, token, is_delete):
if email is None:
raise SDKException(Constants.USER_MAIL_NULL_ERROR, Constants.USER_MAIL_NULL_ERROR_MESSAGE)
query = "delete from " if is_delete is True else "select * from "
query += self.__table_name + " where user_mail ='" + email + "' and client_id='" + token.get_client_id() + "' and "
if token.get_grant_token() is not None:
query += "grant_token='" + token.get_grant_token() + "'"
else:
query += "refresh_token='" + token.get_refresh_token() + "'"
return query | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/api/authenticator/store/db_store.py | db_store.py |
try:
import logging
from zohosdk.src.com.zoho.exception.sdk_exception import SDKException
from ...util.constants import Constants
except Exception as e:
from ...util.constants import Constants
from zohosdk.src.com.zoho.exception import SDKException
class Logger(object):
"""
This class represents the Logger level and the file path.
"""
def __init__(self, level, file_path=None):
self.__level = level
self.__file_path = file_path
def get_level(self):
"""
This is a getter method to get __level.
Returns:
string: A enum representing __level
"""
return self.__level
def get_file_path(self):
"""
This is a getter method to get __file_path.
Returns:
string: A string representing __file_path
"""
return self.__file_path
@staticmethod
def get_instance(level, file_path=None):
"""
Creates an Logger class instance with the specified log level and file path.
:param level: A Levels class instance containing the log level.
:param file_path: A str containing the log file path.
:return: A Logger class instance.
"""
return Logger(level=level, file_path=file_path)
import enum
class Levels(enum.Enum):
"""
This class represents the possible logger levels
"""
CRITICAL = logging.CRITICAL
ERROR = logging.ERROR
WARNING = logging.WARNING
INFO = logging.INFO
DEBUG = logging.DEBUG
NOTSET = logging.NOTSET
class SDKLogger(object):
"""
The class to initialize the SDK logger.
"""
def __init__(self, logger_instance):
logger = logging.getLogger('SDKLogger')
if logger_instance is None:
logger.setLevel(Logger.Levels.INFO.INFO)
return
logger_level = logger_instance.get_level()
logger_file_path = logger_instance.get_file_path()
if logger_level is not None and logger_level != logging.NOTSET and logger_file_path is not None and logger_file_path != "":
file_handler = logging.FileHandler(logger_file_path)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(module)s - %(filename)s - %(funcName)s - %(lineno)d - %(message)s')
file_handler.setLevel(logger_level.name)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
if logger_level is not None and Constants.LOGGER_LEVELS.__contains__(logger_level.name):
logger.setLevel(logger_level.name)
@staticmethod
def initialize(logger_instance):
try:
SDKLogger(logger_instance=logger_instance)
except Exception as ex:
raise SDKException(message=Constants.LOGGER_INITIALIZATION_ERROR, Exception=ex) | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/api/logger/logger.py | logger.py |
try:
from dateutil.tz import tz
import dateutil.parser
from zohosdk.src.com.zoho.util.constants import Constants
from datetime import date, datetime
except Exception:
from dateutil.tz import tz
import dateutil.parser
from .constants import Constants
from datetime import date, datetime
class DataTypeConverter(object):
"""
This class converts JSON value to the expected object type and vice versa.
"""
pre_converter_map = {}
post_converter_map = {}
@staticmethod
def init():
"""
The method to initialize the PreConverter and PostConverter lambda functions.
"""
if len(DataTypeConverter.pre_converter_map) != 0 and len(DataTypeConverter.post_converter_map) != 0:
return
DataTypeConverter.add_to_map("String", lambda obj: str(obj), lambda obj: str(obj))
DataTypeConverter.add_to_map("Integer", lambda obj: int(obj), lambda obj: int(obj))
DataTypeConverter.add_to_map("Long", lambda obj: int(obj) if str(obj) != Constants.NULL_VALUE else None, lambda obj: int(obj))
DataTypeConverter.add_to_map("Boolean", lambda obj: bool(obj), lambda obj: bool(obj))
DataTypeConverter.add_to_map("Float", lambda obj: float(obj), lambda obj: float(obj))
DataTypeConverter.add_to_map("Double", lambda obj: float(obj), lambda obj: float(obj))
DataTypeConverter.add_to_map("Date", lambda obj: dateutil.parser.isoparse(obj).date(), lambda obj: obj.isoformat())
DataTypeConverter.add_to_map("DateTime", lambda obj: dateutil.parser.isoparse(obj).astimezone(tz.tzlocal()), lambda obj: obj.replace(microsecond=0).astimezone(tz.tzlocal()).isoformat())
DataTypeConverter.add_to_map("Object", lambda obj: DataTypeConverter.pre_convert_object_data(obj), lambda obj: DataTypeConverter.post_convert_object_data(obj))
@staticmethod
def pre_convert_object_data(obj):
return obj
@staticmethod
def post_convert_object_data(obj):
if obj is None:
return None
if isinstance(obj, list):
list_value = []
for data in obj:
list_value.append(DataTypeConverter.post_convert_object_data(data))
return list_value
elif isinstance(obj, dict):
dict_value = {}
for key, value in obj.items():
dict_value[key] = DataTypeConverter.post_convert_object_data(value)
return dict_value
elif isinstance(obj, date):
return DataTypeConverter.post_convert(obj, Constants.DATE_NAMESPACE)
elif isinstance(obj, datetime):
return DataTypeConverter.post_convert(obj, Constants.DATETIME_NAMESPACE)
else:
return obj
@staticmethod
def add_to_map(name, pre_converter, post_converter):
"""
This method to add PreConverter and PostConverter instance.
:param name: A str containing the data type class name.
:param pre_converter: A pre_converter instance.
:param post_converter: A post_converter instance.
"""
DataTypeConverter.pre_converter_map[name] = pre_converter
DataTypeConverter.post_converter_map[name] = post_converter
@staticmethod
def pre_convert(obj, data_type):
"""
The method to convert JSON value to expected data value.
:param obj: An object containing the JSON value.
:param data_type: A str containing the expected method return type.
:return: An object containing the expected data value.
"""
DataTypeConverter.init()
if data_type in DataTypeConverter.pre_converter_map:
return DataTypeConverter.pre_converter_map[data_type](obj)
@staticmethod
def post_convert(obj, data_type):
"""
The method to convert python data to JSON data value.
:param obj: A object containing the python data value.
:param data_type: A str containing the expected method return type.
:return: An object containing the expected data value.
"""
DataTypeConverter.init()
if data_type in DataTypeConverter.post_converter_map:
return DataTypeConverter.post_converter_map[data_type](obj) | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/util/datatype_converter.py | datatype_converter.py |
import datetime
class Constants(object):
"""
This class uses the SDK constants name reference.
"""
DATA_TYPE_ERROR = "DATA TYPE ERROR"
ERROR = "error"
REQUEST_METHOD_GET = "GET"
REQUEST_METHOD_POST = "POST"
REQUEST_METHOD_PUT = "PUT"
REQUEST_METHOD_DELETE = "DELETE"
GIVEN_VALUE = "given-value"
REQUEST_METHOD_PATCH = 'PATCH'
OAUTH_HEADER_PREFIX = "Zoho-oauthtoken "
AUTHORIZATION = "Authorization"
API_NAME = "api_name"
PHOTO = "photo"
API_VERSION = "v1.0"
INPUT_ERROR = "INPUT_ERROR"
LOGGER_LEVELS = {
"CRITICAL": "CRITICAL",
"ERROR": "ERROR",
"WARNING": "WARNING",
"INFO": "INFO",
"DEBUG": "DEBUG",
"NOTSET": "NOTSET"
}
PROXY_SETTINGS = "Proxy settings - "
PROXY_HOST = "Host: "
PROXY_PORT = "Port: "
PROXY_USER = "User: "
PROXY_DOMAIN = "Domain: "
GET_TOKEN_BY_ID_DB_ERROR = "Exception in getTokenById - DBStore : Given ID is invalid"
GET_TOKEN_BY_ID_FILE_ERROR = "Exception in getTokenById - FileStore : Given ID is invalid"
MYSQL_TABLE_NAME = "oauthtoken"
SWITCH_USER_ERROR = "SWITCH USER ERROR"
LOGGER_INITIALIZATION_ERROR = "Exception in Logger Initialization : "
INVALID_ID_MSG = "The given id seems to be invalid."
API_MAX_RECORDS_MSG = "Cannot process more than 100 records at a time."
INVALID_DATA = "INVALID_DATA"
CODE_SUCCESS = "SUCCESS"
STATUS_SUCCESS = "success"
STATUS_ERROR = "error"
GRANT_TYPE = "grant_type"
GRANT_TYPE_AUTH_CODE = "authorization_code"
ACCESS_TOKEN = "access_token"
EXPIRES_IN = "expires_in"
EXPIRES_IN_SEC = "expires_in_sec"
REFRESH_TOKEN = "refresh_token"
CLIENT_ID = "client_id"
CLIENT_SECRET = "client_secret"
REDIRECT_URI = "redirect_uri"
REDIRECT_URL = "redirect_url"
OBJECT = "Object"
DATA_TYPE = {
"String": str,
"List": list,
"Integer": int,
"HashMap": dict,
"Map": dict,
"Long": int,
"Double": float,
"Float": float,
"DateTime": datetime.datetime,
"Date": datetime.date,
"Boolean": bool
}
OBJECT_KEY = "object"
GIVEN_LENGTH = "given-length"
ZOHO_SDK = "X-ZOHO-SDK"
SDK_VERSION = "1.0.0"
CONTENT_DISPOSITION = "Content-Disposition"
TOKEN_ERROR = "TOKEN ERROR"
SAVE_TOKEN_ERROR = "Exception in saving tokens"
INVALID_CLIENT_ERROR = "INVALID CLIENT ERROR"
ERROR_KEY = 'error'
GET_TOKEN_ERROR = "Exception in getting access token"
MYSQL_HOST = "localhost"
MYSQL_DATABASE_NAME = "zohooauth"
MYSQL_USER_NAME = "root"
MYSQL_PORT_NUMBER = "3306"
GET_TOKEN_DB_ERROR = "Exception in getToken - DBStore"
TOKEN_STORE = "TOKEN_STORE"
DELETE_TOKEN_DB_ERROR = "Exception in delete_token - DBStore"
SAVE_TOKEN_DB_ERROR = "Exception in save_token - DBStore"
USER_MAIL = "user_mail"
GRANT_TOKEN = "grant_token"
EXPIRY_TIME = "expiry_time"
GET_TOKEN_FILE_ERROR = "Exception in get_token - FileStore"
SAVE_TOKEN_FILE_ERROR = "Exception in save_token - FileStore"
DELETE_TOKEN_FILE_ERROR = "Exception in delete_token - FileStore"
TYPE = "type"
STREAM_WRAPPER_CLASS_PATH = 'zohosdk.src.com.zoho.util.StreamWrapper'
FIELD = "field"
NAME = "name"
INDEX = "index"
CLASS = "class"
ACCEPTED_TYPE = "accepted_type"
GIVEN_TYPE = "given_type"
TYPE_ERROR = "TYPE ERROR"
VALUES = "values"
ACCEPTED_VALUES = "accepted_values"
UNACCEPTED_VALUES_ERROR = "UNACCEPTED VALUES ERROR"
MIN_LENGTH = "min-length"
MINIMUM_LENGTH = "minimum-length"
MINIMUM_LENGTH_ERROR = "MINIMUM LENGTH ERROR"
UNIQUE = "unique"
FIRST_INDEX = "first-index"
NEXT_INDEX = "next-index"
UNIQUE_KEY_ERROR = "UNIQUE KEY ERROR"
MAX_LENGTH = "max-length"
MAXIMUM_LENGTH = "maximum-length"
MAXIMUM_LENGTH_ERROR = "MAXIMUM LENGTH ERROR"
REGEX = "regex"
INSTANCE_NUMBER = "instance-number"
REGEX_MISMATCH_ERROR = "REGEX MISMATCH ERROR"
READ_ONLY = "read-only"
WRITE_ONLY = "write-only"
UPDATE_ONLY = "update-only"
IS_KEY_MODIFIED = 'is_key_modified'
REQUIRED = "required"
REQUIRED_IN_UPDATE = "required-in-update"
PRIMARY = "primary"
MANDATORY_VALUE_ERROR = "MANDATORY VALUE ERROR"
MANDATORY_VALUE_NULL_ERROR = "MANDATORY VALUE NULL ERROR"
MANDATORY_KEY_ERROR = "Value missing or None for mandatory key(s): "
MANDATORY_KEY_NULL_ERROR = "Null Value for mandatory key : "
SET_KEY_MODIFIED = "set_key_modified"
LIST_NAMESPACE = "List"
MAP_NAMESPACE = "Map"
HASH_MAP = "HashMap"
STRUCTURE_NAME = "structure_name"
KEYS = "keys"
INTERFACE = "interface"
PRODUCTS = "Products"
TAX = "TAX"
TERRITORY = "Territory"
PACKAGE_NAMESPACE = "zohosdk.src.com.zoho."
CHOICE_NAMESPACE = "zohosdk.src.com.zoho.util.Choice"
KEY_VALUES = "key_values"
KEY_MODIFIED = "key_modified"
COMMENTS = "Comments"
CLASSES = "classes"
LOGFILE_NAME = "sdk_logs.log"
USER = "user"
EXPECTED_TYPE = "expected-type"
USER_AGENT = "Mozilla/5.0"
USER_AGENT_KEY = "user-agent"
AT = '@'
EXPECTED_TOKEN_TYPES = 'REFRESH, GRANT'
INITIALIZATION_ERROR = "INITIALIZATION ERROR"
ENVIRONMENT = "environment"
STORE = "store"
TOKEN = "token"
SDK_CONFIG = "sdk_config"
USER_PROXY = "proxy"
JSON_DETAILS_FILE_PATH = 'json_details.json'
EMAIL = "email"
USER_SIGNATURE_ERROR = "USERSIGNATURE ERROR"
USER_INITIALIZATION_ERROR = "Error during User Initialization"
EMAIL_REGEX = '^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$'
STRING = "String"
TOKEN_TYPE = "token_type"
GRANT = "GRANT"
REFRESH = "REFRESH"
CONTENT_TYPE = 'Content-Type'
STRING_NAMESPACE = 'String'
BOOLEAN_NAMESPACE = 'Boolean'
INTEGER_NAMESPACE = 'Integer'
LONG_NAMESPACE = 'Long'
DOUBLE_NAMESPACE = 'Float'
DATE_NAMESPACE = 'Date'
DATETIME_NAMESPACE = 'DateTime'
DISCOUNT = "DISCOUNT"
FILE_NAMESPACE = "zohosdk.src.com.zoho.util.StreamWrapper"
LAYOUT = "Layout"
SUBFORM = "subform"
LOOKUP = "lookup"
MODULEDETAILS = 'moduleDetails'
MODULEPACKAGENAME = "modulePackageName"
UNDERSCORE = "_"
FIELD_DETAILS_DIRECTORY = "resources"
NO_CONTENT_STATUS_CODE = 204
NOT_MODIFIED_STATUS_CODE = 304
HREF = "href"
API_EXCEPTION = "API_EXCEPTION"
FIELDS_LAST_MODIFIED_TIME = "FIELDS-LAST-MODIFIED-TIME"
LINE_TAX = "$line_tax"
CANT_DISCLOSE = " ## can't disclose ## "
URL = "URL"
HEADERS = "HEADERS"
PARAMS = "PARAMS"
INITIALIZATION_SUCCESSFUL = "Initialization successful "
INITIALIZATION_SWITCHED = "Initialization switched "
IN_ENVIRONMENT = " in Environment : "
FOR_EMAIL_ID = "for Email Id : "
REFRESH_TOKEN_MESSAGE = "Access Token has expired. Hence refreshing."
CONTENT_TYPE_HEADER = "Content-Type"
LIST_KEY = "List"
ATTACHMENT_ID = "attachment_id"
FILE_ID = "file_id"
PHOTO_UPLOAD_ERROR_MESSAGE = "The given module is not supported in API."
INVALID_MODULE = "INVALID_MODULE"
MULTI_SELECT_LOOKUP = "multiselectlookup"
MULTI_USER_LOOKUP = "multiuserlookup"
TERRITORIES = "territories"
GENERATED_TYPE = "generated_type"
GENERATED_TYPE_CUSTOM = "custom"
UPLOAD_PHOTO_UNSUPPORTED_MESSAGE = "Photo Upload Operation is not supported by the module: "
SDK_MODULE_METADATA = "SDK-MODULE-METADATA"
INVALID_MODULE_API_NAME_ERROR = "INVALID MODULE API NAME ERROR"
PROVIDE_VALID_MODULE_API_NAME = "PROVIDE VALID MODULE API NAME: "
UPLOAD_PHOTO_UNSUPPORTED_ERROR = "UPLOAD PHOTO UNSUPPORTED MODULE"
DELETE_FIELD_FILE_ERROR = "Exception in deleting Current User Fields file : "
DELETE_FIELD_FILES_ERROR = "Exception in deleting all Fields files : "
DELETE_MODULE_FROM_FIELDFILE_ERROR = "Exception in deleting module from Fields file : "
FILE_BODY_WRAPPER = 'FileBodyWrapper'
EXCEPTION_IS_KEY_MODIFIED = "Exception in calling is_key_modified : "
EXCEPTION_SET_KEY_MODIFIED = "Exception in calling set_key_modified : "
SET_API_URL_EXCEPTION = "Exception in setting API URL : "
AUTHENTICATION_EXCEPTION = "Exception in authenticating current request : "
FORM_REQUEST_EXCEPTION = "Exception in forming request body : "
API_CALL_EXCEPTION = "Exception in current API call execution : "
HTTP = "http"
HTTPS = "https"
CONTENT_API_URL = "content.zohoapis.com"
EXCEPTION = "Exception"
MODULE = "module"
REQUEST_CATEGORY_READ = "READ"
REQUEST_CATEGORY_CREATE = "CREATE"
REQUEST_CATEGORY_UPDATE = "UPDATE"
ID = "id"
CODE = "code"
STATUS = "status"
MESSAGE = "message"
INVALID_URL_ERROR = "Invalid URL Error"
REQUEST_CATEGORY_ACTION = "ACTION"
SKIP_MANDATORY = "skip-mandatory"
FORMULA = "formula"
PICKLIST = "picklist"
ACCOUNTS = "accounts"
PRIMARY_KEY_ERROR = "Value missing or None for required key(s) : "
REFRESH_SINGLE_MODULE_FIELDS_ERROR = "Exception in refreshing fields of module : "
REFRESH_ALL_MODULE_FIELDS_ERROR = "Exception in refreshing fields of all modules : "
GET_TOKENS_DB_ERROR = "Exception in get_tokens - DBStore"
DELETE_TOKENS_DB_ERROR = "Exception in delete_tokens - DBStore"
GET_TOKENS_FILE_ERROR = "Exception in get_tokens - FileStore"
DELETE_TOKENS_FILE_ERROR = "Exception in delete_tokens - FileStore"
SDK_UNINITIALIZATION_ERROR = "SDK UNINITIALIZED ERROR"
SDK_UNINITIALIZATION_MESSAGE = "SDK is UnInitialized"
INITIALIZATION_EXCEPTION = "Exception in initialization"
SWITCH_USER_EXCEPTION = "Exception in switching user"
AUTO_REFRESH_FIELDS_ERROR_MESSAGE = "auto_refresh_fields MUST NOT be None."
HEADER_NONE_ERROR = "NONE HEADER ERROR"
PRODUCT_NAME = "Product_Name"
HEADER_INSTANCE_NONE_ERROR = "Header Instance MUST NOT be None"
PARAM_INSTANCE_NONE_ERROR = "Param Instance MUST NOT be None"
HEADER_NAME_NONE_ERROR = "NONE HEADER NAME ERROR"
HEADER_NAME_NULL_ERROR_MESSAGE = "Header Name MUST NOT be null"
NONE_VALUE_ERROR_MESSAGE = " MUST NOT be None"
PARAMETER_NONE_ERROR = "NONE PARAMETER ERROR"
PARAM_NAME_NONE_ERROR = "NONE PARAM NAME ERROR"
PARAM_NAME_NONE_ERROR_MESSAGE = "Param Name MUST NOT be None"
USER_PROXY_ERROR = "USERPROXY ERROR"
HOST_ERROR_MESSAGE = "Host MUST NOT be None"
PORT_ERROR_MESSAGE = "Port MUST NOT be None"
USER_ERROR_MESSAGE = "User MUST NOT be None/empty"
UNSUPPORTED_IN_API = "API UNSUPPORTED OPERATION"
UNSUPPORTED_IN_API_MESSAGE = " Operation is not supported by API"
NULL_VALUE = "null"
NOTES = "notes"
ATTACHMENTS = "$attachments"
JSON_FILE_EXTENSION = ".json"
FILE_ERROR = "file_error"
FILE_DOES_NOT_EXISTS = "file does not exists"
CONSENT_LOOKUP = "consent_lookup"
USER_MAIL_NULL_ERROR = "USER MAIL NONE ERROR"
USER_MAIL_NULL_ERROR_MESSAGE = "User Mail MUST NOT be None. Set value to user_mail."
JSON_DETAILS_ERROR = "ERROR IN READING JSONDETAILS FILE"
INVALID_TOKEN_ERROR = "INVALID TOKEN ERROR"
NO_ACCESS_TOKEN_ERROR = "ACCESS TOKEN IS NOT PRESENT IN RESPONSE"
CLIENT_ID_NULL_ERROR_MESSAGE = "ClientID MUST NOT be null"
CLIENT_SECRET_NULL_ERROR_MESSAGE = "ClientSecret MUST NOT be null"
REQUEST_PROXY_ERROR_MESSAGE = "request_proxy must be instance of Request Proxy"
USER_SIGNATURE_ERROR_MESSAGE = "user must be instance of userSignature."
ENVIRONMENT_ERROR_MESSAGE = "environment must be instance of Environment."
SDK_CONFIG_ERROR_MESSAGE = "sdk_config must be instance of sdkConfig."
TOKEN_ERROR_MESSAGE = "token must be instance of Token."
STORE_ERROR_MESSAGE = "store must be instance of Store."
COUNT = "count"
OWNER_LOOKUP = "ownerlookup"
TOKEN_FILE = "sdk_tokens.txt"
LOG_FILE_NAME = "sdk_logs.log"
PYTHON = "python_"
OAUTH_MANDATORY_KEYS = ["grant_token", "refresh_token", "id", "access_token"] | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/util/constants.py | constants.py |
try:
from abc import ABC, abstractmethod
import logging
import sys
import zlib
import base64
import re
import os
import importlib
from zohosdk.src.com.zoho.util import Choice
except Exception:
from abc import ABC, abstractmethod
import logging
import sys
import zlib
import base64
import re
import os
import importlib
from .choice import Choice
class Converter(ABC):
"""
This abstract class is to construct API request and response.
"""
logger = logging.getLogger('SDKLogger')
def __init__(self, common_api_handler):
"""
Creates a Converter class instance with the CommonAPIHandler class instance.
:param common_api_handler: A CommonAPIHandler class instance.
"""
self.common_api_handler = common_api_handler
@abstractmethod
def get_response(self, response, pack):
"""
This abstract method to process the API response.
:param response: A object containing the API response contents or response.
:param pack: A str containing the expected method return type.
:return: A object representing the POJO class instance.
"""
pass
@abstractmethod
def form_request(self, request_instance, pack, instance_number, class_member_detail):
"""
This abstract method to construct the API request.
:param request_instance: A Object containing the POJO class instance.
:param pack: A str containing the expected method return type.
:param instance_number: An int containing the POJO class instance list number.
:param class_member_detail : A dict representing the member details
:return: A object representing the API request body object.
"""
pass
@abstractmethod
def append_to_request(self, request_base, request_object):
"""
This abstract method to construct the API request body.
:param request_base: A HttpEntityEnclosingRequestBase class instance.
:param request_object: A object containing the API request body object.
"""
pass
@abstractmethod
def get_wrapped_response(self, response, pack):
"""
This abstract method to process the API response.
:param response: A object containing the HttpResponse class instance.
:param pack: A str containing the expected method return type.
:return: A object representing the POJO class instance.
"""
pass
def value_checker(self, class_name, member_name, key_details, value, unique_values_map, instance_number):
"""
This method is to validate if the input values satisfy the constraints for the respective fields.
:param class_name: A str containing the class name.
:param member_name: A str containing the member name.
:param key_details: A JSON object containing the key JSON details.
:param value: A object containing the key value.
:param unique_values_map: A list containing the construct objects.
:param instance_number: An int containing the POJO class instance list number.
:return: A bool representing the key value is expected pattern, unique, length, and values.
"""
try:
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util.constants import Constants
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from ..exception import SDKException
from .constants import Constants
from ..initializer import Initializer
details_jo = {}
name = key_details[Constants.NAME]
data_type = key_details[Constants.TYPE]
check = True
given_type = None
if value is not None:
if Constants.INTERFACE in key_details and key_details[Constants.INTERFACE]:
interface_details = Initializer.get_initializer().json_details[key_details[Constants.STRUCTURE_NAME]]
classes = interface_details[Constants.CLASSES]
check = False
for each_class in classes:
path_split = str(value.__class__.__module__).rpartition(".")
class_name = self.module_to_class(path_split[-1])
pack = path_split[0] + "." + class_name
if pack == each_class:
check = True
break
else:
given_type = value.__class__.__module__
if data_type in Constants.DATA_TYPE:
if isinstance(value, list) and Constants.STRUCTURE_NAME in key_details:
structure_name = key_details[Constants.STRUCTURE_NAME]
index = 0
path_split = str(structure_name).rpartition('.')
imported_module = importlib.import_module(path_split[0])
class_holder = getattr(imported_module, path_split[-1])
for each_instance in value:
if not isinstance(each_instance, class_holder):
check = False
instance_number = index
data_type = Constants.LIST_KEY + '[' + structure_name + ']'
given_type = each_instance.__module__
break
index = index + 1
else:
try:
from zohosdk.src.com.zoho.util import Utility
except Exception:
from .utility import Utility
check = Utility.check_data_type(value=value, type=data_type)
elif value is not None and data_type.lower() != Constants.OBJECT_KEY:
path_split = str(data_type).rpartition('.')
imported_module = importlib.import_module(path_split[0])
class_holder = getattr(imported_module, path_split[-1])
if not isinstance(value, class_holder):
check = False
if not check:
details_jo[Constants.FIELD] = name
details_jo[Constants.CLASS] = class_name
details_jo[Constants.ACCEPTED_TYPE] = data_type
details_jo[Constants.GIVEN_TYPE] = given_type
if instance_number is not None:
details_jo[Constants.INDEX] = instance_number
raise SDKException(code=Constants.TYPE_ERROR, details=details_jo)
if Constants.VALUES in key_details and \
(Constants.PICKLIST not in key_details
or (key_details[Constants.PICKLIST]
and Initializer.get_initializer().sdk_config.get_pick_list_validation())):
values_ja = key_details[Constants.VALUES]
if isinstance(value, Choice):
value = value.get_value()
if value not in values_ja:
details_jo[Constants.FIELD] = member_name
details_jo[Constants.CLASS] = class_name
details_jo[Constants.GIVEN_VALUE] = value
details_jo[Constants.ACCEPTED_VALUES] = values_ja
if instance_number is not None:
details_jo[Constants.INDEX] = instance_number
raise SDKException(code=Constants.UNACCEPTED_VALUES_ERROR, details=details_jo)
if Constants.UNIQUE in key_details:
if name not in unique_values_map:
unique_values_map[name] = []
values_array = unique_values_map[name]
if value in values_array:
details_jo[Constants.FIELD] = member_name
details_jo[Constants.CLASS] = class_name
details_jo[Constants.FIRST_INDEX] = values_array.index(value) + 1
details_jo[Constants.NEXT_INDEX] = instance_number
raise SDKException(code=Constants.UNIQUE_KEY_ERROR, details=details_jo)
else:
unique_values_map[name].append(value)
if Constants.MIN_LENGTH in key_details or Constants.MAX_LENGTH in key_details:
count = len(str(value))
if isinstance(value, list):
count = len(value)
if Constants.MAX_LENGTH in key_details and count > key_details[Constants.MAX_LENGTH]:
details_jo[Constants.FIELD] = member_name
details_jo[Constants.CLASS] = class_name
details_jo[Constants.GIVEN_LENGTH] = count
details_jo[Constants.MAXIMUM_LENGTH] = key_details[Constants.MAX_LENGTH]
raise SDKException(code=Constants.MAXIMUM_LENGTH_ERROR, details=details_jo)
if Constants.MIN_LENGTH in key_details and count < key_details[Constants.MIN_LENGTH]:
details_jo[Constants.FIELD] = member_name
details_jo[Constants.CLASS] = class_name
details_jo[Constants.GIVEN_LENGTH] = count
details_jo[Constants.MINIMUM_LENGTH] = key_details[Constants.MIN_LENGTH]
raise SDKException(code=Constants.MINIMUM_LENGTH_ERROR, details=details_jo)
if Constants.REGEX in key_details:
if re.search(value, key_details[Constants.REGEX]) is None:
details_jo[Constants.FIELD] = member_name
details_jo[Constants.CLASS] = class_name
details_jo[Constants.INSTANCE_NUMBER] = instance_number
raise SDKException(code=Constants.REGEX_MISMATCH_ERROR, details=details_jo)
return True
def module_to_class(self, module_name):
class_name = module_name
if "_" in module_name:
class_name = ''
module_split = str(module_name).split('_')
for each_name in module_split:
each_name = each_name.capitalize()
class_name += each_name
return class_name
@classmethod
def get_encoded_file_name(cls):
"""
The method to get the module field JSON details file name.
:return: A str representing the module field JSON details file name.
"""
try:
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from ..initializer import Initializer
file_name = Initializer.get_initializer().user.get_email()
file_name = file_name.split("@", 1)[0] + Initializer.get_initializer().environment.url
input_bytes = file_name.encode("UTF-8")
encoded_string = base64.b64encode(input_bytes)
encoded_string = str(encoded_string.decode("UTF-8"))
return encoded_string + '.json' | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/util/converter.py | converter.py |
try:
import importlib
import logging
import re
import json
from zohosdk.src.com.zoho.util import Converter, Constants, StreamWrapper, DataTypeConverter
from zohosdk.src.com.zoho.exception.sdk_exception import SDKException
except Exception:
import importlib
import logging
import re
from .converter import Converter
from .constants import Constants
from .datatype_converter import DataTypeConverter
from .stream_wrapper import StreamWrapper
from ..exception import SDKException
class FormDataConverter(Converter):
"""
This class to process the upload file and stream.
"""
logger = logging.getLogger('SDKLogger')
def __init__(self, common_api_handler):
super().__init__(common_api_handler)
self.unique_dict = {}
self.common_api_handler = common_api_handler
def append_to_request(self, request_base, request_object):
form_data_request_body = []
request_base.file = True
if self.check_file_request(request_object):
self.add_file_body(request_object, form_data_request_body)
else:
self.add_multi_part_body(request_object, form_data_request_body)
return form_data_request_body
def check_file_request(self, request_object):
for key_name, key_value in request_object.items():
if isinstance(key_value, list):
for each_object in key_value:
if not isinstance(each_object, StreamWrapper):
return False
elif not isinstance(key_value, StreamWrapper):
return False
return True
def add_multi_part_body(self, request_object, request_body):
for key_name, key_value in request_object.items():
if isinstance(key_value, list):
for each_object in key_value:
if isinstance(each_object, StreamWrapper):
request_body.append((key_name, each_object.get_stream()))
else:
request_body.append((key_name, (None, json.dumps(key_value))))
elif isinstance(key_value, StreamWrapper):
request_body.append((key_name, key_value.get_stream()))
else:
request_body.append((key_name, (None, json.dumps(key_value))))
def add_file_body(self, request_object, request_body):
for key_name, key_value in request_object.items():
if isinstance(key_value, list):
for each_object in key_value:
if isinstance(each_object, StreamWrapper):
request_body.append((key_name, each_object.get_stream()))
else:
request_body.append((key_name, key_value))
elif isinstance(key_value, StreamWrapper):
request_body.append((key_name, key_value.get_stream()))
else:
request_body.append((key_name, key_value))
def form_request(self, request_instance, pack, instance_number, class_member_detail):
path_split = str(pack).rpartition(".")
class_name = self.module_to_class(path_split[-1])
pack = path_split[0] + "." + class_name
try:
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from ..initializer import Initializer
class_detail = dict(Initializer.json_details[str(pack)])
request = dict()
if Constants.INTERFACE in class_detail and class_detail[Constants.INTERFACE] is not None:
request_object_class_name = request_instance.__class__.__module__
request_object_class_name = str(request_object_class_name)
path_split = str(request_object_class_name).rpartition(".")
request_class_name = self.module_to_class(path_split[-1])
request_object_class_name = path_split[0] + "." + request_class_name
classes = class_detail[Constants.CLASSES]
for class_name in classes:
class_name_interface_lower = str(class_name).lower()
request_class_path_lower = request_object_class_name.lower()
if class_name_interface_lower == request_class_path_lower:
class_detail = dict(Initializer.json_details[str(class_name)])
class_name = str(class_name).rpartition(".")
class_name = self.module_to_class(class_name[-1])
break
lookup = False
skip_mandatory = False
class_member_name = None
if class_member_detail is not None:
lookup = class_member_detail[Constants.LOOKUP] if Constants.LOOKUP in class_member_detail else False
skip_mandatory = class_member_detail[Constants.SKIP_MANDATORY] \
if Constants.SKIP_MANDATORY in class_member_detail else False
class_member_name = class_member_detail[Constants.NAME]
required_keys, primary_keys, required_in_update_keys = {}, {}, {}
for member_name, member_detail in class_detail.items():
if ((Constants.WRITE_ONLY in member_detail and not bool(
member_detail[Constants.WRITE_ONLY])) and (Constants.UPDATE_ONLY in member_detail and not bool(
member_detail[Constants.UPDATE_ONLY])) and (Constants.READ_ONLY in member_detail and bool(
member_detail[Constants.READ_ONLY]))) or (Constants.NAME not in member_detail):
continue
key_name = member_detail[Constants.NAME]
try:
modification = getattr(request_instance, Constants.IS_KEY_MODIFIED)(key_name)
except Exception as e:
raise SDKException(code=Constants.EXCEPTION_IS_KEY_MODIFIED, cause=e)
if Constants.REQUIRED in member_detail and member_detail[Constants.REQUIRED]:
required_keys[key_name] = True
if Constants.PRIMARY in member_detail and member_detail[Constants.PRIMARY] and \
(Constants.REQUIRED_IN_UPDATE not in member_detail or member_detail[Constants.REQUIRED_IN_UPDATE]):
primary_keys[key_name] = True
if Constants.REQUIRED_IN_UPDATE in member_detail and member_detail[Constants.REQUIRED_IN_UPDATE]:
required_in_update_keys[key_name] = True
field_value = getattr(request_instance, self.construct_private_member(class_name=class_name, member_name=member_name))
if modification is not None and modification != 0 and field_value is not None and self.value_checker(class_name=class_name, member_name=member_name, key_details=member_detail, value=field_value, unique_values_map=self.unique_dict, instance_number=instance_number) is True:
if field_value is not None:
required_keys.pop(key_name, None)
primary_keys.pop(key_name, None)
required_in_update_keys.pop(key_name, None)
if field_value is not None:
data_type = member_detail[Constants.TYPE]
if data_type == Constants.LIST_NAMESPACE:
request[key_name] = self.set_json_array(field_value, member_detail)
elif data_type == Constants.MAP_NAMESPACE:
request[key_name] = self.set_json_object(field_value, member_detail)
elif data_type == Constants.CHOICE_NAMESPACE or \
(Constants.STRUCTURE_NAME in member_detail and
member_detail[Constants.STRUCTURE_NAME] == Constants.CHOICE_NAMESPACE):
request[key_name] = field_value.get_value()
elif Constants.STRUCTURE_NAME in member_detail:
request[key_name] = self.form_request(field_value, member_detail[Constants.STRUCTURE_NAME], None, member_detail)
else:
request[key_name] = field_value
if skip_mandatory or self.check_exception(class_member_name, request_instance, instance_number, lookup, required_keys, primary_keys, required_in_update_keys) is True:
return request
def check_exception(self, member_name, request_instance, instance_number,
lookup, required_keys, primary_keys, required_in_update_keys):
if bool(required_in_update_keys) and self.common_api_handler is not None and self.common_api_handler.get_category_method() is not None and \
self.common_api_handler.get_category_method().upper() == Constants.REQUEST_CATEGORY_UPDATE:
error = {
Constants.FIELD: member_name,
Constants.TYPE: request_instance.__module__,
Constants.KEYS: str(list(required_in_update_keys.keys()))
}
if instance_number is not None:
error[Constants.INSTANCE_NUMBER] = instance_number
raise SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.MANDATORY_KEY_ERROR, error)
if self.common_api_handler is not None and self.common_api_handler.get_mandatory_checker() is not None and \
self.common_api_handler.get_mandatory_checker():
if self.common_api_handler.get_category_method().upper() == Constants.REQUEST_CATEGORY_CREATE:
if lookup:
if bool(primary_keys):
error = {
Constants.FIELD: member_name,
Constants.TYPE: request_instance.__module__,
Constants.KEYS: str(list(primary_keys.keys()))
}
if instance_number is not None:
error[Constants.INSTANCE_NUMBER] = instance_number
raise SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.MANDATORY_KEY_ERROR, error)
elif bool(required_keys):
error = {
Constants.FIELD: member_name,
Constants.TYPE: request_instance.__module__,
Constants.KEYS: str(list(required_keys.keys()))
}
if instance_number is not None:
error[Constants.INSTANCE_NUMBER] = instance_number
raise SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.MANDATORY_KEY_ERROR, error)
if self.common_api_handler.get_category_method().upper() == Constants.REQUEST_CATEGORY_UPDATE and \
bool(primary_keys):
error = {
Constants.FIELD: member_name,
Constants.TYPE: request_instance.__module__,
Constants.KEYS: str(list(primary_keys.keys()))
}
if instance_number is not None:
error[Constants.INSTANCE_NUMBER] = instance_number
raise SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.PRIMARY_KEY_ERROR, error)
elif lookup and self.common_api_handler is not None and self.common_api_handler.get_category_method().upper() == Constants.REQUEST_CATEGORY_UPDATE:
if bool(primary_keys):
error = {
Constants.FIELD: member_name,
Constants.TYPE: request_instance.__module__,
Constants.KEYS: str(list(primary_keys.keys()))
}
if instance_number is not None:
error[Constants.INSTANCE_NUMBER] = instance_number
raise SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.PRIMARY_KEY_ERROR, error)
return True
def set_data(self, member_detail, field_value):
if field_value is not None:
data_type = member_detail[Constants.TYPE]
if data_type == Constants.LIST_NAMESPACE:
return self.set_json_array(field_value, member_detail)
elif data_type == Constants.MAP_NAMESPACE:
return self.set_json_object(field_value, member_detail)
elif data_type == Constants.CHOICE_NAMESPACE or \
(Constants.STRUCTURE_NAME in member_detail and
member_detail[Constants.STRUCTURE_NAME] == Constants.CHOICE_NAMESPACE):
return field_value.get_value()
elif Constants.STRUCTURE_NAME in member_detail:
return self.form_request(field_value, member_detail[Constants.STRUCTURE_NAME], None, member_detail)
else:
return DataTypeConverter.post_convert(field_value, data_type)
return None
def set_json_object(self, field_value, member_detail):
json_object = {}
request_object = dict(field_value)
if len(request_object) > 0:
if member_detail is None or (member_detail is not None and Constants.KEYS not in member_detail):
for key, value in request_object.items():
json_object[key] = self.redirector_for_object_to_json(value)
else:
if Constants.KEYS in member_detail:
keys_detail = member_detail[Constants.KEYS]
for key_detail in keys_detail:
key_name = key_detail[Constants.NAME]
if key_name in request_object and request_object[key_name] is not None:
key_value = self.set_data(key_detail, request_object[key_name])
json_object[key_name] = key_value
return json_object
def set_json_array(self, field_value, member_detail):
json_array = []
request_objects = list(field_value)
if len(request_objects) > 0:
if member_detail is None or (member_detail is not None and Constants.STRUCTURE_NAME not in member_detail):
for request in request_objects:
json_array.append(self.redirector_for_object_to_json(request))
else:
pack = member_detail[Constants.STRUCTURE_NAME]
if pack == Constants.CHOICE_NAMESPACE:
for request in request_objects:
json_array.append(request.get_value())
else:
instance_count = 0
for request in request_objects:
json_array.append(self.form_request(request, pack, instance_count, member_detail))
instance_count += 1
return json_array
def redirector_for_object_to_json(self, request):
if isinstance(request, list):
return self.set_json_array(request, None)
elif isinstance(request, dict):
return self.set_json_object(request, None)
else:
return request
def get_wrapped_response(self, response, pack):
return None
def get_response(self, response, pack):
return None
def construct_private_member(self, class_name, member_name):
return '_' + class_name + '__' + member_name | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/util/form_data_converter.py | form_data_converter.py |
try:
import json
import platform
import urllib3
import logging
from zohosdk.src.com.zoho.util.api_http_connector import APIHTTPConnector
from zohosdk.src.com.zoho.util.constants import Constants
from zohosdk.src.com.zoho.util.api_response import APIResponse
from zohosdk.src.com.zoho.header_map import HeaderMap
from zohosdk.src.com.zoho.header import Header
from zohosdk.src.com.zoho.parameter_map import ParameterMap
from zohosdk.src.com.zoho.param import Param
from zohosdk.src.com.zoho.exception import SDKException
except Exception:
import json
import platform
import urllib3
import logging
from .api_http_connector import APIHTTPConnector
from .constants import Constants
from .api_response import APIResponse
from ..header_map import HeaderMap
from ..header import Header
from ..parameter_map import ParameterMap
from ..param import Param
from ..exception import SDKException
class CommonAPIHandler(object):
"""
This class to process the API request and its response.
Construct the objects that are to be sent as parameters or request body with the API.
The Request parameter, header and body objects are constructed here.
Process the response JSON and converts it to relevant objects in the library.
"""
logger = logging.getLogger('SDKLogger')
def __init__(self):
self.__api_path = None
self.__header = HeaderMap()
self.__param = ParameterMap()
self.__request = None
self.__http_method = None
self.__module_api_name = None
self.__content_type = None
self.__category_method = None
self.__mandatory_checker = None
def set_content_type(self, content_type):
"""
The method to set the Content Type
Parameters:
content_type(str): A string containing the Content Type
"""
self.__content_type = content_type
def set_api_path(self, api_path):
"""
The method to set the API Path
Parameters:
api_path(str) : A string containing the API Path
"""
self.__api_path = api_path
def add_param(self, param_instance, param_value):
"""
The method to add an API request parameter.
Parameters:
param_instance (Param) : A Param instance containing the API request parameter.
param_value (object) : An object containing the API request parameter value.
"""
if param_value is None:
return
if self.__param is None:
self.__param = ParameterMap()
self.__param.add(param_instance, param_value)
def add_header(self, header_instance, header_value):
"""
The method to add an API request header.
Parameters:
header_instance (Header) : A Header instance containing the API request header.
header_value (object) : An object containing the API request header value.
"""
if header_value is None:
return
if self.__header is None:
self.__header = HeaderMap()
self.__header.add(header_instance, header_value)
def set_param(self, param):
"""
The method to set the API request parameter map.
Parameters:
param(ParameterMap) : A ParameterMap class instance containing the API request parameters
"""
if param is None:
return
if self.__param.request_parameters is not None and self.__param.request_parameters:
self.__param.request_parameters.update(param.request_parameters)
else:
self.__param = param
def get_module_api_name(self):
"""
The method to get the Module API Name
Returns:
string: A string representing the Module API Name
"""
return self.__module_api_name
def set_module_api_name(self, module_api_name):
"""
The method to set the Module API Name
Parameters:
module_api_name(str): A string containing the Module API Name
"""
self.__module_api_name = module_api_name
def set_header(self, header):
"""
The method to set the API request header map.
Parameters:
header(HeaderMap): A HeaderMap class instance containing the API request headers
"""
if header is None:
return
if self.__header.request_headers is not None and self.__header.request_headers:
self.__header.request_headers.update(header.request_headers)
else:
self.__header = header
def set_request(self, request):
"""
The method to set the request instance.
Parameters:
request(object): An object containing the request body
"""
self.__request = request
def set_http_method(self, http_method):
"""
The method to set the HTTP Method
Parameters:
http_method(str): A string containing the HTTP method.
"""
self.__http_method = http_method
def api_call(self, class_name, encode_type):
"""
The method to construct API request and response details. To make the Zoho API calls.
Parameters:
class_name(str): A str containing the method return type.
encode_type(str): A str containing the expected API response content type.
Returns:
APIResponse: An instance of APIResponse representing the Zoho API response instance
Raises:
SDKException
"""
try:
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from ..initializer import Initializer
if Initializer.get_initializer() is None:
raise SDKException(code=Constants.SDK_UNINITIALIZATION_ERROR,
message=Constants.SDK_UNINITIALIZATION_MESSAGE)
connector = APIHTTPConnector()
try:
self.set_api_url(connector)
except SDKException as e:
CommonAPIHandler.logger.error(Constants.SET_API_URL_EXCEPTION + e.__str__())
raise e
except Exception as e:
sdk_exception = SDKException(cause=e)
CommonAPIHandler.logger.error(Constants.SET_API_URL_EXCEPTION + sdk_exception.__str__())
raise sdk_exception
connector.request_method = self.__http_method
connector.content_type = self.__content_type
if self.__header is not None and len(self.__header.request_headers) > 0:
connector.headers = self.__header.request_headers
if self.__param is not None and len(self.__param.request_parameters) > 0:
connector.parameters = self.__param.request_parameters
try:
Initializer.get_initializer().token.authenticate(connector)
except SDKException as e:
CommonAPIHandler.logger.info(Constants.AUTHENTICATION_EXCEPTION + e.__str__())
raise e
except Exception as e:
sdk_exception = SDKException(cause=e)
CommonAPIHandler.logger.error(Constants.AUTHENTICATION_EXCEPTION + sdk_exception.__str__())
raise sdk_exception
convert_instance = None
if self.__content_type is not None and \
self.__http_method in [Constants.REQUEST_METHOD_PATCH, Constants.REQUEST_METHOD_POST,
Constants.REQUEST_METHOD_PUT]:
try:
convert_instance = self.get_converter_class_instance(self.__content_type.lower())
request = convert_instance.form_request(self.__request, self.__request.__class__.__module__, None, None)
except SDKException as e:
CommonAPIHandler.logger.info(Constants.FORM_REQUEST_EXCEPTION + e.__str__())
raise e
except Exception as e:
sdk_exception = SDKException(cause=e)
CommonAPIHandler.logger.error(Constants.FORM_REQUEST_EXCEPTION + sdk_exception.__str__())
raise sdk_exception
connector.request_body = request
try:
connector.headers[
Constants.ZOHO_SDK] = platform.system() + "/" + \
platform.release() + "/python-2.1/" + platform.python_version() + ":" + \
Constants.SDK_VERSION
response = connector.fire_request(convert_instance)
return_object = None
if Constants.CONTENT_TYPE in response.headers:
content_type = response.headers[Constants.CONTENT_TYPE]
if ";" in content_type:
content_type = content_type.rpartition(";")[0]
convert_instance = self.get_converter_class_instance(str(content_type).lower())
return_object = convert_instance.get_wrapped_response(response, class_name)
else:
CommonAPIHandler.logger.info(response.__str__())
return APIResponse(response.headers, response.status_code, return_object)
except SDKException as e:
CommonAPIHandler.logger.info(Constants.API_CALL_EXCEPTION + e.__str__())
except Exception as e:
sdk_exception = SDKException(cause=e)
CommonAPIHandler.logger.error(Constants.API_CALL_EXCEPTION + sdk_exception.__str__())
raise sdk_exception
def get_converter_class_instance(self, encode_type):
try:
from zohosdk.src.com.zoho.util.json_converter import JSONConverter
from zohosdk.src.com.zoho.util.xml_converter import XMLConverter
from zohosdk.src.com.zoho.util.form_data_converter import FormDataConverter
from zohosdk.src.com.zoho.util.downloader import Downloader
except Exception:
from .json_converter import JSONConverter
from .xml_converter import XMLConverter
from .form_data_converter import FormDataConverter
from .downloader import Downloader
"""
This method to get a Converter class instance.
:param encode_type: A str containing the API response content type.
:return: A Converter class instance.
"""
switcher = {
"application/json": JSONConverter(self),
"text/plain": JSONConverter(self),
"application/ld+json": JSONConverter(self),
"application/xml": XMLConverter(self),
"text/xml": XMLConverter(self),
"multipart/form-data": FormDataConverter(self),
"application/x-download": Downloader(self),
"image/png": Downloader(self),
"image/jpeg": Downloader(self),
"image/gif": Downloader(self),
"image/tiff": Downloader(self),
"image/svg+xml": Downloader(self),
"image/bmp": Downloader(self),
"image/webp": Downloader(self),
"text/html": Downloader(self),
"text/css": Downloader(self),
"text/javascript": Downloader(self),
"text/calendar": Downloader(self),
"application/zip": Downloader(self),
"application/pdf": Downloader(self),
"application/java-archive": Downloader(self),
"application/javascript": Downloader(self),
"application/xhtml+xml": Downloader(self),
"application/x-bzip": Downloader(self),
"application/msword": Downloader(self),
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": Downloader(self),
"application/gzip": Downloader(self),
"application/x-httpd-php": Downloader(self),
"application/vnd.ms-powerpoint": Downloader(self),
"application/vnd.rar": Downloader(self),
"application/x-sh": Downloader(self),
"application/x-tar": Downloader(self),
"application/vnd.ms-excel": Downloader(self),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": Downloader(self),
"application/x-7z-compressed": Downloader(self),
"audio/mpeg": Downloader(self),
"audio/x-ms-wma": Downloader(self),
"audio/vnd.rn-realaudio": Downloader(self),
"audio/x-wav": Downloader(self),
"audio/3gpp": Downloader(self),
"audio/3gpp2": Downloader(self),
"video/mpeg": Downloader(self),
"video/mp4": Downloader(self),
"video/webm": Downloader(self),
"video/3gpp": Downloader(self),
"video/3gpp2": Downloader(self),
"font/ttf": Downloader(self),
"text/csv": Downloader(self),
"application/octet-stream": Downloader(self),
}
return switcher.get(encode_type, None)
def set_api_url(self, connector):
try:
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from ..initializer import Initializer
api_path = ''
if Constants.HTTP in self.__api_path:
if Constants.CONTENT_API_URL in self.__api_path:
api_path = Initializer.get_initializer().environment.file_upload_url
try:
url_parse = urllib3.util.parse_url(self.__api_path)
path = url_parse.path
except Exception as ex:
raise SDKException(code=Constants.INVALID_URL_ERROR, cause=ex)
api_path = api_path + path
else:
if str(self.__api_path)[:1].__eq__('/'):
self.__api_path = self.__api_path[1:]
api_path = api_path + self.__api_path
else:
api_path = Initializer.get_initializer().environment.url
api_path = api_path + self.__api_path
connector.url = api_path
def get_mandatory_checker(self):
"""
The method to get the Mandatory Checker
Returns:
bool: A boolean representing the Mandatory Checker.
"""
return self.__mandatory_checker
def set_mandatory_checker(self, mandatory_checker):
"""
The method to set the Mandatory Checker
Parameters:
mandatory_checker(bool): A boolean containing the Mandatory Checker.
"""
self.__mandatory_checker = mandatory_checker
def get_http_method(self):
"""
The method to get the HTTP Method
Returns:
string: A string representing the HTTP Method
"""
return self.__http_method
def get_category_method(self):
"""
The method to get the Category Method
Returns:
string: A string representing the Category method.
"""
return self.__category_method
def set_category_method(self, category_method):
"""
The method to set the Category Method
Parameters:
category_method(str): A string containing the Category method.
"""
self.__category_method = category_method
def get_api_path(self):
"""
The method to get the API Path
Returns:
string: A string representing the API Path
"""
return self.__api_path | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/util/common_api_handler.py | common_api_handler.py |
try:
import logging
import threading
import datetime
import time
import os
import json
import zlib
import base64
import re
from zohosdk.src.com.zoho.initializer import Initializer
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.header_map import HeaderMap
except Exception:
import logging
import threading
import os
import json
import time
import datetime
import zlib
import base64
import re
from ..initializer import Initializer
from ..exception import SDKException
from ..header_map import HeaderMap
class Utility(object):
"""
This class handles module field details.
"""
@staticmethod
def search_json_details(key):
try:
from zohosdk.src.com.zoho.util import Constants
except Exception:
from .constants import Constants
package_name = Constants.PACKAGE_NAMESPACE + 'record.' + key
from zohosdk.src.com.zoho.initializer import Initializer
for class_key in Initializer.json_details.keys():
if class_key == package_name:
return_json = {
Constants.MODULEPACKAGENAME: class_key,
Constants.MODULEDETAILS: Initializer.json_details[class_key]
}
return return_json
return None
@staticmethod
def get_json_object(json, key):
for key_in_json in json.keys():
if key_in_json.lower() == key.lower():
return json[key_in_json]
return None
@staticmethod
def check_data_type(value, type):
try:
from zohosdk.src.com.zoho.util import Constants
except Exception:
from .constants import Constants
if value is None:
return False
if type.lower() == Constants.OBJECT.lower():
return True
type = Constants.DATA_TYPE.get(type)
class_name = value.__class__
if class_name == type:
return True
else:
return False | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/util/utility.py | utility.py |
try:
import importlib
import logging
import re
import json
from zohosdk.src.com.zoho.util import Converter, Constants, JSONConverter
except Exception:
import importlib
import logging
import re
from .converter import Converter
from .constants import Constants
from .json_converter import JSONConverter
class Downloader(Converter):
"""
This class to process the download file and stream response.
"""
logger = logging.getLogger('SDKLogger')
def __init__(self, common_api_handler):
super().__init__(common_api_handler)
self.unique_dict = {}
self.common_api_handler = common_api_handler
def form_request(self, request_instance, pack, instance_number, class_member_detail):
return None
def append_to_request(self, request_base, request_object):
return
def get_wrapped_response(self, response, pack):
return self.get_response(response, pack)
def get_response(self, response, pack):
try:
from zohosdk.src.com.zoho import Initializer
except Exception:
from ..initializer import Initializer
path_split = str(pack).rpartition(".")
class_name = self.module_to_class(path_split[-1])
pack = path_split[0] + "." + class_name
class_detail = dict(Initializer.json_details[str(pack)])
if Constants.INTERFACE in class_detail and class_detail[Constants.INTERFACE] is not None:
classes = class_detail[Constants.CLASSES]
for each_class in classes:
if Constants.FILE_BODY_WRAPPER in each_class:
return self.get_response(response, each_class)
else:
instance = self.get_class(class_name, path_split[0])()
for member_name, member_detail in class_detail.items():
data_type = member_detail[Constants.TYPE]
instance_value = None
if data_type == Constants.STREAM_WRAPPER_CLASS_PATH:
file_name = ''
content_disposition = response.headers[Constants.CONTENT_DISPOSITION]
if "'" in content_disposition:
start_index = content_disposition.rindex("'")
file_name = content_disposition[start_index + 1:]
elif '"' in content_disposition:
start_index = content_disposition.rindex('=')
file_name = content_disposition[start_index + 1:].replace('"', '')
stream_path_split = str(data_type).rpartition(".")
stream_class_name = self.module_to_class(stream_path_split[-1])
instance_value = self.get_class(stream_class_name, stream_path_split[0])(file_name, response)
setattr(instance,
self.construct_private_member(class_name=class_name, member_name=member_name), instance_value)
return instance
@staticmethod
def construct_private_member(class_name, member_name):
return '_' + class_name + '__' + member_name
@staticmethod
def get_class(class_name, class_path):
imported_module = importlib.import_module(class_path)
class_holder = getattr(imported_module, class_name)
return class_holder | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/util/downloader.py | downloader.py |
try:
import os
import re
import json
from zohosdk.src.com.zoho.util.datatype_converter import DataTypeConverter
from zohosdk.src.com.zoho.exception import SDKException
from zohosdk.src.com.zoho.util.constants import Constants
except Exception:
import os
import re
import json
from .datatype_converter import DataTypeConverter
from ..exception import SDKException
from .constants import Constants
class HeaderParamValidator(object):
"""
This class validates the Header and Parameter values with the type accepted by the APIs.
"""
def validate(self, name, class_name, value):
json_details = self.get_json_details()
json_class_name = self.get_file_name(class_name)
type_detail = None
if json_class_name in json_details:
type_detail = self.get_key_json_details(name, json_details[json_class_name])
if type_detail is not None:
try:
from zohosdk.src.com.zoho.util.utility import Utility
except Exception:
from ..util.utility import Utility
if not Utility.check_data_type(value, type_detail[Constants.TYPE]):
param_or_header = 'PARAMETER' if json_class_name is not None and json_class_name.endswith('Param') else 'HEADER'
error_details = {
param_or_header: name,
Constants.CLASS: json_class_name,
Constants.ACCEPTED_TYPE: Constants.DATA_TYPE.get(type_detail[Constants.TYPE]).__name__ if type_detail[Constants.TYPE] in Constants.DATA_TYPE else type_detail[Constants.TYPE]
}
raise SDKException(code=Constants.TYPE_ERROR, details=error_details)
if Constants.STRUCTURE_NAME in type_detail:
try:
from zohosdk.src.com.zoho.util.json_converter import JSONConverter
except Exception:
from .json_converter import JSONConverter
return JSONConverter(None).form_request(value, type_detail[Constants.TYPE], None, None)
return self.parse_data(value, type_detail[Constants.TYPE])
return DataTypeConverter.post_convert(value, type_detail[Constants.TYPE])
def parse_data(self, value, type):
if type == Constants.MAP_NAMESPACE:
json_object = {}
request_object = dict(value)
if len(request_object) > 0:
for key, field_value in request_object.items():
json_object[key] = self.parse_data(field_value, type)
return json_object
elif type == Constants.LIST_NAMESPACE:
json_array = []
request_objects = list(value)
if len(request_objects) > 0:
for request_object in request_objects:
json_array.append(self.parse_data(request_object, type))
return json_array
else:
DataTypeConverter.post_convert(value, type)
def get_key_json_details(self, name, json_details):
for key_name in json_details.keys():
detail = json_details[key_name]
if Constants.NAME in detail:
if detail[Constants.NAME].lower() == name.lower():
return detail
def get_file_name(self, name):
sdk_name = 'zohosdk.src.'
name_split = str(name).split('.')
class_name = name_split.pop()
package_name = name_split.pop()
pack_split = re.findall('[A-Z][^A-Z]*', package_name)
sdk_package_name = pack_split[0].lower()
if len(pack_split) > 1:
for i in range(1, len(pack_split)):
sdk_package_name += '_' + pack_split[i].lower()
name_split = list(map(lambda x: x.lower(), name_split))
sdk_name = sdk_name + '.'.join(name_split) + '.' + sdk_package_name + '.' + class_name
return sdk_name
def get_json_details(self):
try:
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from ..initializer import Initializer
if Initializer.json_details is None:
dir_name = os.path.dirname(__file__)
filename = os.path.join(dir_name, '..', '..', '..', '..', '..', Constants.JSON_DETAILS_FILE_PATH)
with open(filename, mode='r') as JSON:
Initializer.json_details = json.load(JSON)
return Initializer.json_details | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/util/header_param_validator.py | header_param_validator.py |
try:
import requests
import logging
import json
from zohosdk.src.com.zoho.util.constants import Constants
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from .constants import Constants
import requests
import logging
import json
from ..initializer import Initializer
class APIHTTPConnector(object):
"""
This module is to make HTTP connections, trigger the requests and receive the response.
"""
def __init__(self):
"""
Creates an APIHTTPConnector class instance with the specified parameters.
"""
self.url = None
self.request_method = None
self.headers = dict()
self.parameters = dict()
self.request_body = None
self.content_type = None
self.file = False
def add_header(self, header_name, header_value):
"""
The method to add API request header name and value.
Parameters:
header_name (str) : A String containing the API request header name.
header_value (str) : A String containing the API request header value.
"""
self.headers[header_name] = header_value
def add_param(self, param_name, param_value):
"""
The method to add API request parameter name and value.
Parameters:
param_name (str) : A String containing the API request parameter name.
param_value (str) : A String containing the API request parameter value.
"""
self.parameters[param_name] = param_value
def fire_request(self, converter_instance):
"""
This method makes a request to the Zoho Rest API
Parameters:
converter_instance (Converter) : A Converter class instance to call append_to_request method.
Returns:
requests.Response : An object of requests.Response
"""
response = None
proxies = None
logger = logging.getLogger('SDKLogger')
initializer = Initializer.get_initializer()
sdk_config = initializer.sdk_config
read_timeout = sdk_config.get_read_timeout()
connect_timeout = sdk_config.get_connect_timeout()
if read_timeout is None and connect_timeout is None:
timeout = None
elif read_timeout is None:
timeout = connect_timeout
elif connect_timeout is None:
timeout = read_timeout
else:
timeout = (connect_timeout, read_timeout)
# if self.content_type is not None:
# self.headers[Constants.CONTENT_TYPE_HEADER] = self.content_type
if initializer.request_proxy is not None:
request_proxy = initializer.request_proxy
auth = ""
if request_proxy is not None:
auth = request_proxy.get_user() + ':' + request_proxy.get_password() + '@'
if Constants.HTTP in request_proxy.get_host():
host_split = request_proxy.get_host().split('://')
scheme = host_split[0]
proxies = {
scheme: scheme + '://' + auth + host_split[1] + ':' + str(request_proxy.get_port())
}
else:
proxies = {
Constants.HTTP: Constants.HTTP + '://' + auth + request_proxy.get_host() + ':' + str(
request_proxy.get_port()),
Constants.HTTPS: Constants.HTTPS + '://' + auth + request_proxy.get_host() + ':' + str(
request_proxy.get_port())
}
logger.info(self.proxy_log(request_proxy))
logger.info(self.__str__())
if self.request_method == Constants.REQUEST_METHOD_GET:
response = requests.get(url=self.url, headers=self.headers, params=self.parameters, allow_redirects=False,
proxies=proxies, timeout=timeout)
elif self.request_method == Constants.REQUEST_METHOD_PUT:
data = None
if self.request_body is not None:
data = converter_instance.append_to_request(self, self.request_body)
response = requests.put(url=self.url, data=data, params=self.parameters, headers=self.headers,
allow_redirects=False, proxies=proxies)
elif self.request_method == Constants.REQUEST_METHOD_POST:
data = None
if self.request_body is not None:
data = converter_instance.append_to_request(self, self.request_body)
if self.file:
response = requests.post(url=self.url, files=data, params=self.parameters, headers=self.headers, allow_redirects=False, data={},
proxies=proxies)
else:
response = requests.post(url=self.url, data=data, params=self.parameters, headers=self.headers,
allow_redirects=False, proxies=proxies)
elif self.request_method == Constants.REQUEST_METHOD_PATCH:
data = None
if self.request_body is not None:
data = converter_instance.append_to_request(self, self.request_body)
response = requests.patch(url=self.url, data=data, headers=self.headers, params=self.parameters,
allow_redirects=False, proxies=proxies)
elif self.request_method == Constants.REQUEST_METHOD_DELETE:
response = requests.delete(url=self.url, headers=self.headers, params=self.parameters,
allow_redirects=False, proxies=proxies)
return response
def __str__(self):
request_headers = self.headers.copy()
request_headers[Constants.AUTHORIZATION] = Constants.CANT_DISCLOSE
return self.request_method + ' - ' + Constants.URL + ' = ' + self.url + ' , ' + Constants.HEADERS + ' = ' + \
json.dumps(request_headers) \
+ ' , ' + Constants.PARAMS + ' = ' + json.dumps(self.parameters) + '.'
@staticmethod
def proxy_log(request_proxy):
proxy_details = Constants.PROXY_SETTINGS + Constants.PROXY_HOST + str(
request_proxy.get_host()) + ', ' + Constants.PROXY_PORT + str(request_proxy.get_port())
if request_proxy.user is not None:
proxy_details = proxy_details + ', ' + Constants.PROXY_USER + str(request_proxy.get_user())
return proxy_details | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/util/api_http_connector.py | api_http_connector.py |
try:
import importlib
import re
import json
from zohosdk.src.com.zoho.util import Converter, DataTypeConverter, Constants
from zohosdk.src.com.zoho.exception.sdk_exception import SDKException
except Exception:
import importlib
import re
from ..exception import SDKException
from .constants import Constants
from .datatype_converter import DataTypeConverter
from .converter import Converter
class JSONConverter(Converter):
"""
This class processes the API response to the object and an object to a JSON object, containing the request body.
"""
def __init__(self, common_api_handler):
super().__init__(common_api_handler)
self.unique_dict = {}
self.common_api_handler = common_api_handler
def append_to_request(self, request_base, request_object):
return json.dumps(request_object).encode('utf-8')
def form_request(self, request_instance, pack, instance_number, class_member_detail):
path_split = str(pack).rpartition(".")
class_name = self.module_to_class(path_split[-1])
pack = path_split[0] + "." + class_name
try:
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from ..initializer import Initializer
class_detail = dict(Initializer.json_details[str(pack)])
if Constants.INTERFACE in class_detail and class_detail[Constants.INTERFACE] is not None:
request_object_class_name = request_instance.__class__.__module__
request_object_class_name = str(request_object_class_name)
path_split = str(request_object_class_name).rpartition(".")
request_class_name = self.module_to_class(path_split[-1])
request_object_class_name = path_split[0] + "." + request_class_name
classes = class_detail[Constants.CLASSES]
for class_name in classes:
class_name_interface_lower = str(class_name).lower()
request_class_path_lower = request_object_class_name.lower()
if class_name_interface_lower == request_class_path_lower:
class_detail = dict(Initializer.json_details[str(class_name)])
class_name = str(class_name).rpartition(".")
class_name = self.module_to_class(class_name[-1])
break
return self.is_not_record_request(request_instance, class_name, class_detail,
instance_number, class_member_detail)
def is_not_record_request(self, request_instance, class_name, class_detail, instance_number, class_member_detail):
lookup = False
skip_mandatory = False
class_member_name = None
if class_member_detail is not None:
lookup = class_member_detail[Constants.LOOKUP] if Constants.LOOKUP in class_member_detail else False
skip_mandatory = class_member_detail[Constants.SKIP_MANDATORY] \
if Constants.SKIP_MANDATORY in class_member_detail else False
class_member_name = class_member_detail[Constants.NAME]
request_json = {}
required_keys, primary_keys, required_in_update_keys = {}, {}, {}
for member_name, member_detail in class_detail.items():
if ((Constants.WRITE_ONLY in member_detail and not bool(
member_detail[Constants.WRITE_ONLY])) and (Constants.UPDATE_ONLY in member_detail and not bool(
member_detail[Constants.UPDATE_ONLY])) and (Constants.READ_ONLY in member_detail and bool(
member_detail[Constants.READ_ONLY]))) or (Constants.NAME not in member_detail):
continue
key_name = member_detail[Constants.NAME]
try:
modification = getattr(request_instance, Constants.IS_KEY_MODIFIED)(key_name)
except Exception as e:
raise SDKException(code=Constants.EXCEPTION_IS_KEY_MODIFIED, cause=e)
if Constants.REQUIRED in member_detail and member_detail[Constants.REQUIRED]:
required_keys[key_name] = True
if Constants.PRIMARY in member_detail and member_detail[Constants.PRIMARY] and \
(Constants.REQUIRED_IN_UPDATE not in member_detail or member_detail[Constants.REQUIRED_IN_UPDATE]):
primary_keys[key_name] = True
if Constants.REQUIRED_IN_UPDATE in member_detail and member_detail[Constants.REQUIRED_IN_UPDATE]:
required_in_update_keys[key_name] = True
field_value = None
if modification is not None and modification != 0:
field_value = getattr(request_instance,
self.construct_private_member(class_name=class_name, member_name=member_name))
if self.value_checker(class_name=class_name, member_name=member_name, key_details=member_detail,
value=field_value, unique_values_map=self.unique_dict,
instance_number=instance_number) is True:
if field_value is not None:
required_keys.pop(key_name, None)
primary_keys.pop(key_name, None)
required_in_update_keys.pop(key_name, None)
request_json[key_name] = self.set_data(member_detail, field_value)
if skip_mandatory or self.check_exception(class_member_name, request_instance, instance_number,
lookup, required_keys, primary_keys, required_in_update_keys) is True:
return request_json
def check_exception(self, member_name, request_instance, instance_number,
lookup, required_keys, primary_keys, required_in_update_keys):
if bool(required_in_update_keys) and self.common_api_handler is not None and self.common_api_handler.get_category_method() is not None and \
self.common_api_handler.get_category_method().upper() == Constants.REQUEST_CATEGORY_UPDATE:
error = {
Constants.FIELD: member_name,
Constants.TYPE: request_instance.__module__,
Constants.KEYS: str(list(required_in_update_keys.keys()))
}
if instance_number is not None:
error[Constants.INSTANCE_NUMBER] = instance_number
raise SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.MANDATORY_KEY_ERROR, error)
if self.common_api_handler is not None and self.common_api_handler.get_mandatory_checker() is not None and \
self.common_api_handler.get_mandatory_checker():
if self.common_api_handler.get_category_method().upper() == Constants.REQUEST_CATEGORY_CREATE:
if lookup:
if bool(primary_keys):
error = {
Constants.FIELD: member_name,
Constants.TYPE: request_instance.__module__,
Constants.KEYS: str(list(primary_keys.keys()))
}
if instance_number is not None:
error[Constants.INSTANCE_NUMBER] = instance_number
raise SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.MANDATORY_KEY_ERROR, error)
elif bool(required_keys):
error = {
Constants.FIELD: member_name,
Constants.TYPE: request_instance.__module__,
Constants.KEYS: str(list(required_keys.keys()))
}
if instance_number is not None:
error[Constants.INSTANCE_NUMBER] = instance_number
raise SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.MANDATORY_KEY_ERROR, error)
if self.common_api_handler.get_category_method().upper() == Constants.REQUEST_CATEGORY_UPDATE and \
bool(primary_keys):
error = {
Constants.FIELD: member_name,
Constants.TYPE: request_instance.__module__,
Constants.KEYS: str(list(primary_keys.keys()))
}
if instance_number is not None:
error[Constants.INSTANCE_NUMBER] = instance_number
raise SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.PRIMARY_KEY_ERROR, error)
elif lookup and self.common_api_handler is not None and self.common_api_handler.get_category_method().upper() == Constants.REQUEST_CATEGORY_UPDATE:
if bool(primary_keys):
error = {
Constants.FIELD: member_name,
Constants.TYPE: request_instance.__module__,
Constants.KEYS: str(list(primary_keys.keys()))
}
if instance_number is not None:
error[Constants.INSTANCE_NUMBER] = instance_number
raise SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.PRIMARY_KEY_ERROR, error)
return True
def set_data(self, member_detail, field_value):
if field_value is not None:
data_type = member_detail[Constants.TYPE]
if data_type == Constants.LIST_NAMESPACE:
return self.set_json_array(field_value, member_detail)
elif data_type == Constants.MAP_NAMESPACE:
return self.set_json_object(field_value, member_detail)
elif data_type == Constants.CHOICE_NAMESPACE or \
(Constants.STRUCTURE_NAME in member_detail and
member_detail[Constants.STRUCTURE_NAME] == Constants.CHOICE_NAMESPACE):
return field_value.get_value()
elif Constants.STRUCTURE_NAME in member_detail:
return self.form_request(field_value, member_detail[Constants.STRUCTURE_NAME], None, member_detail)
else:
return DataTypeConverter.post_convert(field_value, data_type)
return None
def set_json_object(self, field_value, member_detail):
json_object = {}
request_object = dict(field_value)
if len(request_object) > 0:
if member_detail is None or (member_detail is not None and Constants.KEYS not in member_detail):
for key, value in request_object.items():
json_object[key] = self.redirector_for_object_to_json(value)
else:
if Constants.KEYS in member_detail:
keys_detail = member_detail[Constants.KEYS]
for key_detail in keys_detail:
key_name = key_detail[Constants.NAME]
if key_name in request_object and request_object[key_name] is not None:
key_value = self.set_data(key_detail, request_object[key_name])
json_object[key_name] = key_value
return json_object
def set_json_array(self, field_value, member_detail):
json_array = []
request_objects = list(field_value)
if len(request_objects) > 0:
if member_detail is None or (member_detail is not None and Constants.STRUCTURE_NAME not in member_detail):
for request in request_objects:
json_array.append(self.redirector_for_object_to_json(request))
else:
pack = member_detail[Constants.STRUCTURE_NAME]
if pack == Constants.CHOICE_NAMESPACE:
for request in request_objects:
json_array.append(request.get_value())
else:
instance_count = 0
for request in request_objects:
json_array.append(self.form_request(request, pack, instance_count, member_detail))
instance_count += 1
return json_array
def redirector_for_object_to_json(self, request):
if isinstance(request, list):
return self.set_json_array(request, None)
elif isinstance(request, dict):
return self.set_json_object(request, None)
else:
return request
def get_wrapped_response(self, response, pack):
try:
return self.get_response(response.json(), pack)
except ValueError:
return None
def get_response(self, response, package_name):
try:
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from ..initializer import Initializer
if response is None or response == '' or response == "None" or response == "null":
return None
response_json = dict(response)
path_split = str(package_name).rpartition(".")
class_name = self.module_to_class(path_split[-1])
package_name = path_split[0] + "." + class_name
class_detail = dict(Initializer.json_details[str(package_name)])
instance = None
if Constants.INTERFACE in class_detail and class_detail[Constants.INTERFACE] is not None:
classes = class_detail[Constants.CLASSES]
instance = self.find_match(classes, response_json)
else:
imported_module = importlib.import_module(path_split[0])
class_holder = getattr(imported_module, class_name)
instance = class_holder()
instance = self.not_record_response(instance=instance, class_name=class_name,
response_json=response_json, class_detail=class_detail)
return instance
def not_record_response(self, instance, class_name, response_json, class_detail):
for member_name, key_detail in class_detail.items():
key_name = key_detail[Constants.NAME] if Constants.NAME in key_detail else None
if key_name is not None and key_name in response_json and response_json.get(key_name) is not None:
key_data = response_json[key_name]
member_value = self.get_data(key_data, key_detail)
setattr(instance, self.construct_private_member(class_name=class_name, member_name=member_name),
member_value)
return instance
def get_data(self, key_data, member_detail):
member_value = None
if key_data is not None:
data_type = member_detail.get(Constants.TYPE)
if data_type == Constants.LIST_NAMESPACE:
member_value = self.get_collections_data(key_data, member_detail)
elif data_type == Constants.MAP_NAMESPACE:
member_value = self.get_map_data(key_data, member_detail)
elif data_type == Constants.CHOICE_NAMESPACE or (
Constants.STRUCTURE_NAME in member_detail
and member_detail[Constants.STRUCTURE_NAME] == Constants.CHOICE_NAMESPACE):
member_value = self.__get_choice_instance(key_data)
elif Constants.STRUCTURE_NAME in member_detail:
member_value = self.get_response(key_data, member_detail[Constants.STRUCTURE_NAME])
else:
member_value = DataTypeConverter.pre_convert(key_data, data_type)
return member_value
def get_map_data(self, response, member_detail):
map_instance = {}
if len(response) > 0:
if member_detail is None or (member_detail is not None and Constants.KEYS not in member_detail):
for key, value in response.items():
map_instance[key] = self.redirector_for_json_to_object(value)
else:
if Constants.KEYS in member_detail:
keys_detail = member_detail[Constants.KEYS]
for key_detail in keys_detail:
key_name = key_detail[Constants.NAME]
if key_name in response and response[key_name] is not None:
key_value = self.get_data(response[key_name], key_detail)
map_instance[key_name] = key_value
return map_instance
def get_collections_data(self, responses, member_detail):
values = []
if len(responses) > 0:
if member_detail is None or (member_detail is not None and Constants.STRUCTURE_NAME not in member_detail):
for response in responses:
values.append(self.redirector_for_json_to_object(response))
else:
pack = member_detail[Constants.STRUCTURE_NAME]
if pack == Constants.CHOICE_NAMESPACE:
for response in responses:
values.append(self.__get_choice_instance(response))
else:
for response in responses:
values.append(self.get_response(response, pack))
return values
def redirector_for_json_to_object(self, key_data):
if isinstance(key_data, dict):
return self.get_map_data(key_data, None)
elif isinstance(key_data, list):
return self.get_collections_data(key_data, None)
else:
return key_data
def find_match(self, classes, response_json):
pack = ""
ratio = 0
for class_name in classes:
match_ratio = self.find_ratio(class_name, response_json)
if match_ratio == 1.0:
pack = class_name
ratio = 1
break
elif match_ratio > ratio:
ratio = match_ratio
pack = class_name
return self.get_response(response_json, pack)
def find_ratio(self, class_name, response_json):
try:
from zohosdk.src.com.zoho.initializer import Initializer
except Exception:
from ..initializer import Initializer
class_detail = dict(Initializer.json_details[str(class_name)])
total_points = len(class_detail.keys())
matches = 0
if total_points == 0:
return
else:
for member_name in class_detail:
member_detail = class_detail[member_name]
key_name = member_detail[Constants.NAME] if Constants.NAME in member_detail else None
if key_name is not None and key_name in response_json and response_json.get(key_name) is not None:
key_data = response_json[key_name]
data_type = type(key_data).__name__
structure_name = member_detail[
Constants.STRUCTURE_NAME] if Constants.STRUCTURE_NAME in member_detail else None
if isinstance(key_data, dict):
data_type = Constants.MAP_NAMESPACE
if isinstance(key_data, list):
data_type = Constants.LIST_NAMESPACE
if data_type == member_detail[Constants.TYPE] or (
member_detail[Constants.TYPE] in Constants.DATA_TYPE and
isinstance(key_data, Constants.DATA_TYPE.get(member_detail[Constants.TYPE]))):
matches += 1
elif key_name.lower() == Constants.COUNT.lower() and \
member_detail[Constants.TYPE].lower() == Constants.LONG_NAMESPACE.lower():
matches += 1
elif member_detail[Constants.TYPE] == Constants.CHOICE_NAMESPACE:
values = list(member_detail[Constants.VALUES])
for value in values:
if value == key_data:
matches += 1
break
if structure_name is not None and structure_name == member_detail[Constants.TYPE]:
if Constants.VALUES in member_detail:
for value in member_detail[Constants.VALUES]:
if value == key_data:
matches += 1
break
else:
matches += 1
return matches / total_points
def build_name(self, key_name):
name_split = str(key_name).split('_')
sdk_name = name_split[0].lower()
if len(name_split) > 1:
for i in range(1, len(name_split)):
if len(name_split[i]) > 0:
sdk_name += '_' + name_split[i].lower()
return sdk_name
@staticmethod
def __get_instance_from_name(class_path):
path_split = str(class_path).rpartition('.')
imported_module = importlib.import_module(path_split[0])
class_holder = getattr(imported_module, path_split[-1])
return class_holder()
def construct_private_member(self, class_name, member_name):
return '_' + class_name + '__' + member_name
def __get_choice_instance(self, data):
choice_split = Constants.CHOICE_NAMESPACE.rpartition('.')
imported_module = importlib.import_module(choice_split[0])
class_holder = getattr(imported_module, choice_split[-1])
choice_instance = class_holder(data)
return choice_instance | zoi-python-sdk | /zoi-python-sdk-1.0.1.tar.gz/zoi-python-sdk-1.0.1/zohosdk/src/com/zoho/util/json_converter.py | json_converter.py |
import os
import logging
import tempfile
import paramiko
class Connection(object):
"""Connects and logs into the specified hostname.
Arguments that are not given are guessed from the environment."""
def __init__(self,
host,
username = None,
private_key = None,
password = None,
port = 22,
):
self.log = logging.getLogger("zoinksftp.ssh.Connection")
self._sftp_live = False
self._sftp = None
if not username:
username = os.environ['LOGNAME']
# Log to a temporary file.
templog = tempfile.mkstemp('.txt', 'ssh-')[1]
paramiko.util.log_to_file(templog)
# Begin the SSH transport.
self._transport = paramiko.Transport((host, port))
self._tranport_live = True
# Authenticate the transport.
if password:
# Using Password.
self._transport.connect(username = username, password = password)
else:
# Use Private Key.
if not private_key:
# Try to use default key.
if os.path.exists(os.path.expanduser('~/.ssh/id_rsa')):
private_key = '~/.ssh/id_rsa'
elif os.path.exists(os.path.expanduser('~/.ssh/id_dsa')):
private_key = '~/.ssh/id_dsa'
else:
raise TypeError, "You have not specified a password or key."
private_key_file = os.path.expanduser(private_key)
rsa_key = paramiko.RSAKey.from_private_key_file(private_key_file)
self._transport.connect(username = username, pkey = rsa_key)
def _sftp_connect(self):
"""Establish the SFTP connection."""
if not self._sftp_live:
self._sftp = paramiko.SFTPClient.from_transport(self._transport)
self._sftp_live = True
def get(self, remotepath, localpath = None):
"""Copies a file between the remote host and the local host."""
if not localpath:
localpath = os.path.split(remotepath)[1]
self._sftp_connect()
self._sftp.get(remotepath, localpath)
def getdir(self, remotepath, localpath = None):
"""Copies and entire directory from remote to local.
Based on what is seen by listdir.
This does not recurse through a directory tree currently. If
a directory is encountered then you'll see and unable to recover
error message.
"""
if not localpath:
localpath = os.path.abspath(os.curdir)
self._sftp_connect()
for i in self._sftp.listdir(remotepath):
try:
self._sftp.get("%s/%s" % (remotepath,i), "%s/%s" % (localpath,i))
except IOError,e:
self.log.warn("unable to recover item '%s'" % i)
def put(self, localpath, remotepath = None):
"""Copies a file between the local host and the remote host."""
if not remotepath:
remotepath = os.path.split(localpath)[1]
self._sftp_connect()
self._sftp.put(localpath, remotepath)
def execute(self, command):
"""Execute the given commands on a remote machine."""
channel = self._transport.open_session()
channel.exec_command(command)
output = channel.makefile('rb', -1).readlines()
if output:
return output
else:
return channel.makefile_stderr('rb', -1).readlines()
def close(self):
"""Closes the connection and cleans up."""
# Close SFTP Connection.
if self._sftp_live:
self._sftp.close()
self._sftp_live = False
# Close the SSH Transport.
if self._tranport_live:
self._transport.close()
self._tranport_live = False
def __del__(self):
"""Attempt to clean up if not explicitly closed."""
try:
self.close()
except AttributeError, e:
# Usually raised if close was called before this was
# garbage collected.
pass | zoink-sftp | /zoink-sftp-0.1.0.tar.gz/zoink-sftp-0.1.0/lib/zoinksftp/ssh.py | ssh.py |
Zoinks<img width="10%" align="right" src="https://github.com/mhucka/zoinks/raw/main/.graphics/zoinks-icon.png">
======
Zoinks (_**Zo**tero **in**formation quic**k** **s**earch_) is a command-line utility that returns the values of selected fields of a bibliographic record given a Zotero select link, an item key, or even the path to a file attachment in your Zotero database.
[](https://choosealicense.com/licenses/bsd-3-clause)
[](https://github.com/mhucka/zoinks/releases)
Table of contents
-----------------
* [Introduction](#introduction)
* [Installation](#installation)
* [Usage](#usage)
* [Known issues and limitations](#known-issues-and-limitations)
* [Getting help](#getting-help)
* [Contributing](#contributing)
* [License](#license)
* [Acknowledgments](#authors-and-acknowledgments)
Introduction
------------
> "Shaggy has a characteristic speech pattern, marked by his frequent use of the filler word "like" and, when startled, his exclamations of "**Zoinks**!" — _from the Wikipedia entry for [Shaggy Rogers](https://en.wikipedia.org/wiki/Shaggy_Rogers), retrieved on 2020-12-15. An [archived copy](https://web.archive.org/web/20201112011139/https://en.wikipedia.org/wiki/Shaggy_Rogers) is available in the Wayback Machine._
When using [Zotero](https://zotero.org) in scripts and other software, you may need a way to retrieve information about bibliographic entries without searching for them in Zotero itself. _Zoinks_ (a loose acronym for _**Zo**tero **in**formation quic**k **s**earch_) is a program that lets you do this from the command line.
Zoinks is a companion to [Zowie](https://github.com/mhucka/zowie), a command-line application that writes Zotero select links into PDF files to make them accessible outside of Zotero.
Installation
------------
[... forthcoming ...]
Usage
-----
[... forthcoming ...]
Known issues and limitations
----------------------------
[... forthcoming ...]
Getting help
------------
If you find an issue, please submit it in [the GitHub issue tracker](https://github.com/mhucka/zoinks/issues) for this repository.
Contributing
------------
I would be happy to receive your help and participation if you are interested. Everyone is asked to read and respect the [code of conduct](CONDUCT.md) when participating in this project. Development generally takes place on the `development` branch.
License
-------
This software is Copyright (C) 2022, by Michael Hucka and the California Institute of Technology (Pasadena, California, USA). This software is freely distributed under a 3-clause BSD type license. Please see the [LICENSE](LICENSE) file for more information.
Acknowledgments
---------------
This work is a personal project developed by the author, using computing facilities and other resources of the [California Institute of Technology Library](https://www.library.caltech.edu).
The [vector artwork](https://thenounproject.com/term/surprise/2696259/) of a surprised person, used as the icon for this repository, was created by [Adrien Coquet](https://thenounproject.com/coquet_adrien/) from the Noun Project. It is licensed under the Creative Commons [CC-BY 3.0](https://creativecommons.org/licenses/by/3.0/) license.
| zoinks | /zoinks-0.0.5.tar.gz/zoinks-0.0.5/README.md | README.md |
      
# Zoish
Zoish is a Python package that simplifies the machine learning process by using SHAP values for feature importance. It integrates with a range of machine learning models, provides feature selection to enhance performance, and improves model interpretability. With Zoish, users can also visualize feature importance through SHAP summary and bar plots, creating an efficient and user-friendly environment for machine learning development.
# Introduction
Zoish is a powerful tool for streamlining your machine learning pipeline by leveraging SHAP (SHapley Additive exPlanations) values for feature selection. Designed to work seamlessly with binary and multi-class classification models as well as regression models from sklearn, Zoish is also compatible with gradient boosting frameworks such as CatBoost and LightGBM.
## Features
- **Model Flexibility:** Zoish exhibits outstanding flexibility as it can work with any tree-based estimator or a superior estimator emerging from a tree-based optimization process. This enables it to integrate seamlessly into binary or multi-class Sklearn classification models, all Sklearn regression models, as well as with advanced gradient boosting frameworks such as CatBoost and LightGBM.
-
- **Feature Selection:** By utilizing SHAP values, Zoish efficiently determines the most influential features for your predictive models. This improves the interpretability of your model and can potentially enhance model performance by reducing overfitting.
- **Visualization:** Zoish includes capabilities for plotting important features using SHAP summary plots and SHAP bar plots, providing a clear and visual representation of feature importance.
## Dependencies
The core dependency of Zoish is the `shap` package, which is used to compute the SHAP values for tree based machine learning model. SHAP values are a unified measure of feature importance and they offer an improved interpretation of machine learning models. They are based on the concept of cooperative game theory and provide a fair allocation of the contribution of each feature to the prediction of each instance.
## Installation
To install Zoish, use pip:
## Installation
Zoish package is available on PyPI and can be installed with pip:
```sh
pip install zoish
```
For log configuration in development environment use
```sh
export env=dev
```
For log configuration in production environment use
```sh
export env=prod
```
# Examples
```
# Built-in libraries
import pandas as pd
# Scikit-learn libraries for model selection, metrics, pipeline, impute, preprocessing, compose, and ensemble
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectFromModel
from sklearn.impute import SimpleImputer
from sklearn.metrics import classification_report, confusion_matrix, f1_score, make_scorer
from sklearn.model_selection import GridSearchCV, KFold, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
# Other libraries
from category_encoders import TargetEncoder
from xgboost import XGBClassifier
from zoish.feature_selectors.shap_selectors import ShapFeatureSelector, ShapPlotFeatures
import logging
from zoish import logger
logger.setLevel(logging.ERROR)
from feature_engine.imputation import (
CategoricalImputer,
MeanMedianImputer
)
# Set logging level
logger.setLevel(logging.ERROR)
```
#### Example: Audiology (Standardized) Data Set
###### https://archive.ics.uci.edu/ml/datasets/Audiology+%28Standardized%29
#### Read data
```
urldata = "https://archive.ics.uci.edu/ml/machine-learning-databases/lymphography/lymphography.data"
urlname = "https://archive.ics.uci.edu/ml/machine-learning-databases/lung-cancer/lung-cancer.names"
# column names
col_names = [
"class",
"lymphatics",
"block of affere",
"bl. of lymph. c",
"bl. of lymph. s",
"by pass",
"extravasates",
"regeneration of",
"early uptake in",
"lym.nodes dimin",
"lym.nodes enlar",
"changes in lym.",
"defect in node",
"changes in node",
"special forms",
"dislocation of",
"exclusion of no",
"no. of nodes in",
]
data = pd.read_csv(urldata,names=col_names)
data.head()
```
#### Define labels and train-test split
```
data.loc[(data["class"] == 1) | (data["class"] == 2), "class"] = 0
data.loc[data["class"] == 3, "class"] = 1
data.loc[data["class"] == 4, "class"] = 2
data["class"] = data["class"].astype(int)
```
#### Train test split
```
X = data.loc[:, data.columns != "class"]
y = data.loc[:, data.columns == "class"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.33, random_state=42
)
```
#### Defining the feature pipeline steps:
Here, we use an untuned XGBClassifier model with the ShapFeatureSelector.In the next section, we will repeat the same process but with a tuned XGBClassifier. The aim is to demonstrate that a better estimator can yield improved results when used with the ShapFeatureSelector.
```
estimator_for_feature_selector= XGBClassifier()
estimator_for_feature_selector.fit(X_train, y_train)
shap_feature_selector = ShapFeatureSelector(model=estimator_for_feature_selector, num_features=5, cv = 5, scoring='accuracy', direction='maximum', n_iter=10, algorithm='auto')
# Define pre-processing for numeric columns (float and integer types)
numeric_features = X_train.select_dtypes(include=['int64', 'float64']).columns
numeric_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='mean')),
('scaler', StandardScaler())])
# Define pre-processing for categorical features
categorical_features = X_train.select_dtypes(include=['object']).columns
categorical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
('encoder', TargetEncoder(handle_missing='return_nan'))])
# Combine preprocessing into one column transformer
preprocessor = ColumnTransformer(
transformers=[
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features)])
# Feature Selection using ShapSelector
feature_selection = shap_feature_selector
# Classifier model
classifier = RandomForestClassifier(n_estimators=100)
# Create a pipeline that combines the preprocessor with a feature selection and a classifier
pipeline = Pipeline(steps=[('preprocessor', preprocessor),
('feature_selection', feature_selection),
('classifier', classifier)])
# Fit the model
pipeline.fit(X_train, y_train)
# Predict on test data
y_test_pred = pipeline.predict(X_test)
# Output first 10 predictions
print(y_test_pred[:10])
```
#### Check performance of the Pipeline
```
print("F1 score : ")
print(f1_score(y_test, y_test_pred,average='micro'))
print("Classification report : ")
print(classification_report(y_test, y_test_pred))
print("Confusion matrix : ")
print(confusion_matrix(y_test, y_test_pred))
```
#### Use better estimator:
In this iteration, we will utilize the optimally tuned estimator with the ShapFeatureSelector, which is expected to yield improved results."
```
int_cols = X_train.select_dtypes(include=['int']).columns.tolist()
# Define the XGBClassifier
xgb_clf = XGBClassifier()
# Define the parameter grid for XGBClassifier
param_grid = {
'learning_rate': [0.01, 0.1],
'max_depth': [ 4, 5],
'min_child_weight': [1, 2, 3],
'gamma': [0, 0.1, 0.2],
}
# Define the scoring function
scoring = make_scorer(f1_score, average='micro') # Use 'micro' average in case of multiclass target
# Set up GridSearchCV
grid_search = GridSearchCV(xgb_clf, param_grid, cv=5, scoring=scoring, verbose=1)
grid_search.fit(X_train, y_train)
# Fit the GridSearchCV object
estimator_for_feature_selector= grid_search.best_estimator_
shap_feature_selector = ShapFeatureSelector(model=estimator_for_feature_selector, num_features=5, scoring='accuracy', algorithm='auto',cv = 5, n_iter=10, direction='maximum')
pipeline =Pipeline([
# int missing values imputers
('floatimputer', MeanMedianImputer(
imputation_method='mean', variables=int_cols)),
('shap_feature_selector', shap_feature_selector),
('classfier', RandomForestClassifier(n_estimators=100))
])
# Fit the model
pipeline.fit(X_train, y_train)
# Predict on test data
y_test_pred = pipeline.predict(X_test)
# Output first 10 predictions
print(y_test_pred[:10])
```
#### Performance has improved
```
print("F1 score : ")
print(f1_score(y_test, y_test_pred,average='micro'))
print("Classification report : ")
print(classification_report(y_test, y_test_pred))
print("Confusion matrix : ")
print(confusion_matrix(y_test, y_test_pred))
#### Shap related plots
```
#### Plot the features importance
```
plot_factory = ShapPlotFeatures(shap_feature_selector)
```
#### Summary Plot of the selected features
```
plot_factory.summary_plot()
```

#### Summary Plot of the all features
```
plot_factory.summary_plot_full()
```

#### Bar Plot of the selected features
```
plot_factory.bar_plot()
```

#### Bar Plot of the all features
```
plot_factory.bar_plot_full()
```

More examples are available in the [examples](https://github.com/drhosseinjavedani/zoish/tree/main/zoish/examples).
## License
Licensed under the [BSD 2-Clause](https://opensource.org/licenses/BSD-2-Clause) License.
| zoish | /zoish-4.5.0.tar.gz/zoish-4.5.0/README.md | README.md |
.. contents:: :depth: 1
Introduction
============
**zojax.mr.gae** is a `zc.buildout`_ extension that alows to install GAE libs that distributed with GAE in development mode.
This extension is supposed to be used with `rod.recipe.googleapengine`_ recipe. Eggs that distributed with GAE are discovered by buildout as generic eggs.
.. _`zc.buildout`: http://pypi.python.org/pypi/zc.buildout
.. _`rod.recipe.googleapengine`: http://pypi.python.org/pypi/rod.recipe.appengine
Usage
=====
Add ``zojax.mr.gae`` to the ``extensions`` entry in your ``[buildout]``
section::
[buildout]
extensions = mr.developer
The format of entries in the ``[gae_source]`` section is::
[sources]
url = url
extraxt_dir = path to dir
eggs = list
Where individual parts are:
``url``
Link to Google App Engine.
``extraxt_dir``
The path to directory where Google App Engine will be stored
``eggs``
The names of the package that will be installed from Google App Engine libs.
Example
=======
Thet is a simple example of buildout config.::
[buildout]
develop = src/inboxer
parts = PIL
app
py-utils
tests
ipython-unix
extensions = zojax.mr.gae
[sources]
jinja2 = fs jinja2
webob_1_1_1 = fs webob_1_1_1
webapp2 = fs webapp2
yaml = fs yaml
[gae_source]
url = http://googleappengine.googlecode.com/files/google_appengine_1.6.4.zip
extraxt_dir = parts
eggs = jinja2
webob_1_1_1
webapp2
yaml
django_1_3
[versions]
Django = 1.3.1
rod.recipe.appengine = 2.0.0
[app]
recipe = rod.recipe.appengine
eggs = inboxer
jinja2
webapp2
PyYaml
Django
packages = inboxer
wtforms
server-script=dev_appserver
src = src/inboxer
zip-packages=False
url=${gae_source:url}
extra-paths = ${PIL:extra-path}
[py-utils]
recipe=zc.recipe.egg
eggs= pastescript
utils
WebTest
${app:eggs}
extra-paths= ${tests:extra-paths}
[pep8]
recipe = zc.recipe.egg
eggs = pep8 | zojax.mr.gae | /zojax.mr.gae-0.3.tar.gz/zojax.mr.gae-0.3/README | README |
import os
import urllib2
from zipfile import *
class Extension(object):
def __init__(self, buildout):
self.buildout = buildout
self.buildout_dir = buildout['buildout']['directory']
self.buildout_parts_dir = buildout['buildout']['parts-directory']
self.url = self.buildout['gae_source']['url']
self.packages = self.buildout['gae_source']['eggs'].split()
self.extraxt_dir = self.buildout['gae_source']['extraxt_dir']
if not self.extraxt_dir[0] == '/':
self.extraxt_dir = os.path.join(self.buildout_dir, self.extraxt_dir)
def download_package(self):
filename = self.url.split('/')[-1]
path_to_file = os.path.join(self.buildout_dir, 'downloads', filename)
try:
localFile =open(path_to_file, 'r')
return localFile
except IOError as e:
remotefile = urllib2.urlopen(self.url)
#print remotefile.info()['Content-Disposition']
if not os.path.exists(os.path.join(self.buildout_dir, 'downloads')):
os.makedirs(os.path.join(self.buildout_dir, 'downloads'))
localFile = open(path_to_file, 'wb')
print 'Downloading file %s to %s' % (filename, os.path.join(self.buildout_dir, 'downloads', filename))
localFile.write(remotefile.read())
localFile.close()
print 'Download complete'
return self.download_package()
def extract_package(self, archive):
if is_zipfile(archive):
print 'Start extracting %s to %s/parts' % (archive.name, os.path.join(self.buildout_dir, 'parts'))
zip_file = ZipFile(archive)
zip_file.extractall(os.path.join(self.buildout_dir, 'parts'))
else:
print "File %s is not zip" % archive.name
def chenge_develop_section(self):
for package in self.packages:
path = os.path.join(self.buildout_dir, 'parts/google_appengine/lib', package)
if os.path.exists(path):
self.buildout['buildout']['develop'] += '\n' + path
else:
print "Package %s is not found." % package
def __call__(self):
if not os.path.exists(os.path.join(self.extraxt_dir, 'google_appengine')):
gae_archive = self.download_package()
self.extract_package(gae_archive)
self.chenge_develop_section()
else:
self.chenge_develop_section()
def extension(buildout=None):
return Extension(buildout)() | zojax.mr.gae | /zojax.mr.gae-0.3.tar.gz/zojax.mr.gae-0.3/src/zojax/mr/gae/extension.py | extension.py |
from __future__ import absolute_import
from typing import cast, List, Tuple, Sequence, Union
# The prime modulus of the field
# field_modulus = 21888242871839275222246405745257275088696311157297823662689037894645226208583
field_modulus = (
21888242871839275222246405745257275088548364400416034343698204186575808495617
)
# CHANGE: Changing the modulus to the embedded curve
# See, it's prime!
assert pow(2, field_modulus, field_modulus) == 2
# The modulus of the polynomial in this representation of FQ12
# FQ12_MODULUS_COEFFS = (82, 0, 0, 0, 0, 0, -18, 0, 0, 0, 0, 0) # Implied + [1]
# FQ2_MODULUS_COEFFS = (1, 0)
# CHANGE: No need for extended in this case
# Extended euclidean algorithm to find modular inverses for
# integers
def inv(a: int, n: int) -> int:
if a == 0:
return 0
lm, hm = 1, 0
low, high = a % n, n
while low > 1:
r = high // low
nm, new = hm - lm * r, high - low * r
lm, low, hm, high = nm, new, lm, low
return lm % n
IntOrFQ = Union[int, "FQ"]
# A class for field elements in FQ. Wrap a number in this class,
# and it becomes a field element.
class FQ(object):
n = None # type: int
def __init__(self, val: IntOrFQ) -> None:
if isinstance(val, FQ):
self.n = val.n
else:
self.n = val % field_modulus
assert isinstance(self.n, int)
def __add__(self, other: IntOrFQ) -> "FQ":
on = other.n if isinstance(other, FQ) else other
return FQ((self.n + on) % field_modulus)
def __mul__(self, other: IntOrFQ) -> "FQ":
on = other.n if isinstance(other, FQ) else other
return FQ((self.n * on) % field_modulus)
def __rmul__(self, other: IntOrFQ) -> "FQ":
return self * other
def __radd__(self, other: IntOrFQ) -> "FQ":
return self + other
def __rsub__(self, other: IntOrFQ) -> "FQ":
on = other.n if isinstance(other, FQ) else other
return FQ((on - self.n) % field_modulus)
def __sub__(self, other: IntOrFQ) -> "FQ":
on = other.n if isinstance(other, FQ) else other
return FQ((self.n - on) % field_modulus)
def __div__(self, other: IntOrFQ) -> "FQ":
on = other.n if isinstance(other, FQ) else other
assert isinstance(on, int)
return FQ(self.n * inv(on, field_modulus) % field_modulus)
def __truediv__(self, other: IntOrFQ) -> "FQ":
return self.__div__(other)
def __rdiv__(self, other: IntOrFQ) -> "FQ":
on = other.n if isinstance(other, FQ) else other
assert isinstance(on, int), on
return FQ(inv(self.n, field_modulus) * on % field_modulus)
def __rtruediv__(self, other: IntOrFQ) -> "FQ":
return self.__rdiv__(other)
def __pow__(self, other: int) -> "FQ":
if other == 0:
return FQ(1)
elif other == 1:
return FQ(self.n)
elif other % 2 == 0:
return (self * self) ** (other // 2)
else:
return ((self * self) ** int(other // 2)) * self
def __eq__(
self, other: IntOrFQ
) -> bool: # type:ignore # https://github.com/python/mypy/issues/2783 # noqa: E501
if isinstance(other, FQ):
return self.n == other.n
else:
return self.n == other
def __ne__(
self, other: IntOrFQ
) -> bool: # type:ignore # https://github.com/python/mypy/issues/2783 # noqa: E501
return not self == other
def __neg__(self) -> "FQ":
return FQ(-self.n)
def __repr__(self) -> str:
return repr(self.n)
def __int__(self) -> int:
return self.n
@classmethod
def one(cls) -> "FQ":
return cls(1)
@classmethod
def zero(cls) -> "FQ":
return cls(0) | zokrates-pycrypto | /zokrates_pycrypto-0.3.0-py3-none-any.whl/zokrates_pycrypto/field.py | field.py |
import bitstring
from .babyjubjub import Point
# //TODO: add doc
WINDOW_SIZE_BITS = 2
def scalar_mul_windowed_bits(bits, base):
"""
FIXED base point
Log2(jubjubE) = 253.6
=> 253 bits!
=> 254 bits lenghts
=> 127 windows
use WINDOW_SIZE_BITS
"""
# Split into 2 bit windows
if isinstance(bits, bitstring.BitArray):
bits = bits.bin
windows = [
bits[i : i + WINDOW_SIZE_BITS] for i in range(0, len(bits), WINDOW_SIZE_BITS)
]
assert len(windows) > 0
# Hash resulting windows
return scalar_mul_windowed(windows, base)
def scalar_mul_windowed(windows, base):
# FIXED BASE POINT
if not isinstance(base, Point):
base = Point(*base)
segments = len(windows)
table = scalar_mul_windowed_gen_table(base, segments)
a = Point.infinity()
for j, window in enumerate(windows[::-1]):
row = table[j]
a += row[int(window, 2)]
return a
def scalar_mul_windowed_gen_table(base, segments=127):
""" Row i of the lookup table contains:
[2**4i * base, 2 * 2**4i * base, 3 * 2**4i * base, 3 * 2**4i * base]
E.g:
row_0 = [base, 2*base, 3*base, 4*base]
row_1 = [16*base, 32*base, 48*base, 64*base]
row_2 = [256*base, 512*base, 768*base, 1024*base]"""
# segments * 4 (WINDOW_SIZE_BITS**2)
p = base
table = []
for _ in range(0, segments):
row = [p.mult(i) for i in range(0, WINDOW_SIZE_BITS ** 2)]
# FIXME: + 1 needed ... see pedersen hash
table.append(row)
p = p.double().double()
return table
def pprint_scalar_mul_windowed_table(table):
dsl = []
segments = len(table)
for i in range(0, segments):
r = table[i]
dsl.append("//Round {}".format(i))
dsl.append(
"cx = sel([e[{}], e[{}]], [{} , {}, {}, {}])".format(
2 * i, 2 * i + 1, r[0].x, r[1].x, r[2].x, r[3].x
)
)
dsl.append(
"cy = sel([e[{}], e[{}]], [{} , {}, {}, {}])".format(
2 * i, 2 * i + 1, r[0].y, r[1].y, r[2].y, r[3].y
)
)
dsl.append("a = add(a , [cx, cy], context)")
# //round X
# cx = sel([e[2*X], e[2*X+1]], 0, x1, x2, x3)
# cy = sel([...], 1, y1, y2, y3)
# a = add(a, [cx, xy], context)
return "\n".join(dsl) | zokrates-pycrypto | /zokrates_pycrypto-0.3.0-py3-none-any.whl/zokrates_pycrypto/optimised_scalar_mul.py | optimised_scalar_mul.py |
from __future__ import division, print_function
import sys
import math
from functools import reduce
if sys.version_info.major > 2:
integer_types = (int,)
long = int
else:
integer_types = (int, long) # noqa: F821
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class SquareRootError(Error):
pass
class NegativeExponentError(Error):
pass
def modular_exp(base, exponent, modulus):
"Raise base to exponent, reducing by modulus"
if exponent < 0:
raise NegativeExponentError("Negative exponents (%d) not allowed" % exponent)
return pow(base, exponent, modulus)
# result = 1L
# x = exponent
# b = base + 0L
# while x > 0:
# if x % 2 > 0: result = (result * b) % modulus
# x = x // 2
# b = ( b * b ) % modulus
# return result
def polynomial_reduce_mod(poly, polymod, p):
"""Reduce poly by polymod, integer arithmetic modulo p.
Polynomials are represented as lists of coefficients
of increasing powers of x."""
# This module has been tested only by extensive use
# in calculating modular square roots.
# Just to make this easy, require a monic polynomial:
assert polymod[-1] == 1
assert len(polymod) > 1
while len(poly) >= len(polymod):
if poly[-1] != 0:
for i in range(2, len(polymod) + 1):
poly[-i] = (poly[-i] - poly[-1] * polymod[-i]) % p
poly = poly[0:-1]
return poly
def polynomial_multiply_mod(m1, m2, polymod, p):
"""Polynomial multiplication modulo a polynomial over ints mod p.
Polynomials are represented as lists of coefficients
of increasing powers of x."""
# This is just a seat-of-the-pants implementation.
# This module has been tested only by extensive use
# in calculating modular square roots.
# Initialize the product to zero:
prod = (len(m1) + len(m2) - 1) * [0]
# Add together all the cross-terms:
for i in range(len(m1)):
for j in range(len(m2)):
prod[i + j] = (prod[i + j] + m1[i] * m2[j]) % p
return polynomial_reduce_mod(prod, polymod, p)
def polynomial_exp_mod(base, exponent, polymod, p):
"""Polynomial exponentiation modulo a polynomial over ints mod p.
Polynomials are represented as lists of coefficients
of increasing powers of x."""
# Based on the Handbook of Applied Cryptography, algorithm 2.227.
# This module has been tested only by extensive use
# in calculating modular square roots.
assert exponent < p
if exponent == 0:
return [1]
G = base
k = exponent
if k % 2 == 1:
s = G
else:
s = [1]
while k > 1:
k = k // 2
G = polynomial_multiply_mod(G, G, polymod, p)
if k % 2 == 1:
s = polynomial_multiply_mod(G, s, polymod, p)
return s
def jacobi(a, n):
"""Jacobi symbol"""
# Based on the Handbook of Applied Cryptography (HAC), algorithm 2.149.
# This function has been tested by comparison with a small
# table printed in HAC, and by extensive use in calculating
# modular square roots.
assert n >= 3
assert n % 2 == 1
a = a % n
if a == 0:
return 0
if a == 1:
return 1
a1, e = a, 0
while a1 % 2 == 0:
a1, e = a1 // 2, e + 1
if e % 2 == 0 or n % 8 == 1 or n % 8 == 7:
s = 1
else:
s = -1
if a1 == 1:
return s
if n % 4 == 3 and a1 % 4 == 3:
s = -s
return s * jacobi(n % a1, a1)
def square_root_mod_prime(a, p):
"""Modular square root of a, mod p, p prime."""
# Based on the Handbook of Applied Cryptography, algorithms 3.34 to 3.39.
# This module has been tested for all values in [0,p-1] for
# every prime p from 3 to 1229.
assert 0 <= a < p
assert 1 < p
if a == 0:
return 0
if p == 2:
return a
jac = jacobi(a, p)
if jac == -1:
raise SquareRootError("%d has no square root modulo %d" % (a, p))
if p % 4 == 3:
return modular_exp(a, (p + 1) // 4, p)
if p % 8 == 5:
d = modular_exp(a, (p - 1) // 4, p)
if d == 1:
return modular_exp(a, (p + 3) // 8, p)
if d == p - 1:
return (2 * a * modular_exp(4 * a, (p - 5) // 8, p)) % p
raise RuntimeError("Shouldn't get here.")
for b in range(2, p):
if jacobi(b * b - 4 * a, p) == -1:
f = (a, -b, 1)
ff = polynomial_exp_mod((0, 1), (p + 1) // 2, f, p)
assert ff[1] == 0
return ff[0]
raise RuntimeError("No b found.")
def inverse_mod(a, m):
"""Inverse of a mod m."""
if a < 0 or m <= a:
a = a % m
# From Ferguson and Schneier, roughly:
c, d = a, m
uc, vc, ud, vd = 1, 0, 0, 1
while c != 0:
q, c, d = divmod(d, c) + (c,)
uc, vc, ud, vd = ud - q * uc, vd - q * vc, uc, vc
# At this point, d is the GCD, and ud*a+vd*m = d.
# If d == 1, this means that ud is a inverse.
assert d == 1
if ud > 0:
return ud
else:
return ud + m
def gcd2(a, b):
"""Greatest common divisor using Euclid's algorithm."""
while a:
a, b = b % a, a
return b
def gcd(*a):
"""Greatest common divisor.
Usage: gcd( [ 2, 4, 6 ] )
or: gcd( 2, 4, 6 )
"""
if len(a) > 1:
return reduce(gcd2, a)
if hasattr(a[0], "__iter__"):
return reduce(gcd2, a[0])
return a[0]
def lcm2(a, b):
"""Least common multiple of two integers."""
return (a * b) // gcd(a, b)
def lcm(*a):
"""Least common multiple.
Usage: lcm( [ 3, 4, 5 ] )
or: lcm( 3, 4, 5 )
"""
if len(a) > 1:
return reduce(lcm2, a)
if hasattr(a[0], "__iter__"):
return reduce(lcm2, a[0])
return a[0]
def factorization(n):
"""Decompose n into a list of (prime,exponent) pairs."""
assert isinstance(n, integer_types)
if n < 2:
return []
result = []
d = 2
# Test the small primes:
for d in smallprimes:
if d > n:
break
q, r = divmod(n, d)
if r == 0:
count = 1
while d <= n:
n = q
q, r = divmod(n, d)
if r != 0:
break
count = count + 1
result.append((d, count))
# If n is still greater than the last of our small primes,
# it may require further work:
if n > smallprimes[-1]:
if is_prime(n): # If what's left is prime, it's easy:
result.append((n, 1))
else: # Ugh. Search stupidly for a divisor:
d = smallprimes[-1]
while 1:
d = d + 2 # Try the next divisor.
q, r = divmod(n, d)
if q < d:
break # n < d*d means we're done, n = 1 or prime.
if r == 0: # d divides n. How many times?
count = 1
n = q
while d <= n: # As long as d might still divide n,
q, r = divmod(n, d) # see if it does.
if r != 0:
break
n = q # It does. Reduce n, increase count.
count = count + 1
result.append((d, count))
if n > 1:
result.append((n, 1))
return result
def phi(n):
"""Return the Euler totient function of n."""
assert isinstance(n, integer_types)
if n < 3:
return 1
result = 1
ff = factorization(n)
for f in ff:
e = f[1]
if e > 1:
result = result * f[0] ** (e - 1) * (f[0] - 1)
else:
result = result * (f[0] - 1)
return result
def carmichael(n):
"""Return Carmichael function of n.
Carmichael(n) is the smallest integer x such that
m**x = 1 mod n for all m relatively prime to n.
"""
return carmichael_of_factorized(factorization(n))
def carmichael_of_factorized(f_list):
"""Return the Carmichael function of a number that is
represented as a list of (prime,exponent) pairs.
"""
if len(f_list) < 1:
return 1
result = carmichael_of_ppower(f_list[0])
for i in range(1, len(f_list)):
result = lcm(result, carmichael_of_ppower(f_list[i]))
return result
def carmichael_of_ppower(pp):
"""Carmichael function of the given power of the given prime.
"""
p, a = pp
if p == 2 and a > 2:
return 2 ** (a - 2)
else:
return (p - 1) * p ** (a - 1)
def order_mod(x, m):
"""Return the order of x in the multiplicative group mod m.
"""
# Warning: this implementation is not very clever, and will
# take a long time if m is very large.
if m <= 1:
return 0
assert gcd(x, m) == 1
z = x
result = 1
while z != 1:
z = (z * x) % m
result = result + 1
return result
def largest_factor_relatively_prime(a, b):
"""Return the largest factor of a relatively prime to b.
"""
while 1:
d = gcd(a, b)
if d <= 1:
break
b = d
while 1:
q, r = divmod(a, d)
if r > 0:
break
a = q
return a
def kinda_order_mod(x, m):
"""Return the order of x in the multiplicative group mod m',
where m' is the largest factor of m relatively prime to x.
"""
return order_mod(x, largest_factor_relatively_prime(m, x))
def is_prime(n):
"""Return True if x is prime, False otherwise.
We use the Miller-Rabin test, as given in Menezes et al. p. 138.
This test is not exact: there are composite values n for which
it returns True.
In testing the odd numbers from 10000001 to 19999999,
about 66 composites got past the first test,
5 got past the second test, and none got past the third.
Since factors of 2, 3, 5, 7, and 11 were detected during
preliminary screening, the number of numbers tested by
Miller-Rabin was (19999999 - 10000001)*(2/3)*(4/5)*(6/7)
= 4.57 million.
"""
# (This is used to study the risk of false positives:)
global miller_rabin_test_count
miller_rabin_test_count = 0
if n <= smallprimes[-1]:
if n in smallprimes:
return True
else:
return False
if gcd(n, 2 * 3 * 5 * 7 * 11) != 1:
return False
# Choose a number of iterations sufficient to reduce the
# probability of accepting a composite below 2**-80
# (from Menezes et al. Table 4.4):
t = 40
n_bits = 1 + int(math.log(n, 2))
for k, tt in (
(100, 27),
(150, 18),
(200, 15),
(250, 12),
(300, 9),
(350, 8),
(400, 7),
(450, 6),
(550, 5),
(650, 4),
(850, 3),
(1300, 2),
):
if n_bits < k:
break
t = tt
# Run the test t times:
s = 0
r = n - 1
while (r % 2) == 0:
s = s + 1
r = r // 2
for i in range(t):
a = smallprimes[i]
y = modular_exp(a, r, n)
if y != 1 and y != n - 1:
j = 1
while j <= s - 1 and y != n - 1:
y = modular_exp(y, 2, n)
if y == 1:
miller_rabin_test_count = i + 1
return False
j = j + 1
if y != n - 1:
miller_rabin_test_count = i + 1
return False
return True
def next_prime(starting_value):
"Return the smallest prime larger than the starting value."
if starting_value < 2:
return 2
result = (starting_value + 1) | 1
while not is_prime(result):
result = result + 2
return result
smallprimes = [
2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
103,
107,
109,
113,
127,
131,
137,
139,
149,
151,
157,
163,
167,
173,
179,
181,
191,
193,
197,
199,
211,
223,
227,
229,
233,
239,
241,
251,
257,
263,
269,
271,
277,
281,
283,
293,
307,
311,
313,
317,
331,
337,
347,
349,
353,
359,
367,
373,
379,
383,
389,
397,
401,
409,
419,
421,
431,
433,
439,
443,
449,
457,
461,
463,
467,
479,
487,
491,
499,
503,
509,
521,
523,
541,
547,
557,
563,
569,
571,
577,
587,
593,
599,
601,
607,
613,
617,
619,
631,
641,
643,
647,
653,
659,
661,
673,
677,
683,
691,
701,
709,
719,
727,
733,
739,
743,
751,
757,
761,
769,
773,
787,
797,
809,
811,
821,
823,
827,
829,
839,
853,
857,
859,
863,
877,
881,
883,
887,
907,
911,
919,
929,
937,
941,
947,
953,
967,
971,
977,
983,
991,
997,
1009,
1013,
1019,
1021,
1031,
1033,
1039,
1049,
1051,
1061,
1063,
1069,
1087,
1091,
1093,
1097,
1103,
1109,
1117,
1123,
1129,
1151,
1153,
1163,
1171,
1181,
1187,
1193,
1201,
1213,
1217,
1223,
1229,
]
miller_rabin_test_count = 0
def __main__():
# Making sure locally defined exceptions work:
# p = modular_exp( 2, -2, 3 )
# p = square_root_mod_prime( 2, 3 )
print("Testing gcd...")
assert gcd(3 * 5 * 7, 3 * 5 * 11, 3 * 5 * 13) == 3 * 5
assert gcd([3 * 5 * 7, 3 * 5 * 11, 3 * 5 * 13]) == 3 * 5
assert gcd(3) == 3
print("Testing lcm...")
assert lcm(3, 5 * 3, 7 * 3) == 3 * 5 * 7
assert lcm([3, 5 * 3, 7 * 3]) == 3 * 5 * 7
assert lcm(3) == 3
print("Testing next_prime...")
bigprimes = (
999671,
999683,
999721,
999727,
999749,
999763,
999769,
999773,
999809,
999853,
999863,
999883,
999907,
999917,
999931,
999953,
999959,
999961,
999979,
999983,
)
for i in range(len(bigprimes) - 1):
assert next_prime(bigprimes[i]) == bigprimes[i + 1]
error_tally = 0
# Test the square_root_mod_prime function:
for p in smallprimes:
print("Testing square_root_mod_prime for modulus p = %d." % p)
squares = []
for root in range(0, 1 + p // 2):
sq = (root * root) % p
squares.append(sq)
calculated = square_root_mod_prime(sq, p)
if (calculated * calculated) % p != sq:
error_tally = error_tally + 1
print(
"Failed to find %d as sqrt( %d ) mod %d. Said %d."
% (root, sq, p, calculated)
)
for nonsquare in range(0, p):
if nonsquare not in squares:
try:
calculated = square_root_mod_prime(nonsquare, p)
except SquareRootError:
pass
else:
error_tally = error_tally + 1
print(
"Failed to report no root for sqrt( %d ) mod %d."
% (nonsquare, p)
)
# Test the jacobi function:
for m in range(3, 400, 2):
print("Testing jacobi for modulus m = %d." % m)
if is_prime(m):
squares = []
for root in range(1, m):
if jacobi(root * root, m) != 1:
error_tally = error_tally + 1
print("jacobi( %d * %d, %d ) != 1" % (root, root, m))
squares.append(root * root % m)
for i in range(1, m):
if not i in squares:
if jacobi(i, m) != -1:
error_tally = error_tally + 1
print("jacobi( %d, %d ) != -1" % (i, m))
else: # m is not prime.
f = factorization(m)
for a in range(1, m):
c = 1
for i in f:
c = c * jacobi(a, i[0]) ** i[1]
if c != jacobi(a, m):
error_tally = error_tally + 1
print("%d != jacobi( %d, %d )" % (c, a, m))
# Test the inverse_mod function:
print("Testing inverse_mod . . .")
import random
n_tests = 0
for i in range(100):
m = random.randint(20, 10000)
for j in range(100):
a = random.randint(1, m - 1)
if gcd(a, m) == 1:
n_tests = n_tests + 1
inv = inverse_mod(a, m)
if inv <= 0 or inv >= m or (a * inv) % m != 1:
error_tally = error_tally + 1
print("%d = inverse_mod( %d, %d ) is wrong." % (inv, a, m))
assert n_tests > 1000
print(n_tests, " tests of inverse_mod completed.")
class FailedTest(Exception):
pass
print(error_tally, "errors detected.")
if error_tally != 0:
raise FailedTest("%d errors detected" % error_tally)
if __name__ == "__main__":
__main__() | zokrates-pycrypto | /zokrates_pycrypto-0.3.0-py3-none-any.whl/zokrates_pycrypto/numbertheory.py | numbertheory.py |
from collections import namedtuple
from .field import FQ, inv, field_modulus
from .numbertheory import square_root_mod_prime, SquareRootError
# order of the field
JUBJUB_Q = field_modulus
# order of the curve
JUBJUB_E = 21888242871839275222246405745257275088614511777268538073601725287587578984328
JUBJUB_C = 8 # Cofactor
JUBJUB_L = JUBJUB_E // JUBJUB_C # C*L == E
JUBJUB_A = 168700 # Coefficient A
JUBJUB_D = 168696 # Coefficient D
def is_negative(v):
assert isinstance(v, FQ)
return v.n < (-v).n
class Point(namedtuple("_Point", ("x", "y"))):
def valid(self):
"""
Satisfies the relationship
ax^2 + y^2 = 1 + d x^2 y^2
"""
xsq = self.x * self.x
ysq = self.y * self.y
return (JUBJUB_A * xsq) + ysq == (1 + JUBJUB_D * xsq * ysq)
def add(self, other):
assert isinstance(other, Point)
if self.x == 0 and self.y == 0:
return other
(u1, v1) = (self.x, self.y)
(u2, v2) = (other.x, other.y)
u3 = (u1 * v2 + v1 * u2) / (FQ.one() + JUBJUB_D * u1 * u2 * v1 * v2)
v3 = (v1 * v2 - JUBJUB_A * u1 * u2) / (FQ.one() - JUBJUB_D * u1 * u2 * v1 * v2)
return Point(u3, v3)
def mult(self, scalar):
if isinstance(scalar, FQ):
scalar = scalar.n
p = self
a = self.infinity()
i = 0
while scalar != 0:
if (scalar & 1) != 0:
a = a.add(p)
p = p.double()
scalar = scalar // 2
i += 1
return a
def neg(self):
"""
Twisted Edwards Curves, BBJLP-2008, section 2 pg 2
"""
return Point(-self.x, self.y)
@classmethod
def generator(cls):
x = 16540640123574156134436876038791482806971768689494387082833631921987005038935
y = 20819045374670962167435360035096875258406992893633759881276124905556507972311
return Point(FQ(x), FQ(y))
@staticmethod
def infinity():
return Point(FQ(0), FQ(1))
def __str__(self):
return "x: {}, y:{}".format(*self)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __neg__(self):
return self.neg()
def __add__(self, other):
return self.add(other)
def __sub__(self, other):
return self.add(other.neg())
def __mul__(self, n):
return self.mult(n)
def double(self):
return self.add(self)
@classmethod
def from_x(cls, x):
"""
y^2 = ((a * x^2) / (d * x^2 - 1)) - (1 / (d * x^2 - 1))
For every x coordinate, there are two possible points: (x, y) and (x, -y)
"""
assert isinstance(x, FQ)
xsq = x * x
ax2 = JUBJUB_A * xsq
dxsqm1 = inv(JUBJUB_D * xsq - 1, JUBJUB_Q)
ysq = dxsqm1 * (ax2 - 1)
y = FQ(square_root_mod_prime(int(ysq), JUBJUB_Q))
return cls(x, y)
@classmethod
def from_y(cls, y, sign=None):
"""
x^2 = (y^2 - 1) / (d * y^2 - a)
"""
assert isinstance(y, FQ)
ysq = y * y
lhs = ysq - 1
rhs = JUBJUB_D * ysq - JUBJUB_A
xsq = lhs / rhs
x = FQ(square_root_mod_prime(int(xsq), JUBJUB_Q))
if sign is not None:
# Used for compress & decompress
if (x.n & 1) != sign:
x = -x
else:
if is_negative(x):
x = -x
return cls(x, y)
@classmethod
def from_hash(cls, entropy):
"""
HashToPoint (or Point.from_hash)
Parameters:
entropy (bytes): input entropy provided as byte array
Hashes the input entropy and interprets the result as the Y coordinate
then recovers the X coordinate, if no valid point can be recovered
Y is incremented until a matching X coordinate is found.
The point is guaranteed to be prime order and not the identity.
From: https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/?include_text=1
Page 6:
o HashToBase(x, i). This method is parametrized by p and H, where p
is the prime order of the base field Fp, and H is a cryptographic
hash function which outputs at least floor(log2(p)) + 2 bits. The
function first hashes x, converts the result to an integer, and
reduces modulo p to give an element of Fp.
"""
from hashlib import sha256
assert isinstance(entropy, bytes)
entropy = sha256(entropy).digest()
entropy_as_int = int.from_bytes(entropy, "big")
y = FQ(entropy_as_int)
while True:
try:
p = cls.from_y(y)
except SquareRootError:
y += 1
continue
# Multiply point by cofactor, ensures it's on the prime-order subgroup
p = p * JUBJUB_C
# Verify point is on prime-ordered sub-group
if (p * JUBJUB_L) != Point.infinity():
raise RuntimeError("Point not on prime-ordered subgroup")
return p
def compress(self):
x = self.x.n
y = self.y.n
# return int.to_bytes(y | ((x & 1) << 255), 32, "little")
return int.to_bytes(y | ((x & 1) << 255), 32, "big")
@classmethod
def decompress(cls, point):
"""
From: https://ed25519.cr.yp.to/eddsa-20150704.pdf
The encoding of F_q is used to define "negative" elements of F_q:
specifically, x is negative if the (b-1)-bit encoding of x is
lexiographically larger than the (b-1)-bit encoding of -x. In particular,
if q is prime and the (b-1)-bit encoding of F_q is the little-endian
encoding of {0, 1, ..., q-1}, then {1,3,5,...,q-2} are the negative element of F_q.
This encoding is also used to define a b-bit encoding of each element `(x,y) ∈ E`
as a b-bit string (x,y), namely the (b-1)-bit encoding of y followed by the sign bit.
the sign bit is 1 if and only if x is negative.
A parser recovers `(x,y)` from a b-bit string, while also verifying that `(x,y) ∈ E`,
as follows: parse the first b-1 bits as y, compute `xx = (y^2 - 1) / (dy^2 - a)`;
compute `x = [+ or -] sqrt(xx)` where the `[+ or -]` is chosen so that the sign of
`x` matches the `b`th bit of the string. if `xx` is not a square then parsing fails.
"""
if len(point) != 32:
raise ValueError("Invalid input length for decompression")
# y = int.from_bytes(point, "little")
y = int.from_bytes(point, "big")
sign = y >> 255
y &= (1 << 255) - 1
return cls.from_y(FQ(y), sign) | zokrates-pycrypto | /zokrates_pycrypto-0.3.0-py3-none-any.whl/zokrates_pycrypto/babyjubjub.py | babyjubjub.py |
from bitstring import BitArray
from .eddsa import Point
from .field import FQ
import hashlib
def to_bytes(*args):
"Returns byte representation for objects used in this module."
result = b""
for M in args:
if isinstance(M, Point):
result += to_bytes(M.x)
# result += to_bytes(M.y)
elif isinstance(M, FQ):
result += to_bytes(M.n)
elif isinstance(M, int):
result += M.to_bytes(32, "big")
elif isinstance(M, BitArray):
result += M.tobytes()
elif isinstance(M, bytes):
result += M
elif isinstance(M, (list, tuple)):
result += b"".join(to_bytes(_) for _ in M)
else:
raise TypeError("Bad type for M: " + str(type(M)))
return result
def write_signature_for_zokrates_cli(pk, sig, msg, path):
"Writes the input arguments for verifyEddsa in the ZoKrates stdlib to file."
sig_R, sig_S = sig
args = [sig_R.x, sig_R.y, sig_S, pk.p.x.n, pk.p.y.n]
args = " ".join(map(str, args))
M0 = msg.hex()[:64]
M1 = msg.hex()[64:]
b0 = BitArray(int(M0, 16).to_bytes(32, "big")).bin
b1 = BitArray(int(M1, 16).to_bytes(32, "big")).bin
args = args + " " + " ".join(b0 + b1)
with open(path, "w+") as file:
for l in args:
file.write(l)
def pprint_hex_as_256bit(n, h):
"Takes a variable name and a hex encoded number and returns Zokrates assignment statement."
b = BitArray(int(h, 16).to_bytes(32, "big")).bin
s = "[" + ", ".join(b) + "]"
return "field[256] {} = {} \n".format(n, s)
def pprint_point(n, p):
"Takes a variable name and curve point and returns Zokrates assignment statement."
x, y = p
return "field[2] {} = [{}, {}] \n".format(n, x, y)
def pprint_fe(n, fe):
"Takes a variable name and field element and returns Zokrates assignment statement."
return "field {} = {} \n".format(n, fe)
def pprint_for_zokrates(pk, sig, msg):
M0 = msg.hex()[:64]
M1 = msg.hex()[64:]
code = []
sig_R, sig_S = sig
for n, h in zip(["M0", "M1"], [M0, M1]):
code.append(pprint_hex_as_256bit(n, h))
code.append(pprint_point("A", pk.p))
code.append(pprint_point("R", sig_R))
code.append(pprint_fe("S", sig_S))
print("\n".join(code)) | zokrates-pycrypto | /zokrates_pycrypto-0.3.0-py3-none-any.whl/zokrates_pycrypto/utils.py | utils.py |
import os
class ZoKrates:
def __init__(self, instructions, inputs_and_outputs):
self.code = []
self.input_assignments = []
self.outputs = []
for ins in instructions:
# Add indentation and newline to each line in the code block
self.code.append("\t{}\n".format(ins.to_zokrates()))
self.header = ["def main("]
# Array for storing the parameters of the main method
parameters = []
for entry in inputs_and_outputs:
if entry["is_input"]:
self.input_assignments.append(entry["value"])
if entry["is_public"]:
parameters.append("field v{}".format(entry["index"]))
else: # private
parameters.append("private field v{}".format(entry["index"]))
else:
self.outputs.append("v{}".format(entry["index"]))
self.header.append(", ".join(parameters))
self.header.append(") -> (field): \n\n")
self.header = "".join(self.header)
# Return the outputs
if self.outputs:
self.code.append("\treturn {}\n".format(",".join(self.outputs)))
else:
# Return 0 if no outputs are specified, as ZoKrates requires a
# return statement
self.code.append("\treturn 0\n")
def compile(self, path):
self.__write_code_file(path)
self.path = path
def synthesize(self):
cmd = "zokrates compile -i {}".format(self.path)
status = os.system(cmd)
if __debug__:
print(status)
def setup(self):
cmd = "zokrates setup"
status = os.system(cmd)
if __debug__:
print(status)
def compute_witness(self):
# TODO: read args from file
args = " ".join(self.input_assignments)
cmd = "zokrates compute-witness -a {}".format(args)
status = os.system(cmd)
if __debug__:
print(status)
def generate_proof(self):
cmd = "zokrates generate-proof"
status = os.system(cmd)
if __debug__:
print(status)
def run(self, path):
self.compile(path)
self.synthesize()
self.setup()
self.compute_witness()
self.generate_proof()
def __write_code_file(self, path):
with open(path, "w+") as f:
f.write(self.header)
for l in self.code:
f.write(l) | zokrates-pycrypto | /zokrates_pycrypto-0.3.0-py3-none-any.whl/zokrates_pycrypto/cli_zokrates.py | cli_zokrates.py |
import hashlib
import binascii
# try:
# import sha3
# except:
# from warnings import warn
# warn("sha3 is not working!")
class MerkleTools(object):
def __init__(self, hash_type="sha256"):
hash_type = hash_type.lower()
if hash_type in ['sha256', 'md5', 'sha224', 'sha384', 'sha512',
'sha3_256', 'sha3_224', 'sha3_384', 'sha3_512']:
self.hash_function = getattr(hashlib, hash_type)
else:
raise Exception('`hash_type` {} nor supported'.format(hash_type))
self.reset_tree()
def _to_hex(self, x):
try: # python3
return x.hex()
except: # python2
return binascii.hexlify(x)
def reset_tree(self):
self.leaves = list()
self.levels = None
self.is_ready = False
def add_leaf(self, values, do_hash=False):
self.is_ready = False
# check if single leaf
if not isinstance(values, tuple) and not isinstance(values, list):
values = [values]
for v in values:
if do_hash:
v = v.encode('utf-8')
v = self.hash_function(v).hexdigest()
v = bytearray.fromhex(v)
self.leaves.append(v)
def get_leaf(self, index):
return self._to_hex(self.leaves[index])
def get_leaf_count(self):
return len(self.leaves)
def get_tree_ready_state(self):
return self.is_ready
def _calculate_next_level(self):
solo_leave = None
N = len(self.levels[0]) # number of leaves on the level
if N % 2 == 1: # if odd number of leaves on the level
solo_leave = self.levels[0][-1]
N -= 1
new_level = []
for l, r in zip(self.levels[0][0:N:2], self.levels[0][1:N:2]):
new_level.append(self.hash_function(l+r).digest())
if solo_leave is not None:
new_level.append(solo_leave)
self.levels = [new_level, ] + self.levels # prepend new level
def make_tree(self):
self.is_ready = False
if self.get_leaf_count() > 0:
self.levels = [self.leaves, ]
while len(self.levels[0]) > 1:
self._calculate_next_level()
self.is_ready = True
def get_merkle_root(self):
if self.is_ready:
if self.levels is not None:
return self._to_hex(self.levels[0][0])
else:
return None
else:
return None
def get_proof(self, index):
if self.levels is None:
return None
elif not self.is_ready or index > len(self.leaves)-1 or index < 0:
return None
else:
proof = []
for x in range(len(self.levels) - 1, 0, -1):
level_len = len(self.levels[x])
if (index == level_len - 1) and (level_len % 2 == 1): # skip if this is an odd end node
index = int(index / 2.)
continue
is_right_node = index % 2
sibling_index = index - 1 if is_right_node else index + 1
sibling_pos = "left" if is_right_node else "right"
sibling_value = self._to_hex(self.levels[x][sibling_index])
proof.append({sibling_pos: sibling_value})
index = int(index / 2.)
return proof
def validate_proof(self, proof, target_hash, merkle_root):
merkle_root = bytearray.fromhex(merkle_root)
target_hash = bytearray.fromhex(target_hash)
if len(proof) == 0:
return target_hash == merkle_root
else:
proof_hash = target_hash
for p in proof:
try:
# the sibling is a left node
sibling = bytearray.fromhex(p['left'])
proof_hash = self.hash_function(sibling + proof_hash).digest()
except:
# the sibling is a right node
sibling = bytearray.fromhex(p['right'])
proof_hash = self.hash_function(proof_hash + sibling).digest()
return proof_hash == merkle_root | zokrates-pycrypto | /zokrates_pycrypto-0.3.0-py3-none-any.whl/zokrates_pycrypto/merkletree.py | merkletree.py |
import hashlib
from collections import namedtuple
from math import ceil, log2
from os import urandom
from .babyjubjub import JUBJUB_E, JUBJUB_L, JUBJUB_Q, Point
from .field import FQ
from .utils import to_bytes
class PrivateKey(namedtuple("_PrivateKey", ("fe"))):
"""
Wraps field element
"""
@classmethod
# FIXME: ethsnarks creates keys > 32bytes. Create issue.
def from_rand(cls):
mod = JUBJUB_L
# nbytes = ceil(ceil(log2(mod)) / 8) + 1
nbytes = ceil(ceil(log2(mod)) / 8)
rand_n = int.from_bytes(urandom(nbytes), "little")
return cls(FQ(rand_n))
def sign(self, msg, B=None):
"Returns the signature (R,S) for a given private key and message."
B = B or Point.generator()
A = PublicKey.from_private(self) # A = kB
M = msg
r = hash_to_scalar(self.fe, M) # r = H(k,M) mod L
R = B.mult(r) # R = rB
# Bind the message to the nonce, public key and message
hRAM = hash_to_scalar(R, A, M)
key_field = self.fe.n
S = (r + (key_field * hRAM)) % JUBJUB_E # r + (H(R,A,M) * k)
return (R, S)
class PublicKey(namedtuple("_PublicKey", ("p"))):
"""
Wraps edwards point
"""
@classmethod
def from_private(cls, sk, B=None):
"Returns public key for a private key. B denotes the group generator"
B = B or Point.generator()
if not isinstance(sk, PrivateKey):
sk = PrivateKey(sk)
A = B.mult(sk.fe)
return cls(A)
def verify(self, sig, msg, B=None):
B = B or Point.generator()
R, S = sig
M = msg
A = self.p
lhs = B.mult(S)
hRAM = hash_to_scalar(R, A, M)
rhs = R + (A.mult(hRAM))
return lhs == rhs
def hash_to_scalar(*args):
"""
Hash the key and message to create `r`, the blinding factor for this signature.
If the same `r` value is used more than once, the key for the signature is revealed.
Note that we take the entire 256bit hash digest as input for the scalar multiplication.
As the group is only of size JUBJUB_E (<256bit) we allow wrapping around the group modulo.
"""
p = b"".join(to_bytes(_) for _ in args)
digest = hashlib.sha256(p).digest()
return int(digest.hex(), 16) # mod JUBJUB_E here for optimized implementation | zokrates-pycrypto | /zokrates_pycrypto-0.3.0-py3-none-any.whl/zokrates_pycrypto/eddsa.py | eddsa.py |
import math
import bitstring
from math import floor, log2
from struct import pack
from ..babyjubjub import Point, JUBJUB_L, JUBJUB_C
from ..field import FQ
WINDOW_SIZE_BITS = 2 # Size of the pre-computed look-up table
def pedersen_hash_basepoint(name, i):
"""
Create a base point for use with the windowed Pedersen
hash function.
The name and sequence numbers are used as a unique identifier.
Then HashToPoint is run on the name+seq to get the base point.
"""
if not isinstance(name, bytes):
if isinstance(name, str):
name = name.encode("ascii")
else:
raise TypeError("Name not bytes")
if i < 0 or i > 0xFFFF:
raise ValueError("Sequence number invalid")
if len(name) > 28:
raise ValueError("Name too long")
data = b"%-28s%04X" % (name, i)
return Point.from_hash(data)
def windows_to_dsl_array(windows):
bit_windows = (bitstring.BitArray(bin(i)).bin[::-1] for i in windows)
bit_windows_padded = ("{:0<3}".format(w) for w in bit_windows)
bitstr = "".join(bit_windows_padded)
return list(bitstr)
class PedersenHasher(object):
def __init__(self, name, segments=False):
self.name = name
if segments:
self.segments = segments
self.is_sized = True
else:
self.is_sized = False
def __gen_table(self):
assert (
self.is_sized == True
), "Hasher size must be defined first, before lookup table can be created"
generators = self.generators
table = []
for p in generators:
row = [p.mult(i + 1) for i in range(0, WINDOW_SIZE_BITS ** 2)]
table.append(row)
return table
def __gen_generators(self):
name = self.name
segments = self.segments
generators = []
for j in range(0, segments):
# TODO: define `62`,
if j % 62 == 0:
current = pedersen_hash_basepoint(name, j // 62)
j = j % 62
if j != 0:
current = current.double().double().double().double()
generators.append(current)
return generators
def __hash_windows(self, windows, witness):
if self.is_sized == False:
self.segments = len(windows)
self.is_sized = True
self.generators = self.__gen_generators()
segments = self.segments
assert (
len(windows) <= segments
), "Number of windows exceeds pedersenHasher config. {} vs {}".format(
len(windows), segments
)
padding = (segments - len(windows)) * [0] # pad to match number of segments
windows.extend(padding)
assert (
len(windows) == segments
), "Number of windows does not match pedersenHasher config. {} vs {}".format(
len(windows), segments
)
# in witness mode return padded windows
if witness:
return windows_to_dsl_array(windows)
result = Point.infinity()
for (g, window) in zip(self.generators, windows):
segment = g * ((window & 0b11) + 1)
if window > 0b11:
segment = segment.neg()
result += segment
return result
def hash_bits(self, bits, witness=False):
# Split into 3 bit windows
if isinstance(bits, bitstring.BitArray):
bits = bits.bin
windows = [int(bits[i : i + 3][::-1], 2) for i in range(0, len(bits), 3)]
assert len(windows) > 0
return self.__hash_windows(windows, witness)
def hash_bytes(self, data, witness=False):
"""
Hashes a sequence of bits (the message) into a point.
The message is split into 3-bit windows after padding (via append)
to `len(data.bits) = 0 mod 3`
"""
assert isinstance(data, bytes)
assert len(data) > 0
# Decode bytes to octets of binary bits
bits = "".join([bin(_)[2:].rjust(8, "0") for _ in data])
return self.hash_bits(bits, witness)
def hash_scalars(self, *scalars, witness=False):
"""
Calculates a pedersen hash of scalars in the same way that zCash
is doing it according to: ... of their spec.
It is looking up 3bit chunks in a 2bit table (3rd bit denotes sign).
E.g:
(b2, b1, b0) = (1,0,1) would look up first element and negate it.
Row i of the lookup table contains:
[2**4i * base, 2 * 2**4i * base, 3 * 2**4i * base, 3 * 2**4i * base]
E.g:
row_0 = [base, 2*base, 3*base, 4*base]
row_1 = [16*base, 32*base, 48*base, 64*base]
row_2 = [256*base, 512*base, 768*base, 1024*base]
Following Theorem 5.4.1 of the zCash Sapling specification, for baby jub_jub
we need a new base point every 62 windows. We will therefore have multiple
tables with 62 rows each.
"""
windows = []
for _, s in enumerate(scalars):
windows += list((s >> i) & 0b111 for i in range(0, s.bit_length(), 3))
return self.__hash_windows(windows, witness)
def gen_dsl_witness_bits(self, bits):
return self.hash_bits(bits, witness=True)
def gen_dsl_witness_bytes(self, data):
return self.hash_bytes(data, witness=True)
def gen_dsl_witness_scalars(self, *scalars):
return self.hash_scalars(*scalars, witness=True)
def __gen_dsl_code(self):
table = self.__gen_table()
imports = """
import "utils/multiplexer/lookup3bitSigned.code" as sel3s
import "utils/multiplexer/lookup2bit.code" as sel2
import "ecc/babyjubjubParams.code" as context
import "ecc/edwardsAdd.code" as add"""
program = []
program.append("\ndef main({}) -> (field[2]):".format(self.gen_dsl_args()))
program.append("\tcontext = context()")
program.append("\tfield[2] a = [context[2], context[3]] //Infinity")
segments = len(table)
for i in range(0, segments):
r = table[i]
program.append("\t//Round {}".format(i))
program.append(
"\tcx = sel3s([e[{}], e[{}], e[{}]], [{} , {}, {}, {}])".format(
3 * i, 3 * i + 1, 3 * i + 2, r[0].x, r[1].x, r[2].x, r[3].x
)
)
program.append(
"\tcy = sel2([e[{}], e[{}]], [{} , {}, {}, {}])".format(
3 * i, 3 * i + 1, r[0].y, r[1].y, r[2].y, r[3].y
)
)
program.append("\ta = add(a, [cx, cy], context)")
program.append("\treturn a")
return imports + "\n".join(program)
@property
def dsl_code(self):
return self.__gen_dsl_code()
def gen_dsl_args(self):
segments = self.segments
return "field[{}] e".format(segments * (WINDOW_SIZE_BITS + 1))
def write_dsl_code(self, file_name):
with open(file_name, "w+") as f:
for l in self.dsl_code:
f.write(l) | zokrates-pycrypto | /zokrates_pycrypto-0.3.0-py3-none-any.whl/zokrates_pycrypto/gadgets/pedersenHasher.py | pedersenHasher.py |
### Program: extractBiG-SCAPEclusters.py
### Author: Rauf Salamzade
### Kalan Lab
### UW Madison, Department of Medical Microbiology and Immunology
# BSD 3-Clause License
#
# Copyright (c) 2023, Kalan-Lab
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import sys
import argparse
from time import sleep
import shutil
from zol import util
lsaBGC_main_directory = '/'.join(os.path.realpath(__file__).split('/')[:-2]) + '/'
def create_parser():
""" Parse arguments """
parser = argparse.ArgumentParser(description="""
Program: extractBiG-SCAPEclusters.py
Author: Rauf Salamzade
Affiliation: Kalan Lab, UW Madison, Department of Medical Microbiology and Immunology
""", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-i', '--antismash_dir',
help='antiSMASH results directory.',
required=True)
parser.add_argument('-b', '--bigscape_dir',
help='BiG-SCAPE results directory. Should be generated using directory from "--antismash_dir" as input.',
required=True)
parser.add_argument('-o', '--output_dir', help='Parent output/workspace directory.', required=True)
parser.add_argument('-g', '--gcf_id', help='GCF ID of interest.', required=True)
parser.add_argument('-t', '--type',
help='Annotation type of BiG-SCAPE, to make sure GCFs with same IDs across different annotation classes are not used (not required but recommended).',
required=False, default=None)
parser.add_argument('-s', '--use_symlink', action='store_true', help='Use symlink instead of performing a deep copy of the file.', default=False, required=False)
args = parser.parse_args()
return args
def extractBiGSCAPEclusters():
"""
Void function which runs primary workflow for program.
"""
"""
PARSE INPUTS
"""
myargs = create_parser()
antismash_dir = os.path.abspath(myargs.antismash_dir) + '/'
bigscape_dir = os.path.abspath(myargs.bigscape_dir) + '/'
outdir = os.path.abspath(myargs.output_dir) + '/'
gcf_id = myargs.gcf_id
type = myargs.type
use_symlink = myargs.use_symlink
try:
assert (os.path.isdir(antismash_dir) and os.path.isdir(bigscape_dir))
except:
sys.stderr.write('Issue with validating that the antismash and bigscape directories provided are valid.\n')
sys.exit(1)
try:
assert (util.is_integer(gcf_id))
except:
raise RuntimeError('Issue with path to BGC predictions Genbanks listing file.')
if os.path.isdir(outdir):
sys.stderr.write("Output directory exists. Overwriting in 5 seconds ...\n ")
sleep(5)
gbk_dir = outdir + "GeneCluster_GenBanks/"
util.setupReadyDirectory([outdir, gbk_dir])
"""
START WORKFLOW
"""
# create logging object
log_file = outdir + 'Progress.log'
logObject = util.createLoggerObject(log_file)
version_string = util.parseVersionFromSetupPy()
logObject.info('Running zol version %s' % version_string)
sys.stderr.write('Running zol version %s' % version_string)
logObject.info("Saving parameters for future records.")
parameters_file = outdir + 'Parameter_Inputs.txt'
parameter_values = [antismash_dir, bigscape_dir, outdir, gcf_id, type, use_symlink]
parameter_names = ["AntiSMASH Results Directory", "BiG-SCAPE Results Directory", "Output Directory of Extracted GenBanks",
"GCF_ID", "Type of BGC for Focal GCF ID", "Use Symlink instead of Copy"]
util.logParametersToFile(parameters_file, parameter_names, parameter_values)
logObject.info("Done saving parameters!")
# Step 1: Parse BiG-SCAPE Results - Get Relevant BGCs and Samples
gcf_bgcs = set([])
for dirpath, dirnames, files in os.walk(bigscape_dir):
for filename in files:
if filename.endswith(".tsv") and "clustering" in filename:
cluster_tsv = os.path.join(dirpath, filename)
cluster_annotation_type = cluster_tsv.split('/')[-2]
if type != None and type != cluster_annotation_type: continue
with open(cluster_tsv) as oct:
for i, line in enumerate(oct):
if i == 0: continue
line = line.strip()
bgc_id, clust_gcf_id = line.split('\t')
if not clust_gcf_id == gcf_id: continue
gcf_bgcs.add(bgc_id)
try:
assert (len(gcf_bgcs) >= 1)
except:
logObject.error('Less than one BGC found to belong to the GCF.')
sys.stderr.write('Error: Less than one BGC found to belong to the GCF.\n')
sys.exit(1)
# Step 2: Parse through AntiSMASH Results and Copy over to Output Directory
for dirpath, dirnames, files in os.walk(antismash_dir):
for filename in files:
if filename.endswith('.gbk'):
gbk_file = os.path.join(dirpath, filename)
if '.region' in gbk_file:
bgc = filename.split('.gbk')[0]
if bgc in gcf_bgcs:
if use_symlink:
os.system('ln -s %s %s' % (gbk_file, gbk_dir))
else:
shutil.copyfile(gbk_file, gbk_dir)
if __name__ == '__main__':
extractBiGSCAPEclusters() | zol | /zol-1.2.1-py3-none-any.whl/zol-1.2.1.data/scripts/extractBiG-SCAPEclusters.py | extractBiG-SCAPEclusters.py |
### Program: runProdigalAndMakeProperGenbank.py
### Author: Rauf Salamzade
### Kalan Lab
### UW Madison, Department of Medical Microbiology and Immunology
# BSD 3-Clause License
#
# Copyright (c) 2021, Kalan-Lab
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import sys
import argparse
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
from Bio.SeqFeature import SeqFeature, FeatureLocation
from collections import defaultdict
from zol import util
import subprocess
from operator import itemgetter
def create_parser():
""" Parse arguments """
parser = argparse.ArgumentParser(description="""
Program: runProdigalAndMakeProperGenbank.py
Author: Rauf Salamzade
Affiliation: Kalan Lab, UW Madison, Department of Medical Microbiology and Immunology
Program to run prodigal gene calling and then create a genbank file with CDS features. Final genome-wide predicted
proteomes + genbank will be edited to have locus tags provided with the "-l" option.
11/17/2022 - can now use pyrodigal instead of progial.
""", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-i', '--input_genomic_fasta', help='Path to genomic assembly in FASTA or GenBank (needed for Eukaryotes) format.', required=True)
parser.add_argument('-o', '--output_directory', help='Path to output directory. Should already be created!', required=True)
parser.add_argument('-s', '--sample_name', help='Sample name', default='Sample', required=False)
parser.add_argument('-l', '--locus_tag', help='Locus tag', default='AAA', required=False)
parser.add_argument('-p', '--use_prodigal', action='store_true', help='Use prodigal instead of pyrodigal.', required=False, default=False)
parser.add_argument('-m', '--meta_mode', action='store_true', help='Use meta mode instead of single for pyrodigal/prodigal.', default=False, required=False)
args = parser.parse_args()
return args
def prodigalAndReformat():
"""
Void function which runs primary workflow for program.
"""
"""
PARSE REQUIRED INPUTS
"""
myargs = create_parser()
input_genomic_fasta_file = os.path.abspath(myargs.input_genomic_fasta)
outdir = os.path.abspath(myargs.output_directory) + '/'
use_prodigal = myargs.use_prodigal
meta_mode = myargs.meta_mode
try:
assert(os.path.isfile(input_genomic_fasta_file))
except:
raise RuntimeError('Issue with input genomic assembly file path.')
if not os.path.isdir(outdir):
sys.stderr.write("Output directory does not exist! Please create and retry program.")
"""
PARSE OPTIONAL INPUTS
"""
sample_name = myargs.sample_name
locus_tag = myargs.locus_tag
"""
START WORKFLOW
"""
# check if uncompression needed
try:
if input_genomic_fasta_file.endswith('.gz'):
os.system('cp %s %s' % (input_genomic_fasta_file, outdir))
updated_genomic_fasta_file = outdir + input_genomic_fasta_file.split('/')[-1].split('.gz')[0]
os.system('gunzip %s' % (updated_genomic_fasta_file + '.gz'))
input_genomic_fasta_file = updated_genomic_fasta_file
assert(util.is_fasta(input_genomic_fasta_file))
except:
raise RuntimeError('Input genomic assembly does not appear to be in FASTA format.')
# Step 1: Run Prodigal (if needed)
og_prod_pred_prot_file = outdir + sample_name + '.original_predicted_proteome'
prodigal_cmd = []
if not use_prodigal:
prodigal_cmd = ['pyrodigal', '-i', input_genomic_fasta_file, '-a', og_prod_pred_prot_file]
else:
prodigal_cmd = ['prodigal', '-i', input_genomic_fasta_file, '-a', og_prod_pred_prot_file]
if meta_mode:
prodigal_cmd += ['-p', 'meta']
subprocess.call(' '.join(prodigal_cmd), shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, executable='/bin/bash')
try:
assert(os.path.isfile(og_prod_pred_prot_file))
except:
raise RuntimeError("Prodigal did not run until the end.")
# Step 2: Process Prodigal predicted proteome and create polished version with locus tags
pc_prod_pred_prot_file = outdir + sample_name + '.faa'
pc_prod_pred_prot_handle = open(pc_prod_pred_prot_file, 'w')
scaffold_prots = defaultdict(list)
prot_sequences = {}
prot_locations = {}
with open(og_prod_pred_prot_file) as ooppf:
for i, rec in enumerate(SeqIO.parse(ooppf, 'fasta')):
if (i+1) < 10:
pid = '00000'+str(i+1)
elif (i+1) < 100:
pid = '0000'+str(i+1)
elif (i+1) < 1000:
pid = '000'+str(i+1)
elif (i+1) < 10000:
pid = '00'+str(i+1)
elif (i+1) < 100000:
pid = '0'+str(i+1)
else:
pid = str(i+1)
new_prot_id = locus_tag + '_' + pid
scaffold = '_'.join(rec.id.split('_')[:-1])
start = int(rec.description.split(' # ')[1])
end = int(rec.description.split(' # ')[2])
direction = int(rec.description.split(' # ')[3])
scaffold_prots[scaffold].append([new_prot_id, start])
prot_locations[new_prot_id] = [scaffold, start, end, direction]
prot_sequences[new_prot_id] = str(rec.seq)
dir_str = '+'
if direction == -1: dir_str = '-'
pc_prod_pred_prot_handle.write('>' + new_prot_id + ' ' + scaffold + ' ' + str(start) + ' ' + str(end) + ' ' + dir_str + '\n' + str(rec.seq) + '\n')
pc_prod_pred_prot_handle.close()
print(scaffold_prots.keys())
# Step 3: Process Prodigal predicted genbank and create polished version with locus tags and protein + nucleotide
# sequences
pc_prod_genbank_file = outdir + sample_name + '.gbk'
pc_prod_genbank_handle = open(pc_prod_genbank_file, 'w')
with open(input_genomic_fasta_file) as oigff:
for fasta_rec in SeqIO.parse(oigff, 'fasta'):
seq = fasta_rec.seq
record = SeqRecord(seq, id=fasta_rec.id, name=fasta_rec.id, description='')
record.annotations['molecule_type'] = 'DNA'
feature_list = []
for prot in sorted(scaffold_prots[fasta_rec.id], key=itemgetter(1)):
pstart = prot_locations[prot[0]][1]
pend = prot_locations[prot[0]][2]
pstrand = prot_locations[prot[0]][3]
feature = SeqFeature(FeatureLocation(start=pstart-1, end=pend, strand=pstrand), type='CDS')
feature.qualifiers['locus_tag'] = prot[0]
feature.qualifiers['translation'] = prot_sequences[prot[0]].rstrip('*')
feature_list.append(feature)
record.features = feature_list
SeqIO.write(record, pc_prod_genbank_handle, 'genbank')
pc_prod_genbank_handle.close()
if __name__ == '__main__':
prodigalAndReformat() | zol | /zol-1.2.1-py3-none-any.whl/zol-1.2.1.data/scripts/runProdigalAndMakeProperGenbank.py | runProdigalAndMakeProperGenbank.py |
### Program: findOrthologs.py
### Author: Rauf Salamzade
### Kalan Lab
### UW Madison, Department of Medical Microbiology and Immunology
# BSD 3-Clause License
#
# Copyright (c) 2022, Kalan-Lab
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import sys
import argparse
import subprocess
import concurrent.futures
from Bio import SeqIO
from collections import defaultdict
from operator import attrgetter
from zol import util
import shutil
split_diamond_results_prog = os.path.abspath(os.path.dirname(__file__) + '/') + '/splitDiamondResults'
rbh_prog = os.path.abspath(os.path.dirname(__file__) + '/') + '/runRBH'
def create_parser():
""" Parse arguments """
parser = argparse.ArgumentParser(description="""
Program: findOrthologs.py
Author: Rauf Salamzade
Affiliation: Kalan Lab, UW Madison, Department of Medical Microbiology and Immunology
Performs reflexive alignment of proteins across different protein-sets/genomes and determines orthologs,
co-orthologs, and in-paralogs.
""", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-p', '--proteome_dir',
help='Path to directory with genomes. Should end with .faa, .faa, or .fasta', required=True)
parser.add_argument('-o', '--output_dir', help='Path to output directory.', required=True)
parser.add_argument('-e', '--evalue', type=float, help='E-value cutoff for determining orthologs.', required=False, default=0.001)
parser.add_argument('-i', '--identity', type=float, help='Percent identity cutoff for determining orthologs.', required=False, default=30.0)
parser.add_argument('-q', '--coverage', type=float, help='Bi-directional coverage cutoff for determining orthologs.', required=False, default=50.0)
parser.add_argument('-c', '--cpus', type=int, help='Maximum number of CPUs to use. Default is 1.', default=1,
required=False)
args = parser.parse_args()
return args
def refactorProteomes(inputs):
sample_name, prot_file, updated_prot_file, original_naming_file, logObject = inputs
try:
updated_prot_handle = open(updated_prot_file, 'w')
original_naming_handle = open(original_naming_file, 'w')
with open(prot_file) as opf:
for i, rec in enumerate(SeqIO.parse(opf, 'fasta')):
original_naming_handle.write(
sample_name + '\t' + prot_file + '\t' + 'Protein_' + str(i) + '\t' + rec.id + '\n')
updated_prot_handle.write('>' + sample_name + '|' + 'Protein_' + str(i) + '\n' + str(rec.seq) + '\n')
original_naming_handle.close()
updated_prot_handle.close()
except Exception as e:
logObject.error('Error with refactoring proteome file.')
logObject.error(e)
sys.exit(1)
def oneVsAllParse(inputs):
sample, samp_algn_res, samp_forth_res, identity_cutoff, coverage_cutoff, logObject = inputs
rbh_cmd = [rbh_prog, samp_algn_res, str(identity_cutoff), str(coverage_cutoff), '>', samp_forth_res]
try:
subprocess.call(' '.join(rbh_cmd), shell=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, executable='/bin/bash')
assert (os.path.isfile(samp_forth_res))
except Exception as e:
logObject.error("Issue with running: %s" % ' '.join(rbh_cmd))
logObject.error(e)
raise RuntimeError(e)
os.system('rm -f %s %s' % (samp_algn_res))
def createFinalResults(concat_result_file, proteome_listing_file, original_naming_file, result_tab_file,
result_mat_file, logObject):
try:
samples = []
with open(proteome_listing_file) as oplf:
for line in oplf:
line = line.strip()
ls = line.split('\t')
samples.append('.'.join(ls[1].split('/')[-1].split('.')[:-1]))
mapping = {}
for f in os.listdir(original_naming_file):
name_file = original_naming_file + f
with open(name_file) as onf:
for line in onf:
line = line.strip()
rn_sample, og_sample, rn_protein, og_protein = line.split('\t')
og_sample = '.'.join(og_sample.split('/')[-1].split('.')[:-1])
mapping[rn_sample + '|' + rn_protein] = tuple([og_sample, og_protein])
result_tab_handle = open(result_tab_file, 'w')
result_mat_handle = open(result_mat_file, 'w')
sorted_samples = sorted(samples)
result_mat_handle.write('Sample\t' + '\t'.join(sorted_samples) + '\n')
with open(concat_result_file) as ocrf:
for line in ocrf:
line = line.strip()
ls = line.split('\t')
og = ls[0]
prots = ls[1:]
samp_prots = defaultdict(set)
for p in sorted(prots):
s, op = mapping[p]
samp_prots[s].add(op)
result_tab_handle.write(og + '\t' + s + '\t' + op + '\n')
printlist = [og]
for s in sorted_samples:
printlist.append(', '.join(sorted(samp_prots[s])))
result_mat_handle.write('\t'.join(printlist) + '\n')
result_tab_handle.close()
result_mat_handle.close()
except Exception as e:
logObject.error(e)
sys.stderr.write(e)
sys.exit(1)
def findOrthologs():
"""
Void function which runs primary workflow for program.
"""
"""
PARSE INPUTS
"""
myargs = create_parser()
proteome_dir = os.path.abspath(myargs.proteome_dir) + '/'
outdir = os.path.abspath(myargs.output_dir) + '/'
cpus = myargs.cpus
coverage_cutoff = myargs.coverage
identity_cutoff = myargs.identity
evalue_cutoff = myargs.evalue
if not os.path.isdir(outdir):
os.system('mkdir %s' % outdir)
else:
sys.stderr.write('Overwriting results file in 5 seconds! Stop now if you do not wish to proceed!\n')
# create logging object
log_file = outdir + 'Progress.log'
logObject = util.createLoggerObject(log_file)
version_string = util.parseVersionFromSetupPy()
sys.stdout.write('Running version: %s\n' % version_string)
logObject.info("Running version: %s" % version_string)
parameters_file = outdir + 'Command_Issued.txt'
sys.stdout.write("Appending command issued for future records to: %s\n" % parameters_file)
sys.stdout.write("Logging more details at: %s\n" % log_file)
logObject.info("\nNEW RUN!!!\n**************************************")
logObject.info('Running version %s' % version_string)
logObject.info("Appending command issued for future records to: %s" % parameters_file)
parameters_handle = open(parameters_file, 'a+')
parameters_handle.write(' '.join(sys.argv) + '\n')
parameters_handle.close()
local_proteome_dir = outdir + 'Proteomes/'
if not os.path.isdir(local_proteome_dir):
os.system('mkdir %s' % local_proteome_dir)
proteome_name_dir = outdir + 'Original_Naming_of_Proteomes/'
if not os.path.isdir(proteome_name_dir):
os.system('mkdir %s' % proteome_name_dir)
checkpoint_dir = outdir + 'Checkpoint_Files/'
if not os.path.isdir(checkpoint_dir):
os.system('mkdir %s' % checkpoint_dir)
sys.stdout.write("--------------------\nStep 0\n--------------------\nProcessing proteomes\n")
logObject.info("--------------------\nStep 0\n--------------------\nProcessing proteomes")
proteome_listing_file = outdir + 'Proteome_Listing.txt'
step0_checkpoint_file = checkpoint_dir + 'Step0_Checkpoint.txt'
if not os.path.isfile(step0_checkpoint_file):
try:
proteome_listing_handle = open(proteome_listing_file, 'w')
proteome_counter = 0
assert (os.path.isdir(proteome_dir))
refactor_proteomes = []
for f in sorted(os.listdir(proteome_dir)):
suffix = f.split('.')[-1]
if not suffix in set(['fa', 'faa', 'fasta']): continue
proteome_counter += 1
prot_file = proteome_dir + f
if not util.is_fasta(prot_file):
logObject.warning('File %s not in valid FASTA format and ignored.')
continue
sample_name = 'Proteome_' + str(proteome_counter)
updated_prot_file = local_proteome_dir + sample_name + '.faa'
original_naming_file = proteome_name_dir + sample_name + '.txt'
refactor_proteomes.append([sample_name, prot_file, updated_prot_file, original_naming_file, logObject])
proteome_listing_handle.write(sample_name + '\t' + prot_file + '\t' + updated_prot_file + '\n')
with concurrent.futures.ThreadPoolExecutor(max_workers=cpus) as executor:
executor.map(refactorProteomes, refactor_proteomes)
except Exception as e:
logObject.error(e)
logObject.error('Difficulties with parsing directory of proteomes.')
sys.exit(1)
proteome_listing_handle.close()
os.system('touch %s' % step0_checkpoint_file)
"""
START WORKFLOW
"""
# Step 1: Concatenate all proteins into single multi-FASTA file
sys.stdout.write("--------------------\nStep 1\n--------------------\nConcatenating proteins into multi-FASTA\n")
logObject.info("--------------------\nStep 1\n--------------------\nConcatenating proteins into multi-FASTA.")
concat_faa = outdir + 'All_Proteins.faa'
if not os.path.isfile(concat_faa):
cf_handle = open(concat_faa, 'w')
for f in os.listdir(local_proteome_dir):
with open(local_proteome_dir + f) as olf:
for rec in SeqIO.parse(olf, 'fasta'):
cf_handle.write('>' + rec.id + '\n' + str(rec.seq) + '\n')
cf_handle.close()
########### Perform Intra-Cluster RBH using reflexive DIAMOND alignment + SwiftOrtho's find_orth.py
# Step 2: Perform reflexive alignment via Diamond
sys.stdout.write("--------------------\nStep 2\n--------------------\nRunning reflexive alignment using Diamond\n")
logObject.info("--------------------\nStep 2\n--------------------\nRunning reflexive alignment using Diamond")
step2_checkpoint_file = checkpoint_dir + 'Step2_Checkpoint.txt'
align_res_dir = outdir + 'Alignments/'
forth_res_dir = outdir + 'Ortholog_Inference_Results/'
sample_prots = defaultdict(set)
sample_inputs = set([])
sample_listing_file = outdir + 'sample_listing.txt'
sample_listing_handle = open(sample_listing_file, 'w')
visited = set([])
try:
with open(concat_faa) as ocf:
for rec in SeqIO.parse(ocf, 'fasta'):
sample = rec.id.split('|')[0]
sample_prots[sample].add(rec.id)
samp_algn_res = align_res_dir + sample + '.out'
samp_forth_res = forth_res_dir + sample + '.abc-like'
sample_inputs.add(tuple([sample, samp_algn_res, samp_forth_res]))
if not sample in visited:
sample_listing_handle.write(sample + '\t' + align_res_dir + sample + '.out\n')
visited.add(sample)
except Exception as e:
raise RuntimeError(e)
sample_listing_handle.close()
if not os.path.isfile(step2_checkpoint_file):
os.system('mkdir %s' % align_res_dir)
db_path = outdir + 'All_Proteins.dmnd'
diamond_makedb_cmd = ['diamond', 'makedb', '--ignore-warnings', '--in', concat_faa, '-d', db_path]
try:
subprocess.call(' '.join(diamond_makedb_cmd), shell=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, executable='/bin/bash')
assert (os.path.isfile(db_path))
except Exception as e:
logObject.error("Issue with running: %s" % ' '.join(diamond_makedb_cmd))
logObject.error(e)
raise RuntimeError(e)
alignment_result_file = outdir + 'Reflexive_Alignment.out'
diamond_blastp_cmd = ['diamond', 'blastp', '--ignore-warnings', '-d', db_path, '-q', concat_faa, '-o',
alignment_result_file, '--outfmt', '6', 'qseqid', 'sseqid', 'pident', 'length',
'mismatch', 'gapopen', 'qstart', 'qend', 'sstart', 'send', 'evalue', 'bitscore',
'qcovhsp', '-k0', '--very-sensitive', '-e', str(evalue_cutoff), '--masking', '0', '-p',
str(cpus)]
try:
subprocess.call(' '.join(diamond_blastp_cmd), shell=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, executable='/bin/bash')
assert (os.path.isfile(alignment_result_file))
except Exception as e:
logObject.error("Issue with running: %s" % ' '.join(diamond_blastp_cmd))
logObject.error(e)
raise RuntimeError(e)
split_diamond_cmd = [split_diamond_results_prog, alignment_result_file, sample_listing_file]
try:
subprocess.call(' '.join(split_diamond_cmd), shell=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, executable='/bin/bash')
except Exception as e:
logObject.error("Issue with running: %s" % ' '.join(split_diamond_cmd))
logObject.error(e)
raise RuntimeError(e)
os.system('touch %s' % step2_checkpoint_file)
sys.stdout.write("--------------------\nStep 3\n--------------------\nRunning RBH.\n")
logObject.info("--------------------\nStep 3\n--------------------\nRunning RBH.")
scaled_find_orthos_result_file = outdir + 'All.normalized.abc-like'
step3_checkpoint_file = checkpoint_dir + 'Step3_Checkpoint.txt'
if not os.path.isfile(step3_checkpoint_file):
os.system('mkdir %s' % forth_res_dir)
find_orthos_result_file = outdir + 'All.abc-like'
parallelize_inputs = []
for inp_tup in sample_inputs:
parallelize_inputs.append(list(inp_tup) + [identity_cutoff, coverage_cutoff, logObject])
with concurrent.futures.ThreadPoolExecutor(max_workers=cpus) as executor:
executor.map(oneVsAllParse, parallelize_inputs)
os.system('cat %s* > %s' % (forth_res_dir, find_orthos_result_file))
scaled_find_orthos_result_handle = open(scaled_find_orthos_result_file, 'w')
qh_pairs_accounted = set([])
qshs_rbh = defaultdict(int)
qshs_rbh_sum = defaultdict(float)
with open(find_orthos_result_file) as osforf:
for line in osforf:
line = line.strip()
query, query_samp, hit, hit_samp, bs = line.split('\t')
qh_pair = tuple(sorted([query, hit]))
if qh_pair in qh_pairs_accounted: continue
qh_pairs_accounted.add(qh_pair)
sample_pair = tuple(sorted([query_samp, hit_samp]))
qshs_rbh[sample_pair] += 1
qshs_rbh_sum[sample_pair] += float(bs)
qshs_rbh_avg = {}
for sp in qshs_rbh:
qshs_rbh_avg[sp] = qshs_rbh_sum[sp]/qshs_rbh[sp]
qh_pairs_accounted = set([])
with open(find_orthos_result_file) as osforf:
for line in osforf:
line = line.strip()
query, query_samp, hit, hit_samp, bs = line.split('\t')
qh_pair = tuple(sorted([query, hit]))
if qh_pair in qh_pairs_accounted: continue
qh_pairs_accounted.add(qh_pair)
if query_samp == hit_samp:
scaled_find_orthos_result_handle.write(query + '\t' + hit + '\t' + str(float(bs)/100.0) + '\n')
else:
sample_pair = tuple(sorted([query_samp, hit_samp]))
scaled_find_orthos_result_handle.write(query + '\t' + hit + '\t' + str(float(bs)/qshs_rbh_avg[sample_pair]) + '\n')
scaled_find_orthos_result_handle.close()
sys.stdout.write("--------------------\nStep 4\n--------------------\nRun MCL to determine OrthoGroups.\n")
logObject.info("--------------------\nStep 4\n--------------------\nRun MCL to determine OrthoGroups.")
tmp_result_file = outdir + 'Tmp_Results.txt'
step4_checkpoint_file = checkpoint_dir + 'Step4_Checkpoint.txt'
if not os.path.isfile(step4_checkpoint_file):
cluster_result_file = outdir + 'MCL_Cluster_Results.txt'
find_clusters_cmd = ['mcl', scaled_find_orthos_result_file, '--abc', '-I', '1.5', '-te',
str(cpus), '-o', cluster_result_file]
try:
subprocess.call(' '.join(find_clusters_cmd), shell=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, executable='/bin/bash')
assert (os.path.isfile(cluster_result_file))
except Exception as e:
logObject.error("Issue with running: %s" % ' '.join(find_clusters_cmd))
logObject.error(e)
raise RuntimeError(e)
result_handle = open(tmp_result_file, 'w')
subclust_id = 1
clustered = set([])
with open(cluster_result_file) as omrf:
for line in sorted([l for l in omrf.readlines()]):
line = line.strip()
ls = line.split()
clustered = clustered.union(set(ls))
result_handle.write('OG_' + str(subclust_id) + '\t' + '\t'.join(ls) + '\n')
subclust_id += 1
with open(concat_faa) as ocf:
fasta_dict = SeqIO.to_dict(SeqIO.parse(ocf, "fasta"))
for rec in sorted(fasta_dict.values(), key=attrgetter('id')):
if not rec.id in clustered:
result_handle.write('OG_' + str(subclust_id) + '\t' + rec.id + '\n')
subclust_id += 1
result_handle.close()
#os.system('rm %s %s' % (alignment_result_file, cluster_result_file))
#shutil.rmtree(forth_res_dir)
#shutil.rmtree(align_res_dir)
os.system('touch %s' % step4_checkpoint_file)
step5_checkpoint_file = checkpoint_dir + 'Step5_Checkpoint.txt'
sys.stdout.write("--------------------\nStep 5\n--------------------\nCreate final result files!\n")
logObject.info("--------------------\nStep 5\n--------------------\nCreate final result files!")
result_tab_file = outdir + 'Orthogroups.Listing.tsv'
result_mat_file = outdir + 'Orthogroups.tsv'
if not os.path.isfile(step5_checkpoint_file):
os.system('touch %s' % step5_checkpoint_file)
createFinalResults(tmp_result_file, proteome_listing_file, proteome_name_dir, result_tab_file,
result_mat_file, logObject)
os.system('touch %s' % step5_checkpoint_file)
# DONE!
sys.stdout.write(
"--------------------\nDONE!\n--------------------\nOrthogroup by sample matrix can be found at: %s\n" % result_mat_file)
logObject.info(
"--------------------\nDONE!\n--------------------\nOrthogroup by sample matrix can be found at: %s" % result_mat_file)
if __name__ == '__main__':
findOrthologs() | zol | /zol-1.2.1-py3-none-any.whl/zol-1.2.1.data/scripts/findOrthologs.py | findOrthologs.py |
import os
import sys
import pandas
import argparse
from time import sleep
from zol import util
import subprocess
from Bio import SeqIO
def create_parser():
""" Parse arguments """
parser = argparse.ArgumentParser(description="""
Program: expandDereplicatedAlignment.py
Author: Rauf Salamzade
Affiliation: Kalan Lab, UW Madison, Department of Medical Microbiology and Immunology
Script to use query protein sequences for some orthogroup to search a set of homologous-gene clusters and produce
a multiple sequence alignment (MSA). Can optionally run FastTree for gene-phylogeny construction and HyPhy's
GARD and FUBAR for site-specific selection analysis.
This is primarily intended for creating a comprehensive MSA after running zol in "dereplicated" mode and identifying
distinct ortholog groups. It is much more computationally tractable than running zol with a full set of highly
redundant gene-clusters.
Note query files will not be included in resulting MSA/gene-tree.
""", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-i', '--input_dir', help='Directory with orthologous/homologous locus-specific GenBanks.\nFiles must end with ".gbk", ".gbff", or ".genbank".', required=False, default=None)
parser.add_argument('-q', '--query_prots', help='Query protein(s) provided in FASTA format.', required=True)
parser.add_argument('-o', '--output_dir', help='Path to output directory.', required=True)
parser.add_argument('-mi', '--min_identity', type=float, help='Minimum identity to a known instance (sequence in query). Default is 95.0.', required=False, default=95.0)
parser.add_argument('-mc', '--min_coverage', type=float, help='Minimum query coverage of a known instance (sequence in query). Default is 95.0.', required=False, default=95.0)
parser.add_argument('-c', '--cpus', type=int, help='Number of cpus/threads to use. Default is 1.', required=False, default=1)
parser.add_argument('-f', '--run_fasttree', action='store_true', help='Run FastTree for approximate maximum-likelihood phylogeny generation of the orthogroup.', required=False, default=False)
args = parser.parse_args()
return args
def expandOg():
"""
PARSE INPUTS
"""
myargs = create_parser()
input_dir = os.path.abspath(myargs.input_dir) + '/'
query_fasta = myargs.query_prots
outdir = os.path.abspath(myargs.output_dir) + '/'
min_identity = myargs.min_identity
min_coverage = myargs.min_coverage
cpus = myargs.cpus
run_fasttree = myargs.run_fasttree
try:
assert(os.path.isdir(input_dir) and util.is_fasta(query_fasta))
except:
sys.stderr.write('Error validating input directory of homologous gene-clusters or the query fasta exists!\n')
if os.path.isdir(outdir):
sys.stderr.write("Output directory exists. Overwriting in 5 seconds ...\n")
#sleep(5)
else:
os.mkdir(outdir)
db_faa = outdir + 'Database.faa'
db_dmnd = outdir + 'Database.dmnd'
db_handle = open(db_faa, 'w')
for f in os.listdir(input_dir):
if util.is_genbank(input_dir + f):
with open(input_dir + f) as of:
for rec in SeqIO.parse(of, 'genbank'):
for feature in rec.features:
if not feature.type == 'CDS': continue
lt = feature.qualifiers.get('locus_tag')[0]
translation = feature.qualifiers.get('translation')[0]
db_handle.write('>' + '.'.join(f.split('.')[:-1]) + '|' + lt + '\n' + translation + '\n')
db_handle.close()
align_result_file = outdir + 'DIAMOND_Results.txt'
diamond_cmd = ['diamond', 'makedb', '--ignore-warnings', '--in', db_faa, '-d', db_dmnd, ';',
'diamond', 'blastp', '--ignore-warnings', '--threads', str(cpus), '--very-sensitive', '--query',
query_fasta, '--db', db_dmnd, '--outfmt', '6', 'qseqid', 'sseqid',
'pident', 'length', 'mismatch', 'gapopen', 'qstart', 'qend', 'sstart', 'send', 'evalue',
'bitscore', 'qcovhsp', 'scovhsp', '-k0', '--out', align_result_file, '--evalue', '1e-3']
try:
subprocess.call(' '.join(diamond_cmd), shell=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, executable='/bin/bash')
assert (os.path.isfile(align_result_file))
except Exception as e:
print(' '.join(diamond_cmd))
raise RuntimeError(e)
matching_lts = set([])
with open(align_result_file) as oarf:
for line in oarf:
line = line.strip()
qseqid, sseqid, pident, length, mismatch, gapone, qstart, qend, sstart, send, evalue, bitscore, qcovhsp, scovhsp = line.split('\t')
pident = float(pident)
qcovhsp = float(qcovhsp)
if qcovhsp >= min_coverage and pident >= min_identity:
matching_lts.add(sseqid)
orthogroup_seqs_faa = outdir + 'OrthoGroup.faa'
orthogroup_seqs_handle = open(orthogroup_seqs_faa, 'w')
with open(db_faa) as odf:
for rec in SeqIO.parse(odf, 'fasta'):
if rec.id in matching_lts:
orthogroup_seqs_handle.write('>' + rec.id + '\n' + str(rec.seq) + '\n')
orthogroup_seqs_handle.close()
orthogroup_seqs_msa = outdir + 'OrthoGroup.msa.faa'
muscle_cmd = ['muscle', '-super5', orthogroup_seqs_faa, '-output', orthogroup_seqs_msa, '-amino', '-threads', str(cpus)]
try:
subprocess.call(' '.join(muscle_cmd), shell=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, executable='/bin/bash')
assert (os.path.isfile(orthogroup_seqs_msa))
except Exception as e:
raise RuntimeError(e)
phylogeny_tre = outdir + 'OrthoGroup.tre'
if run_fasttree:
fasttree_cmd = ['fasttree', orthogroup_seqs_msa, '>', phylogeny_tre]
try:
subprocess.call(' '.join(fasttree_cmd), shell=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, executable='/bin/bash')
assert (os.path.isfile(align_result_file))
except Exception as e:
raise RuntimeError(e)
if __name__ == '__main__':
expandOg() | zol | /zol-1.2.1-py3-none-any.whl/zol-1.2.1.data/scripts/expandDereplicatedAlignment.py | expandDereplicatedAlignment.py |
### Program: convertMiniprotGffToGbkAndProt.py
### Author: Rauf Salamzade
### Kalan Lab
### UW Madison, Department of Medical Microbiology and Immunology
# BSD 3-Clause License
#
# Copyright (c) 2021, Kalan-Lab
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import sys
import argparse
import re
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.SeqFeature import SeqFeature, FeatureLocation
from collections import defaultdict
import subprocess
from operator import itemgetter
def create_parser():
""" Parse arguments """
parser = argparse.ArgumentParser(description="""
Program: convertMiniprotGffToGbkAndProt.py
Author: Rauf Salamzade
Affiliation: Kalan Lab, UW Madison, Department of Medical Microbiology and Immunology
""", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-g', '--miniprot_gff3', help='Path to miniprot produced GFF3.', required=True)
parser.add_argument('-f', '--genome_fasta', help='Path to target genome used for miniprot.', required=True)
parser.add_argument('-og', '--output_genbank', help='Path to output GenBank.', required=True)
parser.add_argument('-op', '--output_proteome', help='Path to output Proteome (FASTA format).', required=True)
parser.add_argument('-l', '--locus_tag', help='Locus tag. Default is AAA.', required=False, default='AAA')
args = parser.parse_args()
return args
def convertMiniProtGFFtoGenbank():
myargs = create_parser()
genome_fasta = myargs.genome_fasta
miniprot_gff3 = myargs.miniprot_gff3
output_genbank = myargs.output_genbank
output_proteome = myargs.output_proteome
locus_tag = myargs.locus_tag
try:
assert (os.path.isfile(genome_fasta) and os.path.isfile(miniprot_gff3))
except:
raise RuntimeError('Issue with validating inputs for miniprot_gff3 and/or genome_fasta are existing files.')
# Step 1: Parse GFF3 for PAF CIGAR Strings
query_mrna_paf_info = defaultdict(list)
paf = None
with open(miniprot_gff3) as omg:
for line in omg:
line = line.strip()
ls = line.split('\t')
if line.startswith('##PAF'):
paf = ls[1:]
elif len(ls) >= 6:
if ls[2] == 'mRNA' and paf != None:
query = line.split('Target=')[1].split(';')[0].split()[0]
mrna_start_coord = int(ls[3])
mrna_end_coord = int(ls[4])
scaffold = ls[0]
paf_start_coord = int(paf[7])
paf_end_coord = int(paf[8])
mrna_coords = set(range(mrna_start_coord, mrna_end_coord+1))
paf_coords = set(range(paf_start_coord, paf_end_coord+1))
if len(mrna_coords.intersection(paf_coords))/len(paf_coords) >= 0.95 and len(mrna_coords.intersection(paf_coords))/len(paf_coords) <= 1.05:
paf_cigar = paf[17]
paf_matches = re.findall(r'(\d+)([A-Z]{1})', paf_cigar)
paf_cigar_parsed = [{'type': m[1], 'length': int(m[0])} for m in paf_matches]
query_mrna_paf_info[tuple([query, mrna_start_coord])] = [scaffold, paf_start_coord, paf_end_coord, paf_cigar_parsed, '\t'.join(paf)]
else:
paf = None
# Step 1: Parse GFF3 for transcript coordinates
query_mrna_coords = defaultdict(list)
scaffold_queries = defaultdict(list)
with open(miniprot_gff3) as omg:
for line in omg:
line = line.strip()
if line.startswith('#'): continue
ls = line.split('\t')
if ls[2] != 'mRNA': continue
query = line.split('Target=')[1].split(';')[0].split()[0]
scaffold = ls[0]
start_coord = int(ls[3])
end_coord = int(ls[4])
score = float(ls[5])
identity = float(ls[8].split('Identity=')[1].split(';')[0].split()[0])
if identity < 0.80: continue
dire = 1
if ls[6] == '-':
dire = -1
# in case there are paralogs
query_mrna_coords[tuple([query, start_coord])] = [scaffold, start_coord, end_coord, dire, score]
scaffold_queries[scaffold].append([query, start_coord])
# Step 2: Resolve overlap between mRNA transcripts
redundant = set([])
for i, mrna1 in enumerate(sorted(query_mrna_coords.items())):
m1_coords = set(range(mrna1[1][1], mrna1[1][2]))
m1_score = mrna1[1][4]
for j, mrna2 in enumerate(sorted(query_mrna_coords.items())):
if i >= j: continue
# check scaffolds are the same
if mrna1[1][0] != mrna2[1][0]: continue
m2_coords = set(range(mrna2[1][1], mrna2[1][2]))
if len(m1_coords.intersection(m2_coords)) > 0:
m2_score = mrna2[1][4]
if m1_score >= m2_score:
redundant.add(mrna2[0])
else:
redundant.add(mrna1[0])
# Step 3: Parse GFF3 for CDS coordinates
query_cds_coords = defaultdict(list)
with open(miniprot_gff3) as omg:
for line in omg:
line = line.strip()
if line.startswith('#'): continue
ls = line.split('\t')
if ls[2] != 'CDS': continue
query = line.split('Target=')[1].split(';')[0].split()[0]
scaffold = ls[0]
start_coord = int(ls[3])
end_coord = int(ls[4])
dire = 1
if ls[6] == '-':
dire = -1
query_cds_coords[query].append([scaffold, start_coord, end_coord, dire])
# Step 4: Go through FASTA scaffold/contig by scaffold/contig and create output GenBank
gbk_handle = open(output_genbank, 'w')
faa_handle = open(output_proteome, 'w')
lt_iter = 0
with open(genome_fasta) as ogf:
for rec in SeqIO.parse(ogf, 'fasta'):
seq = rec.seq
gbk_rec = SeqRecord(seq, id=rec.id, name=rec.id, description=rec.description)
gbk_rec.annotations['molecule_type'] = 'DNA'
feature_list = []
for mrna in sorted(scaffold_queries[rec.id], key=itemgetter(1)):
qid, start = mrna
key = tuple([qid, start])
if key in redundant: continue
mrna_info = query_mrna_coords[key]
mrna_coords = set(range(mrna_info[1], mrna_info[2]))
mrna_exon_locs = []
all_coords = []
for cds_info in query_cds_coords[qid]:
cds_coords = set(range(cds_info[1], cds_info[2]))
if len(mrna_coords.intersection(cds_coords)) > 0 and cds_info[0] == mrna_info[0]:
all_coords.append([cds_info[1], cds_info[2]])
assert(mrna_info[3] == cds_info[3])
mrna_exon_locs.append(FeatureLocation(cds_info[1]-1, cds_info[2], strand=cds_info[3]))
feature_loc = sum(mrna_exon_locs)
feature = SeqFeature(feature_loc, type='CDS')
lt = None
if (lt_iter + 1) < 10:
lt = '00000' + str(lt_iter + 1)
elif (lt_iter + 1) < 100:
lt = '0000' + str(lt_iter + 1)
elif (lt_iter + 1) < 1000:
lt = '000' + str(lt_iter + 1)
elif (lt_iter + 1) < 10000:
lt = '00' + str(lt_iter + 1)
elif (lt_iter + 1) < 100000:
lt = '0' + str(lt_iter + 1)
else:
lt = str(lt_iter + 1)
lt_iter += 1
"""
nucl_seq = ''
prot_seq = None
for sc, ec in sorted(all_coords, key=itemgetter(0)):
if ec >= len(seq):
nucl_seq += seq[sc - 1:]
else:
nucl_seq += seq[sc - 1:ec]
if mrna_info[3] == -1:
prot_seq = str(Seq(nucl_seq).reverse_complement().translate())
else:
prot_seq = str(Seq(nucl_seq).translate())
assert(prot_seq != None)
"""
scaffold, paf_start_coord, paf_end_coord, paf_cigar_parsed, paf_string = query_mrna_paf_info[key]
paf_nucl_seq = ''
paf_coord = paf_start_coord
if mrna_info[3] == -1:
paf_cigar_parsed.reverse()
for op in paf_cigar_parsed:
length = op['length']
if op['type'] == 'M':
paf_nucl_seq += seq[paf_coord:(paf_coord+(length*3))]
paf_coord += length*3
elif op['type'] == 'D':
paf_coord += length*3
elif op['type'] == 'G':
#paf_coord += seq[paf_coord:paf_coord+length]
paf_coord += length
elif op['type'] in set(['F', 'N', 'U', 'V']):
paf_coord += length
paf_prot_seq = None
paf_upstream_nucl_seq = None
#paf_upstream_check = None
if mrna_info[3] == -1:
paf_nucl_seq = str(Seq(paf_nucl_seq).reverse_complement())
paf_prot_seq = str(Seq(paf_nucl_seq).translate())
paf_upstream_nucl_seq = str(Seq(seq[paf_end_coord:paf_end_coord+100]).reverse_complement())
#paf_upstream_check = str(Seq(seq[paf_end_coord-1:paf_end_coord+99]).reverse_complement())
else:
paf_prot_seq = str(Seq(paf_nucl_seq).translate())
paf_upstream_nucl_seq = seq[paf_start_coord-100:paf_start_coord]
"""
print('----------------------')
print(paf_string)
print(locus_tag + '_' + lt)
print(paf_nucl_seq)
print('++++++++++++++++++++++')
print(paf_upstream_nucl_seq)
print('++++++++++++++++++++++')
print(paf_upstream_check)
#print(paf_prot_seq)
"""
faa_handle.write('>' + locus_tag + '_' + lt + '\n' + paf_prot_seq + '\n')
feature.qualifiers['locus_tag'] = locus_tag + '_' + lt
feature.qualifiers['translation'] = paf_prot_seq
feature.qualifiers['open_reading_frame'] = paf_nucl_seq
feature.qualifiers['orf_upstream'] = paf_upstream_nucl_seq
feature_list.append(feature)
gbk_rec.features = feature_list
SeqIO.write(gbk_rec, gbk_handle, 'genbank')
gbk_handle.close()
faa_handle.close()
if __name__ == '__main__':
convertMiniProtGFFtoGenbank() | zol | /zol-1.2.1-py3-none-any.whl/zol-1.2.1.data/scripts/convertMiniprotGffToGbkAndProt.py | convertMiniprotGffToGbkAndProt.py |
### Program: listAllGenomesInDirectory.py
### Author: Rauf Salamzade
### Kalan Lab
### UW Madison, Department of Medical Microbiology and Immunology
# BSD 3-Clause License
#
# Copyright (c) 2021, Kalan-Lab
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import argparse
import sys
def create_parser():
""" Parse arguments """
parser = argparse.ArgumentParser(description="""
Program: listAllGenomesInDirectory.py
Author: Rauf Salamzade
Affiliation: Kalan Lab, UW Madison, Department of Medical Microbiology and Immunology
Program to create genomic listing file needed for lsaBGC-Ready.py. Provided a directory
with genomes, such as those generated by ncbi-genome-download, it will create a two-column,
tab-delimited listing file where the first column is the sample name and the second is the
full path to the genomic assembly in FASTA or Genbank format. It will recursively search so they
do not need to be in the main level of the directory structure.
If --list_cmds is specified together with other complementary option
""", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-i', '--input_genomes_dir', help='Path to genomic assembly in FASTA/Genbank format.',
required=True)
parser.add_argument('-z', '--uncompress', action='store_true', help='Whether to uncompress genomes files.',
required=False, default=False)
parser.add_argument('-u', '--uncompress_dir',
help='Path to temporary directory where to unzip genomic assembly files if requested and update paths listed accordingly.',
required=False, default='./Uncompressed_Genomes/')
parser.add_argument('-l', '--list_cmds', action='store_true',
help='List BGC commands instead of producing a sample to genome mapping file needed for input into lsaBGC-Ready.py.',
required=False, default=False)
parser.add_argument('-o', '--bgc_prediction_dir',
help='Path to output directory to list for BGC prediction output.',
default='./BGC_Predictions/', required=False)
parser.add_argument('-p', '--bgc_prediction_software',
help='Software used to predict BGCs (Options: antiSMASH, DeepBGC, GECCO).\nDefault is antiSMASH.',
default='antiSMASH', required=False)
parser.add_argument('-c', '--cpus', help='Number of cpus to specify per job.', required=False, default=4)
parser.add_argument('-t', '--taxon',
help='Taxon class to provide BGC prediction software, e.g. antiSMASH. Options: bacteri, fungi. Default: bacteria',
default="bacteria", required=False)
parser.add_argument('-d', '--dryrun_naming_file',
help='Results from running ncbi-genome-download in dry-run mode to use for sample naming.',
required=False, default=None)
args = parser.parse_args()
return args
def siftAndPrint():
"""
Void function which runs primary workflow for program.
"""
"""
PARSE INPUTS
"""
myargs = create_parser()
input_genomes_dir = os.path.abspath(myargs.input_genomes_dir) + '/'
uncompress_flag = myargs.uncompress
uncompress_dir = os.path.abspath(myargs.uncompress_dir) + '/'
bgc_prediction_dir = os.path.abspath(myargs.bgc_prediction_dir) + '/'
list_cmds_flag = myargs.list_cmds
bgc_prediction_software = myargs.bgc_prediction_software.upper()
cpus = myargs.cpus
taxon = myargs.taxon.lower()
dryrun_naming_file = myargs.dryrun_naming_file
genome_id_to_sample_name = {}
if dryrun_naming_file != None:
try:
assert (os.path.isfile(dryrun_naming_file))
except:
raise RuntimeError('Cannot locate the ncbi-genome-download dryrun naming file provided.')
try:
assert (os.path.isdir(input_genomes_dir))
except:
raise RuntimeError('Cannot find input directory of genomes directory.')
try:
assert (os.path.isdir(uncompress_dir))
except:
os.system('mkdir %s' % uncompress_dir)
try:
assert (os.path.isdir(uncompress_dir))
except:
raise RuntimeError('Cannot find/create directory for uncompressing genomes.')
try:
assert (os.path.isdir(bgc_prediction_dir))
except:
if list_cmds_flag:
os.system('mkdir %s' % bgc_prediction_dir)
try:
assert (os.path.isdir(bgc_prediction_dir))
except:
raise RuntimeError('Cannot find/create output directory for BGC prediction commands.')
try:
assert (bgc_prediction_software in set(['ANTISMASH', 'DEEPBGC', 'GECCO']))
except:
raise RuntimeError('BGC prediction software option is not a valid option.')
try:
assert (taxon in set(['bacteria', 'fungi']))
except:
raise RuntimeError('Taxon is not a valid option.')
"""
START WORKFLOW
"""
genome_id_to_sample_name = {}
if dryrun_naming_file:
with open(dryrun_naming_file) as odnf:
for line in odnf:
line = line.strip()
sample_name = '_'.join(line.split())
genome_id = line.split()[0]
genome_id_to_sample_name[genome_id] = sample_name
sample_to_genome = {}
any_file_gzipped = False
for dirpath, dirnames, files in os.walk(input_genomes_dir):
for f in files:
suffix = f.split('.')[-1]
gzip_flag = False
if suffix == 'gz':
suffix = f.split('.')[-2] + '.gz'
gzip_flag = True
any_file_gzipped = True
if not suffix in set(
['fasta', 'fna', 'fa', 'gbff', 'fasta.gz', 'fna.gz', 'fa.gz', 'gbff.gz', 'gbk', 'gbk.gz']):
sys.stderr.write(
'Warning, skipping file: %s, does not appear to have suffix expected of nucleotide FASTA files.\n' % f)
else:
sample = '.'.join(f.split('.')[:-1])
if gzip_flag:
sample = '.'.join(f.split('.')[:-2])
if sample.endswith('_genomic'):
sample = sample.split('_genomic')[0]
full_file_name = dirpath + '/' + f
if sample in sample_to_genome:
sys.stderr.write('Warning, sample %s has more than one genome, skipping second instance' % sample)
else:
sample_to_genome[sample] = full_file_name
if (uncompress_flag or list_cmds_flag) and any_file_gzipped:
for sample in sample_to_genome:
genome_file = sample_to_genome[sample]
if genome_file.endswith('.gz'):
uncompressed_genome_file = uncompress_dir + genome_file.split('/')[-1].split('.gz')[0]
os.system('cp %s %s' % (genome_file, uncompress_dir))
os.system('gunzip %s' % uncompressed_genome_file + '.gz')
try:
assert (os.path.isfile(uncompressed_genome_file))
except:
raise RuntimeError(
'Had issues creating uncompressed genome %s for sample %s' % (uncompressed_genome_file, sample))
sample_to_genome[sample] = uncompressed_genome_file
for sample in sample_to_genome:
genome_file = sample_to_genome[sample]
if dryrun_naming_file != None:
genome_id = '_'.join(genome_file.split('/')[-1].split('_')[:2])
sample = genome_id_to_sample_name[genome_id]
sample = sample.replace('#', '').replace('*', '_').replace(':', '_').replace(';', '_').replace(' ',
'_').replace(':',
'_').replace(
'|', '_').replace('"', '_').replace("'", '_').replace("=", "_").replace('-', '_').replace('(', '').replace(
')', '').replace('/', '').replace('\\', '').replace('[', '').replace(']', '').replace(',', '')
if list_cmds_flag:
bgc_cmd = None
if bgc_prediction_software == 'ANTISMASH':
gene_finding = 'prodigal'
if taxon == 'fungi':
gene_finding = 'glimmerhmm'
if genome_file.endswith('.gbff.gz') or genome_file.endswith('.gbk.gz') or genome_file.endswith(
'.gbk') or genome_file.endswith('.gbff'):
gene_finding = 'none'
bgc_cmd = ['antismash', '--taxon', taxon, '--output-dir', bgc_prediction_dir + sample + '/', '-c',
str(cpus), '--genefinding-tool', gene_finding, '--output-basename', sample, genome_file]
elif bgc_prediction_software == 'DEEPBGC':
bgc_cmd = ['deepbgc', 'pipeline', '--output', bgc_prediction_dir + sample + '/', genome_file]
elif bgc_prediction_software == 'GECCO':
if taxon == 'fungi':
raise RuntimeError("Not recommended to run GECCO with fungal genomes.")
bgc_cmd = ['gecco', 'run', '-j', str(cpus), '-o', bgc_prediction_dir + sample + '/', '-g', genome_file]
print(' '.join(bgc_cmd))
else:
print(sample + '\t' + genome_file)
if __name__ == '__main__':
siftAndPrint() | zol | /zol-1.2.1-py3-none-any.whl/zol-1.2.1.data/scripts/listAllGenomesInDirectory.py | listAllGenomesInDirectory.py |
import os
import sys
import argparse
import subprocess
from Bio import SeqIO
import shutil
zol_main_directory = '/'.join(os.path.realpath(__file__).split('/')[:-2]) + '/'
def create_parser():
""" Parse arguments """
parser = argparse.ArgumentParser(description="""
Program: setup_annotation_dbs.py
Author: Rauf Salamzade
Affiliation: Kalan Lab, UW Madison, Department of Medical Microbiology and Immunology
Downloads annotation databases for KO, PGAP,
""", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-p', '--download_path', help='Path to where the databases should be downloaded. Default is /path/to/zol_Github_clone/db/', required=False, default=zol_main_directory + 'db/')
parser.add_argument('-c', '--cpus', type=int, help="Number of cpus/threads to use.", required=False, default=4)
parser.add_argument('-m', '--minimal', action='store_true', help="Minimal mode - will only download PGAP.", required=False, default=False)
args = parser.parse_args()
return args
def setup_annot_dbs():
myargs = create_parser()
download_path = os.path.abspath(myargs.download_path) + '/'
cpus = myargs.cpus
minimal_mode = myargs.minimal
try:
assert(os.path.isdir(download_path))
except:
sys.stderr.write('Error: Provided directory for downloading annotation files does not exist!\n')
if minimal_mode:
sys.stdout.write('Minimal mode requested, will only be downloading the PGAP database.\n')
try:
shutil.rmtree(download_path)
os.mkdir(download_path)
readme_outf = open(download_path + 'README.txt', 'w')
readme_outf.write('Default space for downloading KOFam annotation databases.\n')
readme_outf.close()
except Exception as e:
sys.stderr.write('Issues clearing contents of db/ to re-try downloads.\n')
sys.stderr.write(str(e) + '\n')
sys.exit(1)
listing_file = zol_main_directory + 'db/database_location_paths.txt'
listing_handle = open(listing_file, 'w')
if minimal_mode:
# Final annotation files
pgap_info_file = download_path + 'hmm_PGAP.tsv'
pgap_phmm_file = download_path + 'PGAP.hmm'
download_links = ['https://ftp.ncbi.nlm.nih.gov/hmm/current/hmm_PGAP.HMM.tgz',
'https://ftp.ncbi.nlm.nih.gov/hmm/current/hmm_PGAP.tsv']
# Download
print('Starting download of files!')
os.chdir(download_path)
try:
for dl in download_links:
axel_download_dbs_cmd = ['axel', '-a', '-n', str(cpus), dl]
os.system(' '.join(axel_download_dbs_cmd))
except Exception as e:
sys.stderr.write('Error occurred during downloading!\n')
sys.stderr.write(str(e) + '\n')
sys.exit(1)
try:
print('Setting up PGAP database!')
os.system(' '.join(['tar', '-zxvf', 'hmm_PGAP.HMM.tgz']))
assert (os.path.isfile(pgap_info_file))
assert (os.path.isdir(download_path + 'hmm_PGAP.HMM/'))
for f in os.listdir(download_path + 'hmm_PGAP.HMM/'):
os.system(' '.join(['cat', download_path + 'hmm_PGAP.HMM/' + f, '>>', pgap_phmm_file]))
pgap_descriptions_file = download_path + 'pgap_descriptions.txt'
pdf_handle = open(pgap_descriptions_file, 'w')
with open(pgap_info_file) as opil:
for i, line in enumerate(opil):
if i == 0: continue
line = line.strip()
ls = line.split('\t')
label = ls[2]
description = ls[10]
pdf_handle.write(label + '\t' + description + '\n')
pdf_handle.close()
assert (os.path.isfile(pgap_phmm_file))
os.system(' '.join(['hmmpress', pgap_phmm_file]))
listing_handle.write('pgap\t' + pgap_descriptions_file + '\t' + pgap_phmm_file + '\n')
os.system(' '.join(
['rm', '-rf', download_path + 'hmm_PGAP.HMM/', download_path + 'hmm_PGAP.HMM.tgz', pgap_info_file]))
except Exception as e:
sys.stderr.write('Issues setting up PGAP database.\n')
sys.stderr.write(str(e) + '\n')
sys.exit(1)
else:
# Final annotation files
pfam_phmm_file = download_path + 'Pfam-A.hmm'
ko_annot_info_file = download_path + 'ko_list'
ko_phmm_file = download_path + 'profile.hmm'
pgap_info_file = download_path + 'hmm_PGAP.tsv'
pgap_phmm_file = download_path + 'PGAP.hmm'
pb_faa_file = download_path + 'paperblast.dmnd'
#pb_sql_file = download_path + 'litsearch.db'
vog_phmm_file = download_path + 'vog.hmm'
vog_info_file = download_path + 'vog.annotations.tsv'
is_faa_file = download_path + 'isfinder.dmnd'
mb_faa_file = download_path + 'mibig.dmnd'
card_faa_file = download_path + 'card.dmnd'
vfdb_faa_file = download_path + 'vfdb.dmnd'
download_links = ['https://ftp.ebi.ac.uk/pub/databases/Pfam/current_release/Pfam-A.hmm.gz',
'https://ftp.ncbi.nlm.nih.gov/hmm/current/hmm_PGAP.HMM.tgz',
'ftp://ftp.genome.jp/pub/db/kofam/profiles.tar.gz',
'http://papers.genomics.lbl.gov/data/uniq.faa',
'http://www.mgc.ac.cn/VFs/Down/VFDB_setB_pro.fas.gz',
'https://dl.secondarymetabolites.org/mibig/mibig_prot_seqs_3.1.fasta',
'http://fileshare.csb.univie.ac.at/vog/latest/vog.hmm.tar.gz',
#'http://papers.genomics.lbl.gov/data/litsearch.db'
'https://ftp.ncbi.nlm.nih.gov/hmm/current/hmm_PGAP.tsv',
'http://fileshare.csb.univie.ac.at/vog/latest/vog.annotations.tsv.gz',
'ftp://ftp.genome.jp/pub/db/kofam/ko_list.gz',
'https://raw.githubusercontent.com/thanhleviet/ISfinder-sequences/master/IS.faa',
'https://card.mcmaster.ca/download/0/broadstreet-v3.2.5.tar.bz2']
# Download
print('Starting download of files!')
os.chdir(download_path)
try:
for dl in download_links:
axel_download_dbs_cmd = ['axel', '-a', '-n', str(cpus), dl]
os.system(' '.join(axel_download_dbs_cmd))
except Exception as e:
sys.stderr.write('Error occurred during downloading!\n')
sys.stderr.write(str(e) + '\n')
sys.exit(1)
try:
print('Setting up Pfam database!')
os.system(' '.join(['gunzip', 'Pfam-A.hmm.gz']))
assert(os.path.isfile(pfam_phmm_file))
name = None
desc = None
pfam_descriptions_file = download_path + 'pfam_descriptions.txt'
pdf_handle = open(pfam_descriptions_file, 'w')
with open(pfam_phmm_file) as oppf:
for line in oppf:
line = line.strip()
ls = line.split()
if ls[0].strip() == 'NAME':
name = ' '.join(ls[1:]).strip()
elif ls[0].strip() == 'DESC':
desc = ' '.join(ls[1:]).strip()
pdf_handle.write(name + '\t' + desc + '\n')
pdf_handle.close()
os.system(' '.join(['hmmpress', pfam_phmm_file]))
listing_handle.write('pfam\t' + pfam_descriptions_file + '\t' + pfam_phmm_file + '\n')
except Exception as e:
sys.stderr.write('Issues setting up Pfam database.\n')
sys.stderr.write(str(e) + '\n')
sys.exit(1)
try:
print('Setting up KO database!')
os.system(' '.join(['gunzip', 'ko_list.gz']))
os.system(' '.join(['tar', '-zxvf', download_path + 'profiles.tar.gz']))
assert(os.path.isfile(ko_annot_info_file))
assert(os.path.isdir(download_path + 'profiles/'))
if os.path.isfile(ko_phmm_file):
os.system(' '.join(['rm', '-f', ko_phmm_file]))
for f in os.listdir(download_path + 'profiles/'):
if not f.endswith('.hmm'): continue
os.system(' '.join(['cat', download_path + 'profiles/' + f, '>>', ko_phmm_file]))
assert(os.path.isfile(ko_phmm_file))
os.system(' '.join(['hmmpress', ko_phmm_file]))
ko_descriptions_file = download_path + 'ko_descriptions.txt'
kdf_handle = open(ko_descriptions_file, 'w')
with open(ko_annot_info_file) as oaif:
for i, line in enumerate(oaif):
if i == 0: continue
line = line.strip()
ls = line.split('\t')
ko = ls[0]
if ls[1] == '-': continue
description = ls[-1]
kdf_handle.write(ko + '\t' + description + '\n')
kdf_handle.close()
listing_handle.write('ko\t' + ko_descriptions_file + '\t' + ko_phmm_file + '\n')
os.system(' '.join(['rm', '-rf', download_path + 'profiles/', download_path + 'profiles.tar.gz', ko_annot_info_file]))
except Exception as e:
sys.stderr.write('Issues setting up KO database.\n')
sys.stderr.write(str(e) + '\n')
sys.exit(1)
try:
print('Setting up PGAP database!')
os.system(' '.join(['tar', '-zxvf', 'hmm_PGAP.HMM.tgz']))
assert(os.path.isfile(pgap_info_file))
assert(os.path.isdir(download_path + 'hmm_PGAP/'))
for f in os.listdir(download_path + 'hmm_PGAP/'):
os.system(' '.join(['cat', download_path + 'hmm_PGAP/' + f, '>>', pgap_phmm_file]))
pgap_descriptions_file = download_path + 'pgap_descriptions.txt'
pdf_handle = open(pgap_descriptions_file, 'w')
with open(pgap_info_file) as opil:
for i, line in enumerate(opil):
if i == 0: continue
line = line.strip()
ls = line.split('\t')
label = ls[2]
description = ls[10]
pdf_handle.write(label + '\t' + description + '\n')
pdf_handle.close()
assert(os.path.isfile(pgap_phmm_file))
os.system(' '.join(['hmmpress', pgap_phmm_file]))
listing_handle.write('pgap\t' + pgap_descriptions_file + '\t' + pgap_phmm_file + '\n')
os.system(' '.join(['rm', '-rf', download_path + 'hmm_PGAP/', download_path + 'hmm_PGAP.HMM.tgz', pgap_info_file]))
except Exception as e:
sys.stderr.write('Issues setting up PGAP database.\n')
sys.stderr.write(str(e) + '\n')
sys.exit(1)
try:
print('Setting up MI-BiG database!')
os.system(' '.join(['diamond', 'makedb', '--in', 'mibig_prot_seqs_3.1.fasta', '-d', mb_faa_file]))
assert(os.path.isfile(mb_faa_file))
mibig_descriptions_file = download_path + 'mibig_descriptions.txt'
mdf_handle = open(mibig_descriptions_file, 'w')
with open(download_path + 'mibig_prot_seqs_3.1.fasta') as omf:
for rec in SeqIO.parse(omf, 'fasta'):
mdf_handle.write(rec.id + '\t' + rec.description + '\n')
mdf_handle.close()
listing_handle.write('mibig\t' + mibig_descriptions_file + '\t' + mb_faa_file + '\n')
os.system(' '.join(['rm', '-rf', download_path + 'mibig_prot_seqs_3.1.fasta']))
except Exception as e:
sys.stderr.write('Issues setting up MI-BiG database.\n')
sys.stderr.write(str(e) + '\n')
sys.exit(1)
try:
print('Setting up VFDB database!')
os.system(' '.join(['gunzip', 'VFDB_setB_pro.fas.gz']))
os.system(' '.join(['diamond', 'makedb', '--in', 'VFDB_setB_pro.fas', '-d', vfdb_faa_file]))
assert(os.path.isfile(mb_faa_file))
vfdb_descriptions_file = download_path + 'vfdb_descriptions.txt'
vdf_handle = open(vfdb_descriptions_file, 'w')
with open(download_path + 'VFDB_setB_pro.fas') as ovf:
for rec in SeqIO.parse(ovf, 'fasta'):
vdf_handle.write(rec.id + '\t' + rec.description + '\n')
vdf_handle.close()
listing_handle.write('vfdb\t' + vfdb_descriptions_file + '\t' + vfdb_faa_file + '\n')
os.system(' '.join(['rm', '-rf', download_path + 'VFDB_setB_pro.fas']))
except Exception as e:
sys.stderr.write('Issues setting up VFDB database.\n')
sys.stderr.write(str(e) + '\n')
sys.exit(1)
# have note in program to recommend folks check out ARTS webserver for more detailed analysis
# in finding antibiotic BGCs
try:
print('Setting up CARD database!')
os.mkdir(download_path + 'CARD_DB_Files/')
os.system(' '.join(['tar', '-xf', download_path + 'card-data.tar.bz2', '-C', download_path + 'CARD_DB_Files/']))
os.system(' '.join(['mv', download_path + 'CARD_DB_Files/protein_fasta_protein_homolog_model.fasta', download_path]))
os.system(' '.join(['diamond', 'makedb', '--in', download_path + 'protein_fasta_protein_homolog_model.fasta', '-d', card_faa_file]))
card_descriptions_file = download_path + 'card_descriptions.txt'
cdf_handle = open(card_descriptions_file, 'w')
with open(download_path + 'protein_fasta_protein_homolog_model.fasta') as ocf:
for rec in SeqIO.parse(ocf, 'fasta'):
cdf_handle.write(rec.id + '\t' + rec.description + '\n')
cdf_handle.close()
os.system(' '.join(['rm', '-rf', download_path + 'CARD_DB_Files/', download_path + 'protein_fasta_protein_homolog_model.fasta', download_path + 'card-data.tar.bz2']))
assert(os.path.isfile(card_faa_file))
listing_handle.write('card\t' + card_descriptions_file + '\t' + card_faa_file + '\n')
except Exception as e:
sys.stderr.write('Issues setting up CARD database.\n')
sys.stderr.write(str(e) + '\n')
sys.exit(1)
try:
print('Setting up VOG database!')
os.mkdir(download_path + 'VOG_HMM_Files/')
os.system(' '.join(['tar', '-xzvf', 'vog.hmm.tar.gz', '-C', download_path + 'VOG_HMM_Files/']))
os.system(' '.join(['gunzip', download_path + 'vog.annotations.tsv.gz']))
vog_db_dir = download_path + 'VOG_HMM_Files/'
for f in os.listdir(vog_db_dir):
os.system('cat %s >> %s' % (vog_db_dir + f, vog_phmm_file))
vog_descriptions_file = download_path + 'vog_descriptions.txt'
vdf_handle = open(vog_descriptions_file, 'w')
with open(download_path + 'vog.annotations.tsv') as ovf:
for i, line in enumerate(ovf):
line = line.rstrip('\n')
ls = line.split('\t')
if i == 0: continue
vdf_handle.write(ls[0] + '\t' + ls[4] + '[' + ls[3] + ']\n')
vdf_handle.close()
os.system(' '.join(['rm', '-rf', download_path + 'VOG_HMM_Files/', vog_info_file]))
assert(os.path.isfile(vog_phmm_file))
assert(os.path.isfile(vog_descriptions_file))
os.system(' '.join(['hmmpress', vog_phmm_file]))
listing_handle.write('vog\t' + vog_descriptions_file + '\t' + vog_phmm_file + '\n')
except Exception as e:
sys.stderr.write('Issues setting up VOG database.\n')
sys.stderr.write(str(e) + '\n')
sys.exit(1)
try:
print('Setting up PaperBlast database!')
pb_faa_path = download_path + 'uniq.faa'
os.system(' '.join(['diamond', 'makedb', '--in', pb_faa_path, '-d', pb_faa_file]))
paperblast_descriptions_file = download_path + 'paperblast_descriptions.txt'
pbdf_handle = open(paperblast_descriptions_file, 'w')
with open(download_path + 'uniq.faa') as opdf:
for rec in SeqIO.parse(opdf, 'fasta'):
pbdf_handle.write(rec.id + '\t' + rec.description + '\n')
pbdf_handle.close()
os.system(' '.join(['rm', '-rf', pb_faa_path]))
assert(os.path.isfile(paperblast_descriptions_file))
assert(os.path.isfile(pb_faa_file))
listing_handle.write('paperblast\t' + paperblast_descriptions_file + '\t' + pb_faa_file + '\n')
except Exception as e:
sys.stderr.write('Issues setting up PaperBlast database.\n')
sys.stderr.write(str(e) + '\n')
sys.exit(1)
try:
print('Setting up ISFinder database!')
is_faa_path = download_path + 'IS.faa'
os.system(' '.join(['diamond', 'makedb', '--in', is_faa_path, '-d', is_faa_file]))
is_descriptions_file = download_path + 'is_descriptions.txt'
idf_handle = open(is_descriptions_file, 'w')
with open(is_faa_path) as oif:
for rec in SeqIO.parse(oif, 'fasta'):
idf_handle.write(rec.id + '\t' + rec.description + '\n')
idf_handle.close()
assert(os.path.isfile(is_faa_path))
assert(os.path.isfile(is_descriptions_file))
listing_handle.write('isfinder\t' + is_descriptions_file + '\t' + is_faa_file + '\n')
os.system(' '.join(['rm', '-rf', is_faa_path]))
except Exception as e:
sys.stderr.write('Issues setting up ISFinder database.\n')
sys.stderr.write(str(e) + '\n')
sys.exit(1)
listing_handle.close()
print("Done setting up annotation databases!")
print("Information on final files used by zol can be found at:\n%s" % listing_file)
sys.exit(0)
setup_annot_dbs() | zol | /zol-1.2.1-py3-none-any.whl/zol-1.2.1.data/scripts/setup_annotation_dbs.py | setup_annotation_dbs.py |
### Program: processNCBIGenBank.py
### Author: Rauf Salamzade
### Kalan Lab
### UW Madison, Department of Medical Microbiology and Immunology
# BSD 3-Clause License
#
# Copyright (c) 2021, Kalan-Lab
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import sys
import argparse
from Bio import SeqIO
from Bio.Seq import Seq
import gzip
from zol import util
def create_parser():
""" Parse arguments """
parser = argparse.ArgumentParser(description="""
Program: processNCBIGenBank.py
Author: Rauf Salamzade
Affiliation: Kalan Lab, UW Madison, Department of Medical Microbiology and Immunology
Process NCBI Genbanks to create proteome + genbanks with specific locus tag.
""", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-i', '--input_ncbi_genbank', help='Path to genomic assembly in GenBank format.', required=True)
parser.add_argument('-g', '--genbank_outdir',
help='Path to output directory where genbank file should be written. Should already be created!',
required=True)
parser.add_argument('-p', '--proteome_outdir',
help='Path to output directory where proteome file should be written. Should already be created!',
required=True)
parser.add_argument('-n', '--name_mapping_outdir',
help='Path to output directory where gene old-to-new mapping text files should be written. Should already be created!',
required=True)
parser.add_argument('-s', '--sample_name', help='Sample name', default='Sample', required=False)
parser.add_argument('-l', '--locus_tag', help='Locus tag', default=None, required=False)
args = parser.parse_args()
return args
def processAndReformatNCBIGenbanks():
"""
Void function which runs primary workflow for program.
"""
"""
PARSE REQUIRED INPUTS
"""
myargs = create_parser()
input_genbank_file = os.path.abspath(myargs.input_ncbi_genbank)
gbk_outdir = os.path.abspath(myargs.genbank_outdir) + '/'
pro_outdir = os.path.abspath(myargs.proteome_outdir) + '/'
map_outdir = os.path.abspath(myargs.name_mapping_outdir) + '/'
try:
assert (util.is_genbank(input_genbank_file))
except:
raise RuntimeError('Issue with input Genbank file from NCBI.')
outdirs = [gbk_outdir, pro_outdir, map_outdir]
for outdir in outdirs:
if not os.path.isdir(outdir):
sys.stderr.write("Output directory %s does not exist! Please create and retry program." % outdir)
"""
PARSE OPTIONAL INPUTS
"""
sample_name = myargs.sample_name
locus_tag = myargs.locus_tag
"""
START WORKFLOW
"""
# Step 1: Process NCBI Genbank and (re)create genbank/proteome with updated locus tags.
try:
gbk_outfile = gbk_outdir + sample_name + '.gbk'
pro_outfile = pro_outdir + sample_name + '.faa'
map_outfile = map_outdir + sample_name + '.txt'
gbk_outfile_handle = open(gbk_outfile, 'w')
pro_outfile_handle = open(pro_outfile, 'w')
map_outfile_handle = open(map_outfile, 'w')
locus_tag_iterator = 1
oigf = None
if input_genbank_file.endswith('.gz'):
oigf = gzip.open(input_genbank_file, 'rt')
else:
oigf = open(input_genbank_file)
for rec in SeqIO.parse(oigf, 'genbank'):
for feature in rec.features:
if feature.type == "CDS":
all_starts = []
all_ends = []
all_directions = []
all_coords = []
if 'order' in str(feature.location):
raise RuntimeError(
'Currently order is not allowed for CDS features in Genbanks. Please consider removing sample %s from analysis and trying again.' % sample_name)
if not 'join' in str(feature.location):
start = min([int(x.strip('>').strip('<')) for x in
str(feature.location)[1:].split(']')[0].split(':')]) + 1
end = max(
[int(x.strip('>').strip('<')) for x in str(feature.location)[1:].split(']')[0].split(':')])
direction = str(feature.location).split('(')[1].split(')')[0]
all_starts.append(start);
all_ends.append(end);
all_directions.append(direction)
all_coords.append([start, end, direction])
else:
all_starts = []
all_ends = []
all_directions = []
for exon_coord in str(feature.location)[5:-1].split(', '):
start = min(
[int(x.strip('>').strip('<')) for x in exon_coord[1:].split(']')[0].split(':')]) + 1
end = max([int(x.strip('>').strip('<')) for x in exon_coord[1:].split(']')[0].split(':')])
direction = exon_coord.split('(')[1].split(')')[0]
all_starts.append(start);
all_ends.append(end);
all_directions.append(direction)
all_coords.append([start, end, direction])
assert (len(set(all_directions)) == 1)
start = min(all_starts)
end = max(all_ends)
direction = all_directions[0]
old_locus_tag = 'NA'
prot_seq = ''
try:
old_locus_tag = feature.qualifiers.get('locus_tag')[0]
except:
pass
try:
prot_seq = str(feature.qualifiers.get('translation')[0]).replace('*', '')
except:
raise RuntimeError(
"Currently only full Genbanks with translations available for each CDS is accepted.")
nucl_seq = str(rec.seq)[start - 1:end]
if direction == '-':
nucl_seq = str(Seq(nucl_seq).reverse_complement())
prot_seq = Seq(nucl_seq).translate()
feature.qualifiers['translation'] = prot_seq
# sys.stderr.write('CDS with locus tag %s does not have translation available, generating translation.\n' % old_locus_tag)
new_locus_tag = None
try:
new_locus_tag = feature.qualifiers.get('locus_tags')[0]
except:
pass
if locus_tag != None or new_locus_tag == None:
if locus_tag == None:
sys.stderr.write('Using AAAA as locus tag because non-provided by user or GenBank for CDS.\n')
locus_tag = 'AAAA'
new_locus_tag = locus_tag + '_'
if locus_tag_iterator < 10:
new_locus_tag += '00000' + str(locus_tag_iterator)
elif locus_tag_iterator < 100:
new_locus_tag += '0000' + str(locus_tag_iterator)
elif locus_tag_iterator < 1000:
new_locus_tag += '000' + str(locus_tag_iterator)
elif locus_tag_iterator < 10000:
new_locus_tag += '00' + str(locus_tag_iterator)
elif locus_tag_iterator < 100000:
new_locus_tag += '0' + str(locus_tag_iterator)
else:
new_locus_tag += str(locus_tag_iterator)
locus_tag_iterator += 1
feature.qualifiers['locus_tag'] = new_locus_tag
pro_outfile_handle.write('>' + str(new_locus_tag) + ' ' + rec.id + ' ' + str(start) + ' ' + str(end) + ' ' + str(direction) + '\n' + prot_seq + '\n')
map_outfile_handle.write(str(old_locus_tag) + '\t' + str(new_locus_tag) + '\n')
SeqIO.write(rec, gbk_outfile_handle, 'genbank')
oigf.close()
gbk_outfile_handle.close()
pro_outfile_handle.close()
map_outfile_handle.close()
except:
raise RuntimeError("Issue processing NCBI Genbank file.")
if __name__ == '__main__':
processAndReformatNCBIGenbanks() | zol | /zol-1.2.1-py3-none-any.whl/zol-1.2.1.data/scripts/processNCBIGenBank.py | processNCBIGenBank.py |
import os
import sys
import pandas
import argparse
from time import sleep
zol_main_directory = '/'.join(os.path.realpath(__file__).split('/')[:-2]) + '/'
plot_prog = zol_main_directory + 'scripts/generateSyntenicVisual.R'
def create_parser():
""" Parse arguments """
parser = argparse.ArgumentParser(description="""
Program: generateSyntenicVisual.py
Author: Rauf Salamzade
Affiliation: Kalan Lab, UW Madison, Department of Medical Microbiology and Immunology
""", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-i', '--zol_report_tsv', help='Path to zol tsv report.', required=True)
parser.add_argument('-o', '--output_dir', help='Path to output directory.', required=True)
parser.add_argument('-m', '--metric', help='Metric to use for coloring in plot. Valid options are headers for evolutionary statistics.\nPlease surround by quotes if there is a space in the header of the column. Default is "Tajima\'s D"', required=False, default="Tajima's D")
parser.add_argument('-l', '--length', type=int, help='Specify the height/length of the plot. Default is 7.', required=False, default=3)
parser.add_argument('-w', '--width', type=int, help='Specify the width of the plot. Default is 10.', required=False, default=7)
args = parser.parse_args()
return args
def genSynVis():
"""
PARSE INPUTS
"""
myargs = create_parser()
input_zol_report = myargs.zol_report_tsv
metric_name = myargs.metric
outdir = os.path.abspath(myargs.output_dir) + '/'
plot_height = myargs.length
plot_width = myargs.width
try:
assert(os.path.isfile(input_zol_report))
except:
sys.stderr.write('Error validating input file %s exists!' % input_zol_report)
if os.path.isdir(outdir):
sys.stderr.write("Output directory exists. Overwriting in 5 seconds ...\n")
sleep(5)
else:
os.mkdir(outdir)
df = pandas.read_csv(input_zol_report, sep='\t', header=0)
"""
0 Homolog Group (HG) ID
1 HG is Single Copy?
2 Proportion of Total Gene Clusters with HG
3 HG Median Length (bp)
4 HG Consensus Order
5 HG Consensus Direction
6 Proportion of Focal Gene Clusters with HG
7 Proportion of Comparator Gene Clusters with HG
8 Fixation Index
9 Upstream Region Fixation Index
10 Tajima's D
11 Proportion of Filtered Codon Alignment is Segregating Sites
12 Entropy
13 Upstream Region Entropy
14 Median Beta-RD-gc
15 Max Beta-RD-gc
16 Proportion of sites which are highly ambiguous in codon alignment
17 Proportion of sites which are highly ambiguous in trimmed codon alignment
18 GARD Partitions Based on Recombination Breakpoints
19 Number of Sites Identified as Under Positive or Negative Selection by FUBAR
20 Average delta(Beta, Alpha) by FUBAR across sites
21 Proportion of Sites Under Selection which are Positive
22 Custom Annotation (E-value)
23 KO Annotation (E-value)
24 PGAP Annotation (E-value)
25 PaperBLAST Annotation (E-value)
26 CARD Annotation (E-value)
27 IS Finder (E-value)
28 MI-BiG Annotation (E-value)
29 VOG Annotation (E-value)
30 VFDB Annotation (E-value)
31 Pfam Domains
32 CDS Locus Tags
33 HG Consensus Sequence
"""
df.sort_values(by="HG Consensus Order", ascending=True, inplace=True)
prev_end = 1
plot_input_file = outdir + 'Track.txt'
pif_handle = open(plot_input_file, 'w')
pif_handle.write('\t'.join(['HG', 'Start', 'End', 'Direction', 'SC', 'Metric']) + '\n')
for index, row in df.iterrows():
hg = row['Homolog Group (HG) ID']
hg_cons = row['Proportion of Total Gene Clusters with HG']
if float(hg_cons) < 0.25: continue
hg_mlen = float(row['HG Median Length (bp)'])
hg_dir = row['HG Consensus Direction']
sc_flag = row['HG is Single Copy?']
sc_mark = ''
if sc_flag == False:
sc_mark = '//'
start = prev_end
end = prev_end + hg_mlen
dir = 1
if hg_dir == '-':
dir = 0
metric_val = row[metric_name]
print_row = [hg, start, end, dir, sc_mark, metric_val]
pif_handle.write('\t'.join([str(x) for x in print_row]) + '\n')
prev_end = end + 200
pif_handle.close()
plot_result_pdf = outdir + 'Plot.pdf'
plot_cmd = ['Rscript', plot_prog, plot_input_file, str(plot_height), str(plot_width), plot_result_pdf]
try:
subprocess.call(' '.join(plot_cmd), shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
executable='/bin/bash')
assert (os.path.isfile(plot_result_pdf))
except Exception as e:
sys.stderr.write('Had an issue running R based plotting: %s\n' % ' '.join(plot_cmd))
sys.exit(1)
if __name__ == '__main__':
genSynVis() | zol | /zol-1.2.1-py3-none-any.whl/zol-1.2.1.data/scripts/generateSyntenicVisual.py | generateSyntenicVisual.py |
from pymodbus.client.sync import ModbusSerialClient
from pymodbus import payload
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.payload import BinaryPayloadBuilder
from pymodbus.constants import Endian
from pymodbus.utilities import computeCRC
import numpy as np
import time
def reset_Lyra(client,target_unit):
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x0002)
builder.add_16bit_uint(0x0001)
payload = builder.build()
result = client.write_registers(5000, payload, skip_encode=True)
return
except:
raise
def Lyra_factory_reset(client,target_unit):
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x0002)
builder.add_16bit_uint(0x0002)
payload = builder.build()
result = client.write_registers(5000, payload, skip_encode=True)
return
except:
raise
def read_time_register(client,target_unit):
#ID is composed by two 16-bit digits.
try:
request=client.read_holding_registers(address=5004,count=2,unit=target_unit)
if not request.isError():
time=int(str(request.registers[0])+str(request.registers[1]))
#print('Time from unit ',target_unit," is ",time)
return time
except:
raise
def read_k1_register(client,target_unit):
#ID is composed by two 16-bit digits.
try:
request=client.read_holding_registers(address=5000,count=2,unit=target_unit)
if not request.isError():
return hex(request.registers[0]),hex(request.registers[1])
except:
raise
def read_system_status(client,target_unit):
#ID is composed by two 16-bit digits.
try:
request=client.read_holding_registers(address=5016,count=2,unit=target_unit)
if not request.isError():
return hex(request.registers[0]),hex(request.registers[1])
except:
raise
def reset_time_register(client,target_unit,time_to_write):
#ID is composed by two 16-bit digits.
try:
wrequest=client.write_registers(address=5004,values=[0x0000,time_to_write],unit=target_unit)
request=client.read_holding_registers(address=5004,count=2,unit=target_unit)
if not request.isError():
time=int(str(request.registers[0])+str(request.registers[1]))
print('Time from unit ',target_unit," is ",time)
return time
except:
raise
def change_id_register_to_default(client,target_unit):
#ID is composed by two 16-bit digits.
new_id=2
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x5A5A)
builder.add_16bit_uint(new_id)
payload = builder.build()
result = client.write_registers(5200, payload, skip_encode=True)
return
# rq=client.write_registers(5200,[0x0000],unit=target_unit)
# rq=client.write_registers(5201,[new_id],unit=target_unit)
except:
raise
def change_bt_timeout(client,target_unit,new_value):
#ID is composed by two 16-bit digits.
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_32bit_float(new_value)
payload = builder.build()
result = client.write_registers(7220, payload, skip_encode=True)
return
# rq=client.write_registers(5200,[0x0000],unit=target_unit)
# rq=client.write_registers(5201,[new_id],unit=target_unit)
except:
raise
def change_btconfig_parameters(client,target_unit,values):
#ID is composed by two 16-bit digits.
for i in range(14):
value_to_write=values[i]
## print(value_to_write,7220+2*i)
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_32bit_float(value_to_write)
payload = builder.build()
result = client.write_registers(7200+2*i, payload, skip_encode=True)
time.sleep(0.1)
print('Value ',value_to_write,' successfully written at register: ',7200+2*i)
# rq=client.write_registers(5200,[0x0000],unit=target_unit)
# rq=client.write_registers(5201,[new_id],unit=target_unit)
except:
raise
print('All values succesfully written')
return
def change_guconfig_parameters(client,target_unit,values):
#ID is composed by two 16-bit digits.
for i in range(7):
value_to_write=values[i]
## print(value_to_write,7220+2*i)
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_32bit_float(value_to_write)
payload = builder.build()
result = client.write_registers(7228+2*i, payload, skip_encode=True)
time.sleep(0.1)
print('Value ',value_to_write,' successfully written at register: ',7228+2*i)
# rq=client.write_registers(5200,[0x0000],unit=target_unit)
# rq=client.write_registers(5201,[new_id],unit=target_unit)
except:
raise
print('All values succesfully written')
return
def change_sbconfig_parameters(client,target_unit,values):
#ID is composed by two 16-bit digits.
for i in range(11):
value_to_write=values[i]
## print(value_to_write,7220+2*i)
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_32bit_float(value_to_write)
payload = builder.build()
result = client.write_registers(7242+2*i, payload, skip_encode=True)
time.sleep(0.1)
print('Value ',value_to_write,' successfully written at register: ',7242+2*i)
# rq=client.write_registers(5200,[0x0000],unit=target_unit)
# rq=client.write_registers(5201,[new_id],unit=target_unit)
except:
raise
print('All values successfully written')
return
def change_id_register(client,target_unit,target_id):
#ID is composed by two 16-bit digits.
new_id=target_id
try:
rq=client.write_registers(5200,[0x5A5A,new_id],unit=target_unit)
print('ID of unit ',target_unit,' has been changed successfully to ',target_id)
return
# rq=client.write_registers(5201,,unit=target_unit)
except:
raise
def broadcast_default_ID(client):
try:
rq=client.write_registers(5200,[0x5A5A,1],unit=0)
return
except:
raise
def broadcast_get_IDs(client):
#This needs to be improved to associate the response with the incoming ID.
try:
print('Trying to get IDs from the network via broadcasting to unit 0...')
rq=client.read_holding_registers(5200,count=2,unit=0)
if not rq.isError():
print('IDs from network gathered successfully...')
return rq
except:
print('Unable to retrieve network devices IDs')
return client.read_holding_registers(5200,count=2,unit=0)
raise
def broadcast_reset_Lyra(client):
try:
rq=client.write_registers(5000,[0x0002],unit=0)
rq=client.write_registers(5001,[0x0001],unit=0)
except:
raise
def K1_contactor_sync(client,target_unit):
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x0010)
builder.add_16bit_uint(0x0001)
payload = builder.build()
result = client.write_registers(5000, payload, skip_encode=True)
print('Sync attempt of K1 at: ',str(dt.datetime.now()))
return
except:
raise
def K1_contactor_forced_closing(client,target_unit):
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x0010)
builder.add_16bit_uint(0x0002)
payload = builder.build()
result = client.write_registers(5000, payload, skip_encode=True)
print('Forced close of K1 at',str(dt.datetime.now()))
return
except:
raise
def K1_contactor_forced_opening(client,target_unit):
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x0010)
builder.add_16bit_uint(0x0003)
payload = builder.build()
result = client.write_registers(5000, payload, skip_encode=True)
print('Forced opening of K1 at',str(dt.datetime.now()))
return
except:
raise
def K2_contactor_sync(client,target_unit):
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x0020)
builder.add_16bit_uint(0x0001)
payload = builder.build()
result = client.write_registers(5000, payload, skip_encode=True)
print('Sync attempt of K2 at: ',str(dt.datetime.now()))
return
except:
raise
def K2_contactor_forced_closing(client,target_unit):
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x0020)
builder.add_16bit_uint(0x0002)
payload = builder.build()
result = client.write_registers(5000, payload, skip_encode=True)
print('Forced close of K2 at',str(dt.datetime.now()))
#rq = client.write_registers(5001, [0x0002], unit=target_unit)
return
except:
raise
def K2_contactor_forced_opening(client,target_unit):
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x0020)
builder.add_16bit_uint(0x0003)
payload = builder.build()
result = client.write_registers(5000, payload, skip_encode=True)
print('Forced opening of K2 at',str(dt.datetime.now()))
return
except:
raise
def K1_contactor_donothing(client,target_unit):
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x0000)
builder.add_16bit_uint(0x0000)
payload = builder.build()
result = client.write_registers(5000, payload, skip_encode=True)
print('Registers 5000 with "do nothing" cmd at: ',str(dt.datetime.now()))
return
except:
raise
def K2_contactor_donothing(client,target_unit):
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x0000)
builder.add_16bit_uint(0x0000)
payload = builder.build()
result = client.write_registers(5000, payload, skip_encode=True)
print('Registers 5000 with "do nothing" cmd at: ',str(dt.datetime.now()))
return
except:
raise
def K3_contactor_donothing(client,target_unit):
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x0000)
builder.add_16bit_uint(0x0000)
payload = builder.build()
result = client.write_registers(5000, payload, skip_encode=True)
print('Registers 5000 with "do nothing" cmd at: ',str(dt.datetime.now()))
return
except:
raise
def K3_contactor_sync(client,target_unit):
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x0030)
builder.add_16bit_uint(0x0001)
payload = builder.build()
result = client.write_registers(5000, payload, skip_encode=True)
print('Sync attempt of K3 at: ',str(dt.datetime.now()))
return
except:
raise
def K3_contactor_forced_closing(client,target_unit):
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x0030)
builder.add_16bit_uint(0x0002)
payload = builder.build()
result = client.write_registers(5000, payload, skip_encode=True)
print('Forced close of K3 at',str(dt.datetime.now()))
return
except:
raise
def K3_contactor_forced_opening(client,target_unit):
try:
builder = BinaryPayloadBuilder(byteorder=Endian.Big)
builder.add_16bit_uint(0x0030)
builder.add_16bit_uint(0x0003)
payload = builder.build()
result = client.write_registers(5000, payload, skip_encode=True)
print('Forced opening of K3 at',str(dt.datetime.now()))
return
except:
raise
#Reading purpose functions
###
### Functions:
#read_min_volt_conn_register(client,1)
#read_max_volt_conn_register(client,1)
#read_min_volt_disc_register(client,1)
#read_max_volt_disc_register(client,1)
#read_max_volt_diff_disc_register(client,1)
#read_max_volt_diff_conn_register(client,1)
#read_max_freq_diff_conn_register(client,1)
#read_max_angle_diff_conn_register(client,1)
#read_max_angle_diff_disc_register(client,1)
#read_conn_timeout_register(client,1)
def read_k1_status(client,target_unit):
try:
rq=client.read_coils(1000,unit=target_unit)
return rq.bits[0]
except:
raise
def read_flags(client,target_unit):
try:
values=[]
for i in range(0,3):
request=client.read_holding_registers(address=5010+i*2,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=">", wordorder=">")
c,d='{0:016b}'.format(client.read_holding_registers(address=5010,count=2,unit=8).registers[0]),'{0:016b}'.format(client.read_holding_registers(address=5010,count=2,unit=8).registers[1])
if not request.isError():
value=decoder.decode_32bit_uint()
## values.append(['{0:032b}'.format(value),c,d])
values.append('{0:032b}'.format(value))
return values
except:
raise
def read_config_parameters(client,target_unit,app):
if app=='bt':
#ID is composed by two 16-bit digits.
try:
values=[]
for i in range(0,14):
request=client.read_holding_registers(address=7200+i*2,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=">", wordorder=">")
if not request.isError():
value=decoder.decode_32bit_float()
values.append(value)
return values
except:
raise
if app=='gu':
#ID is composed by two 16-bit digits.
try:
values=[]
for i in range(7):
request=client.read_holding_registers(address=7228+i*2,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=">", wordorder=">")
if not request.isError():
value=decoder.decode_32bit_float()
values.append(value)
return values
except:
raise
if app=='sb':
#ID is composed by two 16-bit digits.
try:
values=[]
for i in range(0,11):
request=client.read_holding_registers(address=7242+i*2,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=">", wordorder=">")
if not request.isError():
value=decoder.decode_32bit_float()
values.append(value)
return values
except:
raise
def read_id_register(client,target_unit):
#ID is composed by two 16-bit digits.
try:
request=client.read_holding_registers(address=5200,count=2,unit=target_unit)
if not request.isError():
print('ID from unit ',target_unit," is ",request.registers)
return request.registers
except:
raise
def read_min_volt_conn_register(client,target_unit):
#ID is composed by two 16-bit digits.
try:
request=client.read_holding_registers(address=7204,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=">", wordorder=">")
if not request.isError():
value=decoder.decode_32bit_float()
print('Min voltage for connection from unit ',target_unit," is ",value)
return value
except:
raise
def read_max_volt_conn_register(client,target_unit):
#ID is composed by two 16-bit digits.
try:
request=client.read_holding_registers(address=7206,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=">", wordorder=">")
if not request.isError():
value=decoder.decode_32bit_float()
print('Max voltage for connection from unit ',target_unit," is ",value)
return value
except:
raise
def read_min_volt_disc_register(client,target_unit):
#ID is composed by two 16-bit digits.
try:
request=client.read_holding_registers(address=7214,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=">", wordorder=">")
if not request.isError():
value=decoder.decode_32bit_float()
print('Min voltage for disconnection from unit ',target_unit," is ",value)
return value
except:
raise
def read_max_volt_disc_register(client,target_unit):
#ID is composed by two 16-bit digits.
try:
request=client.read_holding_registers(address=7216,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=">", wordorder=">")
if not request.isError():
value=decoder.decode_32bit_float()
print('Max voltage for disconnection from unit ',target_unit," is ",value)
return value
except:
raise
def read_max_volt_diff_disc_register(client,target_unit):
#ID is composed by two 16-bit digits.
try:
request=client.read_holding_registers(address=7218,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=">", wordorder=">")
if not request.isError():
value=decoder.decode_32bit_float()
print('Max voltage difference for disconnection from unit ',target_unit," is ",value)
return value
except:
raise
def read_max_volt_diff_conn_register(client,target_unit):
#ID is composed by two 16-bit digits.
try:
request=client.read_holding_registers(address=7210,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=">", wordorder=">")
if not request.isError():
value=decoder.decode_32bit_float()
print('Max voltage difference for connection from unit ',target_unit," is ",value)
return value
except:
raise
def read_max_freq_diff_conn_register(client,target_unit):
#ID is composed by two 16-bit digits.
try:
request=client.read_holding_registers(address=7208,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=">", wordorder=">")
if not request.isError():
value=decoder.decode_32bit_float()
print('Max frequency difference for connect from unit ',target_unit," is ",value)
return value
except:
raise
def read_max_angle_diff_disc_register(client,target_unit):
#ID is composed by two 16-bit digits.
try:
request=client.read_holding_registers(address=7212,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=">", wordorder=">")
if not request.isError():
value=decoder.decode_32bit_float()
print('Max angle difference for connection from unit ',target_unit," is ",value)
return value
except:
raise
def read_max_angle_diff_conn_register(client,target_unit):
#ID is composed by two 16-bit digits.
try:
request=client.read_holding_registers(address=7202,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=">", wordorder=">")
if not request.isError():
value=decoder.decode_32bit_float()
print('Max angle tolerance from unit ',target_unit," is ",value)
return value
except:
raise
def read_conn_timeout_register(client,target_unit):
#ID is composed by two 16-bit digits.
try:
request=client.read_holding_registers(address=7220,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(request.registers, byteorder=">", wordorder=">")
if not request.isError():
value=decoder.decode_32bit_float()
print('Timeout value for connection from unit ',target_unit," is ",value)
return value
except:
raise
#Phase Reading functions
#Phase Reading functions
#Phase Reading functions
def read_side_1_info(client,target_unit):
try:
result=client.read_input_registers(address=7000,count=36,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(result.registers, byteorder=">", wordorder=">")
data=[]
for i in range(int(36/2)):
data.append(decoder.decode_32bit_float())
return data
except Exception as e:
raise
def read_phase_1_info_side_1(client,target_unit):
try:
data=[]
for i in range(6):
result=client.read_input_registers(address=7000+i*2,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(result.registers, byteorder=">", wordorder=">")
data.append(decoder.decode_32bit_float())
return data
except Exception as e:
raise
def read_phase_2_info_side_1(client,target_unit):
try:
data=[]
for i in range(6):
result=client.read_input_registers(address=7012+i*2,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(result.registers, byteorder=">", wordorder=">")
data.append(decoder.decode_32bit_float())
return data
except Exception as e:
raise
def read_phase_3_info_side_1(client,target_unit):
try:
data=[]
for i in range(6):
result=client.read_input_registers(address=7024+i*2,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(result.registers, byteorder=">", wordorder=">")
data.append(decoder.decode_32bit_float())
return data
except Exception as e:
raise
def read_phase_1_info_side_2(client,target_unit):
try:
data=[]
for i in range(6):
result=client.read_input_registers(address=7036+i*2,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(result.registers, byteorder=">", wordorder=">")
data.append(decoder.decode_32bit_float())
return data
except Exception as e:
return result
def read_phase_2_info_side_2(client,target_unit):
try:
data=[]
for i in range(6):
result=client.read_input_registers(address=7048+i*2,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(result.registers, byteorder=">", wordorder=">")
data.append(decoder.decode_32bit_float())
return data
except Exception as e:
raise
def read_phase_3_info_side_2(client,target_unit):
try:
data=[]
for i in range(6):
result=client.read_input_registers(address=7060+i*2,count=2,unit=target_unit)
decoder = payload.BinaryPayloadDecoder.fromRegisters(result.registers, byteorder=">", wordorder=">")
data.append(decoder.decode_32bit_float())
return data
except Exception as e:
raise
#Writing registers purpose functions
###
###
def write_max_angle_diff_conn_register(client,target_unit,new_value):
#ID is composed by two 16-bit digits.
try:
builder=BinaryPayloadBuilder()
builder.add_16bit_float(new_value)
payload=builder.build()
print(payload)
#wrequest=client.write_registers(address=7202,values=[new_value,0],unit=target_unit)
wrequest=client.write_registers(address=7202,values=payload,skip_encode=True,unit=target_unit)
if not wrequest.isError():
print('Max angle tolerance from unit ',target_unit," now is ",new_value)
return new_value
except Exception as e:
print(e)
raise
def write_min_vol_conn_register(client,target_unit,new_value):
#ID is composed by two 16-bit digits.
try:
wrequest=client.write_registers(address=7204,values=[new_value],unit=target_unit)
if not wrequest.isError():
print('Min voltage connection tolerance from unit ',target_unit," now is ",new_value)
return new_value
except:
raise
def write_max_vol_conn_register(client,target_unit,new_value):
#ID is composed by two 16-bit digits.
try:
wrequest=client.write_registers(address=7206,values=[new_value],unit=target_unit)
if not wrequest.isError():
print('Max voltage connection tolerance from unit ',target_unit," now is ",new_value)
return new_value
except:
raise
def write_max_freq_diff_conn_register(client,target_unit,new_value):
#ID is composed by two 16-bit digits.
try:
wrequest=client.write_registers(address=7208,values=[0x0028],unit=target_unit)
if not wrequest.isError():
print('Max angle tolerance from unit ',target_unit," now is ",new_value)
return new_value
except:
raise
def write_max_volt_diff_conn_register(client,target_unit,new_value):
#ID is composed by two 16-bit digits.
try:
wrequest=client.write_registers(address=7210,values=[0x0028],unit=target_unit)
if not wrequest.isError():
print('Max voltage difference tolerance from unit ',target_unit," now is ",new_value)
return new_value
except:
raise
def write_max_agl_diff_disc_register(client,target_unit,new_value):
#ID is composed by two 16-bit digits.
try:
wrequest=client.write_registers(address=7212,values=[],unit=target_unit)
if not wrequest.isError():
print('Max angle disconnection tolerance from unit ',target_unit," now is ")
return new_value
except:
raise
def write_min_vol_disc_register(client,target_unit,new_value):
#ID is composed by two 16-bit digits.
try:
wrequest=client.write_registers(address=7214,values=[0x0028],unit=target_unit)
if not wrequest.isError():
print('Min voltage tolerance for disconnection from unit ',target_unit," now is ",new_value)
return new_value
except:
raise
def write_max_vol_disc_register(client,target_unit,new_value):
#ID is composed by two 16-bit digits.
try:
wrequest=client.write_registers(address=7216,values=[0x0028],unit=target_unit)
if not wrequest.isError():
print('Max voltage tolerance for connection from unit ',target_unit," now is ",new_value)
return new_value
except:
raise
def write_max_vol_diff_disc_register(client,target_unit,new_value):
#ID is composed by two 16-bit digits.
try:
wrequest=client.write_registers(address=7218,values=[0x0028],unit=target_unit)
if not wrequest.isError():
print('Max voltage difference tolerance for disconnection from unit ',target_unit," now is ",new_value)
return new_value
except:
raise
def write_conn_timeout_register(client,target_unit,new_value):
#ID is composed by two 16-bit digits.
try:
wrequest=client.write_registers(address=7220,values=[0x0028],unit=target_unit)
if not wrequest.isError():
print('Max angle tolerance from unit ',target_unit," now is ",new_value)
return new_value
except:
raise
####RELAY MODULES
def create_connection(comport):
num_retries=10
try:
#client=ModbusSerialClient(method='rtu',port='/dev/ttyUSB'+str(comport),stopbits=1,bytesize=8,parity='N',baudrate=115200)
client=ModbusSerialClient(method='rtu',port='COM'+str(comport),stopbits=1,bytesize=8,parity='N',baudrate=115200)
client.connect()
return client
except:
i=0
while i<=num_retries:
try:
client=ModbusSerialClient(method='rtu',port='/dev/ttyUSB'+str(comport),stopbits=1,bytesize=8,parity='N',baudrate=115200)
client.connect()
i+=1
return client
except:
i+=1
pass
raise
def close_connection(client):
try:
client.close()
except:
raise
#IDs van desde 1 a 256 (0x01 a 0xFF), broadcast ID is 0x00
def read_slave_id_address(client,slave_id):
# return client.read_holding_registers(address=16384,count=1,unit=slave_id).registers
return client.read_holding_registers(address=0x4000,count=1,unit=slave_id).registers[0]
def change_slave_id(client,slave_id,target_id):
rq=client.write_register(address=0x4000,value=target_id,unit=slave_id)
return
def change_slave_baudrate(client,slave_id,target_baudrate):
# The baud rate
# 0x0000 : 4800
# 0x0001 : 9600
# 0x0002 : 19200
# 0x0003 : 38400
# 0x0004 : 57600
# 0x0005 : 115200
# 0x0006 : 128000
# 0x0007 : 256000
try:
client.write_register(address=0x2000,value=target_baudrate,unit=slave_id)
print("Baudrate was modified successfully to option: ",target_baudrate)
return
except:
raise
#Status readings
def read_relays_status(client,slave_id):
#Returns a list with bools indicating status of the relays.
#Register=0, count=8, unit=11 to 14.
#output -> [True, True, True, True, True, True, True, True]
# If it fails, it will give an error.
retries=10
j=0
while j<=retries:
#time.sleep(0.1)
if j!=0:
print('Attempt: ',j+1)
req=client.read_coils(address=0,count=8,unit=slave_id)
if not req.isError():
req = req.bits
out={}
for i in range(8):
out.update({i:req[i]})
if j!=0:
print('Num_Tries: ',j+1)
return out
time.sleep(0.1)
j+=1
#{0:False,1:False,2:False,3:False,4:False,5:False,6:False,7:False,8:False}
return req
#Individual relay handling
def close_relay(client,slave_id,relay_to_close):
#values for relay_to_close from 0 to 7
status=read_relays_status(client,slave_id)
state=status[relay_to_close]
while state==False:
try:
if client.is_socket_open():
client.write_coil(address=relay_to_close,value=1,unit=slave_id)
time.sleep(0.1)
state=read_relays_status(client,slave_id)[relay_to_close]
except Exception as e:
print(e)
raise
return
def open_relay(client,slave_id,relay_to_close):
#values for relay_to_close from 0 to 7
status=read_relays_status(client,slave_id)
state=status[relay_to_close]
while state==True:
try:
if client.is_socket_open():
client.write_coil(address=relay_to_close,value=0,unit=slave_id)
time.sleep(0.1)
state=read_relays_status(client,slave_id)[relay_to_close]
except Exception as e:
print(e)
raise
return
#Relays group handling
#Close all relays for a
def close_all_module_relays(client,slaves_id):
#Grid Unifying contactor data
grid_unifying_module=14
grid_unifying_contactor_id=0
try:
for slave_id in slaves_id:
#Slave ID that contains GUC.
try:
status=read_relays_status(client,slave_id)
except:
time.sleep(0.1)
status=read_relays_status(client,slave_id)
if slave_id==grid_unifying_module:
for i in range(7,0,-1):
if status[i]==False and i!=grid_unifying_contactor_id:
close_relay(client,slave_id,i)
else:
pass
else:
try:
client.write_coil(address=0x00ff,value=1,unit=slave_id)
time.sleep(0.1)
status=read_relays_status(client,slave_id)
for i in range(8):
#if its not closed
if status[i]==False:
close_relay(client,slave_id,i)
except:
raise
except:
raise
def open_all_module_relays(client,slaves_id):
#Grid Unifying contactor data
grid_unifying_module=14
grid_unifying_contactor_id=0
try:
for slave_id in slaves_id:
#Slave ID that contains GUC.
try:
status=read_relays_status(client,slave_id)
except:
time.sleep(0.1)
status=read_relays_status(client,slave_id)
if slave_id==grid_unifying_module:
for i in range(7,0,-1):
if status[i]==True and i!=grid_unifying_contactor_id:
open_relay(client,slave_id,i)
else:
pass
else:
try:
client.write_coil(address=0x00ff,value=0,unit=slave_id)
time.sleep(0.1)
status=read_relays_status(client,slave_id)
for i in range(8):
#if its not closed
if status[i]==True:
open_relay(client,slave_id,i)
except:
raise
except:
raise
####UGRID CONTROL
#list devices in terminal ls /dev/*USB*
def connect_all(client):
modules=[11,12,13,14]
relays=[0,1,2,3,4,5,6,7]
for module in modules:
for relay in relays:
close_relay(client,module,relay)
return
def disconnect_all(client):
modules=[14,13,12,11]
relays=[7,6,5,4,3,2,1,0]
for module in modules:
for relay in relays:
open_relay(client,module,relay)
return
def connect_der(client,ders_to_connect):
#ders_to_connect takes values from 1 to 6
#der_locations={DER:(module_id,contactor)}
der_locations={1:(11,2),2:(12,6),3:(12,2),4:(13,2),5:(14,6),6:(14,2)}
for der in ders_to_connect:
module=der_locations[der][0]
contactor=der_locations[der][1]
close_relay(client,module,contactor)
return
def disconnect_der(client,ders_to_disconnect):
#ders_to_discconnect is a list that takes values from 1 to 6
#der_locations={DER:(module_id,contactor)}
der_locations={1:(11,2),2:(12,6),3:(12,2),4:(13,2),5:(14,6),6:(14,2)}
for der in ders_to_disconnect:
module=der_locations[der][0]
contactor=der_locations[der][1]
open_relay(client,module,contactor)
return
def connect_load(client,loads_to_connect):
#loads_to_connect takes values from 1 to 12(?)
load_locations={1:(11,3),2:(11,1),3:(12,7),4:(12,5),5:(12,3),6:(12,1),7:(13,3),8:(13,1),9:(14,7),10:(14,5),11:(14,4)}
for load in loads_to_connect:
module=load_locations[load][0]
contactor=load_locations[load][1]
close_relay(client,module,contactor)
return
def disconnect_load(client,loads_to_disconnect):
#loads_to_connect takes values from 1 to 12(?)
load_locations={1:(11,3),2:(11,1),3:(12,7),4:(12,5),5:(12,3),6:(12,1),7:(13,3),8:(13,1),9:(14,7),10:(14,5),11:(14,4)}
for load in loads_to_disconnect:
module=load_locations[load][0]
contactor=load_locations[load][1]
open_relay(client,module,contactor)
return
def connect_all_load(client):
load_locations={1:(11,3),2:(11,1),3:(12,7),4:(12,5),5:(12,3),6:(12,1),7:(13,3),8:(13,1),9:(14,7),10:(14,4),11:(14,4)}
for load in load_locations.keys():
module=load_locations[load][0]
contactor=load_locations[load][1]
close_relay(client,module,contactor)
return
def disconnect_all_load(client):
load_locations={1:(11,3),2:(11,1),3:(12,7),4:(12,5),5:(12,3),6:(12,1),7:(13,3),8:(13,1),9:(14,7),10:(14,4),11:(14,4)}
for load in load_locations.keys():
module=load_locations[load][0]
contactor=load_locations[load][1]
open_relay(client,module,contactor)
return
def connect_all_der(client):
der_locations={1:(11,2),2:(12,6),3:(12,2),4:(13,2),5:(14,6),6:(14,2)}
for der in der_locations.keys():
module=der_locations[der][0]
contactor=der_locations[der][1]
close_relay(client,module,contactor)
return
def disconnect_all_der(client):
der_locations={1:(11,2),2:(12,6),3:(12,2),4:(13,2),5:(14,6),6:(14,2)}
for der in der_locations.keys():
module=der_locations[der][0]
contactor=der_locations[der][1]
open_relay(client,module,contactor)
return | zola-ugrid-control | /zola_ugrid_control-0.0.3.tar.gz/zola_ugrid_control-0.0.3/ugrid_control/__init__.py | __init__.py |
import requests
import json
import os
from moviepy.editor import AudioFileClip
import speech_recognition as sr
from .handlers.jsonHandler import jsonHandler
from .structure.simpleMsg import simpleMsg
from .structure.quickReplies import quickReplies
from .structure.templates import templates
from .structure.buttons import buttons
class messenger(jsonHandler, simpleMsg, quickReplies, templates, buttons):
"""[summary]
Arguments:
jsonHandler {class} -- operate on received json
simpleMsg {class} -- responsible for simple messages
quickReplies {class} -- responsible for quick Replies
templates {class} -- responsible for templates
buttons {class} -- responsible for buttons
"""
def __init__(self):
self.ACCESS_TOKEN = ""
self.VERIFY_TOKEN = ""
self.URL_BASE = "https://graph.facebook.com/v2.6/me/"
self.URL_BASE_TEMPS = "https://graph.facebook.com/me/"
self.post_url = "messages?access_token="
self.assest_url = "message_attachments?access_token="
def URL_TO_POST(self, url):
"""return the required url to the api
Arguments:
url {string} -- url to api
Returns:
string -- url to api
"""
return self.URL_BASE + url + self.ACCESS_TOKEN
def Verify_Token(self, token):
"""verfiy toke in when setup webhooks
Arguments:
token {string} -- token to be verfied
Returns:
bool -- if the toke is coorect or not
"""
if (token == self.VERIFY_TOKEN):
return True
else:
return False
def sender(self, jsonToSend, assest=False):
"""send json to facebook api
Arguments:
jsonToSend {json} -- json of any kind to send
Keyword Arguments:
assest {bool} -- if you want to send assests set it to true (default: {False})
Returns:
requst object -- return the reponse of the sending
"""
post_message_url = ""
if assest:
post_message_url = self.URL_TO_POST(self.assest_url)
else :
post_message_url = self.URL_TO_POST(self.post_url)
headers = {"Content-Type": "application/json"}
req = requests.post(post_message_url, headers=headers, data=jsonToSend, timeout=20)
return req
def savingAssests(self, type_of_content, url):
"""save assests to facebook server
Arguments:
type_of_content {string} -- tyoe if content image, video, audio, file
url {string} -- url of the media
Returns:
string -- id of assest to use it in buttons,temps,...etc
"""
json_body = { "message": {"attachment": {"type": type_of_content, "payload": {"is_reusable": "true", "url": url}}}}
json_body = json.dumps(json_body)
req = self.sender(json_body, assest=True)
return req.json()["attachment_id"]
def addObject(self, obje, arrayOfObjects=[]):
"""add object to array
Arguments:
obje {object} -- any object to be added
Keyword Arguments:
arrayOfObjects {list} -- list of objects (default: {[]})
Returns:
list -- return list after being added to list
"""
arrayOfObjects = arrayOfObjects + [obje]
return arrayOfObjects
def downloadFile(self, id, url):
"""rebonsible for downloading
Arguments:
id {string} -- id of user
url {string} -- url of file
Returns:
string -- file's name
"""
local_filename = str(id)+".mp4"
r = requests.get(url, stream=True)
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
return local_filename
def covertMp4Towav(self, inputName, outputName):
"""convert mp4 file to wave
Arguments:
inputName {string} -- file name
outputName {string} -- file name after converting
"""
audioclip = AudioFileClip(inputName)
audioclip.write_audiofile(outputName)
def voiceNoteToText(self, id, url, lan="en-US"):
"""extract text from voice note
Arguments:
id {string} -- user id
url {string} -- url of the voice note
Keyword Arguments:
lan {string} -- language of the voice note (default: {"en-US"})
Returns:
string -- text ininside voice note
"""
nameIn = str(id)+".mp4"
nameOut = str(id)+".wav"
self.downloadFile(id, url)
self.covertMp4Towav(nameIn, nameOut)
r = sr.Recognizer()
with sr.AudioFile(nameOut) as source:
audio = r.record(source)
command = r.recognize_google(audio, language=lan)
return command | zoldyck | /messengerBot/messenger.py | messenger.py |
class jsonHandler():
def checkForMessageAttr(self, receivedJson):
"""check for message attribute inside the json
Arguments:
receivedJson {json} -- received json
Returns:
bool -- if it is inside the json or not
"""
result = receivedJson["entry"][0]["messaging"][0].get("message", "no")
if result == "no":
return False
return True
def checkForAttachment(self, receivedJson):
"""check for Attachment attribute inside the json
Arguments:
receivedJson {json} -- received json
Returns:
bool -- if it is inside the json or not
"""
result = receivedJson["entry"][0]["messaging"][0].get("message").get("attachments", "no")
if result == "no":
return False
return True
def checkForQuickReply(self, receivedJson):
"""check for Quick Reply attribute inside the json
Arguments:
receivedJson {json} -- received json
Returns:
bool -- if it is inside the json or not
"""
result = receivedJson["entry"][0]["messaging"][0].get("message").get("quick_reply", "no")
if result == "no":
return False
return True
def checkForText(self, receivedJson):
"""check for Text attribute inside the json
Arguments:
receivedJson {json} -- received json
Returns:
bool -- if it is inside the json or not
"""
result = receivedJson["entry"][0]["messaging"][0].get("message").get("text")
if result == "no":
return False
return True
def checkForPostback(self, receivedJson):
"""check for Postback attribute inside the json
Arguments:
receivedJson {json} -- received json
Returns:
bool -- if it is inside the json or not
"""
result = receivedJson["entry"][0]["messaging"][0].get("postback", "no")
if result == "no":
return False
return True
def returnJsonType(self, receivedJson):
"""it detect the type of message sent
Arguments:
receivedJson {json} -- received json
Returns:
string -- type of the message
"""
if not self.checkForMessageAttr(receivedJson):
if self.checkForPostback(receivedJson):
return "postback"
if self.checkForAttachment(receivedJson):
return receivedJson["entry"][0]["messaging"][0].get("message").get("attachments")[0].get("type")
elif self.checkForQuickReply(receivedJson):
return "quick_reply"
elif self.checkForText(receivedJson):
return "text"
def getQuickReplyPayload(self, receivedJson):
"""get the quick reply payload from received json
Arguments:
receivedJson {json} -- received json
Returns:
string -- payload of false in there is no quick reply payload
"""
if not self.checkForQuickReply(receivedJson):
return "False"
return receivedJson["entry"][0]["messaging"][0].get("message").get("quick_reply").get("payload")
def getAttachementLink(self, receivedJson):
"""get the attachment link from received json
Arguments:
receivedJson {json} -- received json
Returns:
string -- Attachement Link
"""
if not self.checkForAttachment(receivedJson):
return "False"
return receivedJson["entry"][0]["messaging"][0].get("message").get("attachments")[0].get("payload").get("url")
def returnReceptionId(self, receivedJson):
"""get the user -sender- id
Arguments:
receivedJson {json} -- received json
Returns:
string -- user -sender- id
"""
return receivedJson["entry"][0]["messaging"][0]["sender"]["id"]
def returnReceivedText(self, receivedJson):
"""it the type of received message is text, so this function bet you that text
Arguments:
receivedJson {json} -- received json
Returns:
string -- received text
"""
text = receivedJson["entry"][0]["messaging"][0].get("message")
if text:
return text["text"]
def returnPostbackPayload(self, receivedJson):
"""get the postback text received
Arguments:
receivedJson {json} -- received json
Returns:
string -- received postback
"""
return receivedJson["entry"][0]["messaging"][0].get("postback")["payload"]
def returnPostbackTitle(self, receivedJson):
"""get the postback title received
Arguments:
receivedJson {json} -- received json
Returns:
string -- received postback title
"""
return receivedJson["entry"][0]["messaging"][0].get("postback")["title"]
def returnLatAndLong(self, receivedJson):
"""get the latitude and longitude received from location quick reply
Arguments:
receivedJson {json} -- received json
Returns:
json -- latitude and longitude
"""
return receivedJson["entry"][0]["messaging"][0].get("message").get("attachments")[0].get("payload").get("coordinates") | zoldyck | /messengerBot/handlers/jsonHandler.py | jsonHandler.py |
import json
class buttons():
def createUrlButtonJson(self, url, title, webHeightRatio="full"):
"""Create button when you press it it open url
Arguments:
url {string} -- url of site you whant to go to when button pressed
title {string} -- title of button
Keyword Arguments:
webHeightRatio {str} -- Height of the Webview (default: {"full"})
Returns:
Json Object -- json object of button
"""
json_body = {"type": "web_url", "url": url, "title": title,
"webview_height_ratio": webHeightRatio}
json_body = json.dumps(json_body)
return json_body
def createUrlButtonWithMsgExtJson(self, url, title, fullbackIRL,
webHeightRatio="full",
messengerExt="false"):
"""Create button when you press it it open url with messenger Extention
Arguments:
url {string} -- url of site you whant to go to when button pressed
title {string} -- title of button
fullbackIRL {[type]} -- The URL to use on clients that don't support Messenger Extensions.
If this is not defined, the url will be used as the fallback.
It may only be specified if messenger_extensions is true.
Keyword Arguments:
webHeightRatio {str} -- Height of the Webview (default: {"full"})
messengerExt {str} -- Must be true if using Messenger Extensions. (default: {"false"})
Returns:
Json Object -- json object of button
"""
json_body = {"type": "web_url", "url": url, "title": title,
"webview_height_ratio": webHeightRatio}
json_body["messenger_extensions"] = "true"
json_body["fallback_url"] = fullbackIRL
json_body = json.dumps(json_body)
return json_body
def createPostbackButtonJson(self, title, payload):
"""Create button when you press it send request to ypur server with text -payload-
Arguments:
title {string} -- title of button
payload {string} -- text you want to be send to your server
Returns:
Json Object -- json object of button
"""
json_body = {"type": "postback", "title": title, "payload": payload}
json_body = json.dumps(json_body)
return json_body
def createShareButtonJson(self, title, subtitle, imageUrl,
tempUrl, Urlbutton=[]):
"""[summary]
Arguments:
title {string} -- title of button
subtitle {string} -- subtitle of the temp
imageUrl {string} -- url of photo to the template
tempUrl {string} -- url you want user go to when template is pressed
Keyword Arguments:
Urlbutton {list} -- list of buttons to share it (default: {[]})
Returns:
Json Object -- json object of button
"""
json_body = {"type": "element_share",
"share_contents": {"attachment": {"type": "template", "payload": {"template_type": "generic",
"elements": [{"title": title,
"subtitle": subtitle,
"image_url": imageUrl,
"default_action": {
"type": "web_url",
"url": tempUrl},
"buttons": Urlbutton}]}}}}
json_body = json.dumps(json_body)
return json_body
def createPriceListJson(self, label, amount):
"""create list of prices to be added to buy button
Arguments:
label {string} -- label of price
amount {string} -- amount of the product
Returns:
Json Object -- json object of button
"""
json_body = {"label": label, "amount": amount}
json_body = json.dumps(json_body)
return json_body
def createBuyButtonJson(self, title, payload, currency, payment_type,
Pricelists, merchant_name, is_test_payment="true"):
"""[summary]
Arguments:
title {string} -- title of button
payload {string} -- Developer defined metadata about the purchase.
currency {string} -- Currency for price.
payment_type {string} -- Must be FIXED_AMOUNT or FLEXIBLE_AMOUNT.
Pricelists {list} -- List of objects used to calculate total price.
Each label is rendered as a line item in the checkout dialog.
merchant_name {string} -- Name of merchant.
Keyword Arguments:
is_test_payment {str} -- Optional. Whether this is a test payment. Once set to true, the charge will be a dummy charge.
Returns:
Json Object -- json object of button
"""
json_body = {"type": "payment", "title": title, "payload": payload}
json_body["payment_summary"] = {"currency": currency, "payment_type": payment_type,
"is_test_payment": is_test_payment, "merchant_name": merchant_name}
json_body["payment_summary"]["requested_user_info"] = ["shipping_address", "contact_name", "contact_phone",
"contact_email"]
json_body["payment_summary"]["price_list"] = {"price_list": Pricelists}
json_body = json.dumps(json_body)
return json_body
def createCallButton(self, title, phoneNumber):
"""[summary]
Arguments:
title {string} -- title of button
phoneNumber {string} -- Format must have "+" prefix followed by the country code,
area code and local number. For example, +16505551234.
Returns:
Json Object -- json object of button
"""
json_body = {"type": "phone_number", "title": title,
"payload": phoneNumber}
json_body = json.dumps(json_body)
return json_body | zoldyck | /messengerBot/structure/buttons.py | buttons.py |
import json
class simpleMsg():
def __init__(self):
self.type = "simple"
def createTextMsgJson(self, rec_ID, msg, msg_type, tag=None,
notification_type="REGULAR"):
"""This functions responsible for creating Json Object
to send text message to facebook messenger
Arguments:
rec_ID {string} -- recipient id
msg {string} -- message you want to send to messenger
msg_type {string} -- identifies the messaging type of the message being sent
https://developers.facebook.com/docs/messenger-platform/send-messages#messaging_types
Keyword Arguments:
tag {string} -- Message tags give you the ability to send messages to
a person outside of the normally allowed 24-hour window
for all possible values check link] (default: {None})
https://developers.facebook.com/docs/messenger-platform/send-messages/message-tags
notification_type {str} -- Push notification type (default: {"REGULAR"})
https://developers.facebook.com/docs/messenger-platform/reference/send-api/#payload
Returns:
Json Object -- complete Json Object to be send to facebook API
"""
json_body = dict()
if msg_type == "MESSAGE_TAG":
json_body["tag"] = tag
json_body["messaging_type"] = msg_type
json_body["recipient"] = {"id": rec_ID}
json_body["message"] = {"text": msg}
json_body["notification_type"] = notification_type
json_body = json.dumps(json_body)
return json_body
def createMediaByURLJson(self, url, rec_ID, media_type, Assest=False):
"""This functions responsible for creating Json Object
to send message with attachment (image,video,audio,files)
to facebook messenger by URL
Arguments:
url {string} -- URL of the media you want to send
rec_ID {string} -- recipient id
media_type {string} -- type of medial (image,video,audio,files)
Keyword Arguments:
Assest {bool} -- [check if you want to save this attachment in facebook
if it is true facebook will send you id for this attach.] (default: {False})
Returns:
Json Object -- complete Json Object to be send to facebook API
"""
json_body = dict()
json_body["recipient"] = {"id": rec_ID}
json_body["message"] = {"attachment": {"type": media_type, "payload":
{"url": url, "is_reusable": str(Assest).lower()
}}}
json_body = json.dumps(json_body)
return json_body
def createMediaByAssestIdJson(self, rec_ID, media_type, assestID):
"""This functions responsible for creating Json Object
to send message with attachment (image,video,audio,files)
to facebook messenger by Assest ID
for more info : https://developers.facebook.com/docs/messenger-platform/send-messages/saving-assets
Arguments:
rec_ID {string} -- recipient id
media_type {string} -- type of medial (image,video,audio,files)
assestID {string} -- id given by facbook when you save attachment in it
Returns:
Json Object -- complete Json Object to be send to facebook API
"""
json_body = dict()
json_body["recipient"] = {"id": rec_ID}
json_body["message"] = {"message": {"attachment": {"type": media_type,
"payload": {"attachment_id": assestID}}}}
json_body = json.dumps(json_body)
return json_body
def creatTypingStatusJson(self, rec_ID, status):
"""This functions responsible for creating Json Object
to create (seen , typing on , typing off) effect in
facebook messenger
Arguments:
rec_ID {string} -- recipient id
status {string} -- status of the boot (seen , typing on , typing off)
Returns:
Json Object -- complete Json Object to be send to facebook API
"""
json_body = dict()
json_body["recipient"] = {"id": rec_ID}
if status == "on":
json_body["sender_action"] = "typing_on"
elif status == "off":
json_body["sender_action"] = "typing_off"
elif status == "seen":
json_body["sender_action"] = "mark_seen"
json_body = json.dumps(json_body)
return json_body | zoldyck | /messengerBot/structure/simpleMsg.py | simpleMsg.py |
import json
class quickReplies():
def creatTextQuickReplyJson(self, title, payload, buttonImageUrl):
"""create text reply which user can press it inside messenger
Arguments:
title {string} -- [name appear on reply]
payload {string} -- text defined by programmer which will be
return to server if user press the reply
buttonImageUrl {string} -- URL for png photo for reply
Returns:
Json Object -- only return json for text reply
"""
json_body = dict()
json_body = {"content_type": "text", "title": title,
"payload": payload, "image_url": buttonImageUrl}
json_body = json.dumps(json_body)
return json_body
def creatLocationQuickReplyJson(self):
"""create reply which user can press it inside messenger
it will open a map allowing user to choose location
then messenger will send back to server latitude and longitude
Returns:
Json Object -- only return json for location reply
"""
json_body = dict()
json_body = {"content_type": "location"}
json_body = json.dumps(json_body)
return json_body
def creatPhoneNumberQuickReplyJson(self, payload, buttonImageUrl):
"""create reply which user can press it inside messenger
to send his phone number
Arguments:
payload {string} -- text defined by programmer which will be
return to server if user press the reply
buttonImageUrl {string} -- URL for png photo for reply
Returns:
Json Object -- only return json for number reply
"""
json_body = dict()
json_body = {"content_type": "user_phone_number", "payload": payload,
"image_url": buttonImageUrl}
json_body = json.dumps(json_body)
return json_body
def creatEmailQuickReplyJson(self, payload, buttonImageUrl):
"""create reply which user can press it inside messenger
to send his email
Arguments:
payload {string} -- text defined by programmer which will be
return to server if user press the reply
buttonImageUrl {string} -- URL for png photo for reply
Returns:
Json Object -- only return json for email reply
"""
json_body = dict()
json_body = {"content_type": "user_email", "payload": payload,
"image_url": buttonImageUrl}
json_body = json.dumps(json_body)
return json_body
def creatFullRepliesWithTextJson(self, rec_ID, text, repliesArray):
"""create full json to send all replies you have created
to facebook messenger with simple text above it
Arguments:
rec_ID {string} -- recipient id
text {string} -- text will be sent above replies
repliesArray {list} -- list of replies json
Returns:
Json Object -- complete Json Object to be send to facebook API
"""
json_body = dict()
json_body["recipient"] = {"id": rec_ID}
json_body["message"] = {"text": text, "quick_replies": repliesArray}
json_body = json.dumps(json_body)
return json_body
def creatFullRepliesWithMediaJson(self, rec_ID, repliesArray, mediaType,
content, contentTypeAssest=False):
"""create full json to send all replies you have created
to facebook messenger with attachment above it
Arguments:
rec_ID {string} -- recipient id
repliesArray {list} -- list of replies json
mediaType {string} -- type of medial (image,video,audio,files)
content {string} -- url or Assest id of attachment
Keyword Arguments:
contentTypeAssest {bool} -- if true that means (content) argument
is Assest Id not URL (default: {False})
Returns:
Json Object -- complete Json Object to be send to facebook API
"""
json_body = dict()
json_body["recipient"] = {"id": rec_ID}
json_body["message"] = {"quick_replies": repliesArray}
if (contentTypeAssest is False):
json_body["message"]["attachment"] = {"type": mediaType, "payload":
{"url": content}}
else:
json_body["message"]["attachment"] = {"type": mediaType, "payload":
{"attachment_id": content}}
json_body = json.dumps(json_body)
return json_body | zoldyck | /messengerBot/structure/quickReplies.py | quickReplies.py |
import json
class templates():
def createDefaultActionJson(self, url, webHeightRatio="full"):
"""The default action executed when the template is tapped.
Arguments:
url {string} -- url of site you whant to go to when it pressed
Keyword Arguments:
webHeightRatio {string} -- Height of the Webview (default: {"full"})
Returns:
Json Object -- json object of Default Action section
"""
json_body = {"type": "web_url", "url": url,
"webview_height_ratio": webHeightRatio}
json_body = json.dumps(json_body)
return json_body
def createDefaultActionWithMsgExtJson(self, url, fullbackIRL,
webHeightRatio="full"):
"""The default action executed when the template is tapped.
with messenger Extention
Arguments:
url {string} -- url of site you whant to go to when button pressed
fullbackIRL {string} -- The URL to use on clients that don't support Messenger Extensions.
If this is not defined, the url will be used as the fallback.
It may only be specified if messenger_extensions is true.
Keyword Arguments:
webHeightRatio {string} -- Height of the Webview (default: {"full"})
Returns:
Json Object -- json object of Default Action section
"""
json_body = {"type": "web_url", "url": url,
"webview_height_ratio": webHeightRatio}
json_body["messenger_extensions"] = "true"
json_body["fallback_url"] = fullbackIRL
json_body = json.dumps(json_body)
return json_body
def createElementJson(self, title, subTitle, imageUrl, defaultAction):
"""body of the template
Arguments:
title {string} -- The title to display in the template. 80 character limit.
subTitle {string} -- The subtitle to display in the template. 80 character limit.
imageUrl {string} -- The URL of the image to display in the template.
defaultAction {json} -- The default action executed when the template is tapped.
Returns:
Json Object -- json object of element section
"""
json_body = {"title": title, "image_url": imageUrl,
"subtitle": subTitle, "default_action": defaultAction}
json_body = json.dumps(json_body)
return json_body
def createElementWithButtonJson(self, title, subTitle, imageUrl,
defaultAction, buttons):
"""body of the template with button
Arguments:
title {string} -- The title to display in the template. 80 character limit.
subTitle {string} -- The subtitle to display in the template. 80 character limit.
imageUrl {string} -- The URL of the image to display in the template.
defaultAction {json} -- The default action executed when the template is tapped.
buttons {list} -- An array of buttons to append to the template. A maximum of 3 buttons per element is supported.
Returns:
Json Object -- json object of element section
"""
json_body = {"title": title, "image_url": imageUrl,
"subtitle": subTitle, "default_action": defaultAction,
"buttons": buttons}
json_body = json.dumps(json_body)
return json_body
def createGenericTempleteJson(self, rec_ID, elementsList):
"""create the full generic template json
Arguments:
rec_ID {string} -- user id
elementsList {list} -- An array of element objects that describe instances of the generic template to be sent.
Specifying multiple elements will send a horizontally scrollable carousel of templates.
A maximum of 10 elements is supported.
Returns:
Json Object -- json object of full generic template
"""
self.type = "generic"
json_body = {"recipient": {"id": rec_ID}, "message": {
"attachment": {"type": "template", "payload":
{"template_type": "generic",
"elements": elementsList}}}}
json_body = json.dumps(json_body)
return json_body
def createListTempleteJson(self, rec_ID, elementsList,
topElementStyle="compact"):
"""create the full list template json
Arguments:
rec_ID {string} -- user id
elementsList {list} -- An array of element objects that describe instances of the generic template to be sent.
Specifying multiple elements will send a horizontally scrollable carousel of templates.
A maximum of 10 elements is supported.
Keyword Arguments:
topElementStyle {string} -- Sets the format of the first list items.
Messenger web client currently only renders compact. (default: {"compact"})
Returns:
Json Object -- json object of full list template
"""
self.type = "list"
json_body = {"recipient": {"id": rec_ID}, "message": {"attachment": {"type": "template",
"payload": {"template_type": "list",
"top_element_style": topElementStyle,
"elements": elementsList}}}}
json_body = json.dumps(json_body)
return json_body
def createListTemplateWithButtonJson(self, rec_ID, elementsList,
buttomButton, topElementStyle="compact"):
"""create the full list template json with buttom button
Arguments:
rec_ID {string} -- user id
elementsList {list} -- An array of element objects that describe instances of the generic template to be sent.
Specifying multiple elements will send a horizontally scrollable carousel of templates.
A maximum of 10 elements is supported.
buttomButton {list} -- Button to display on the list item. Maximum of 1 button is supported.
Keyword Arguments:
topElementStyle {str} -- Sets the format of the first list items.
Messenger web client currently only renders compact. (default: {"compact"})
Returns:
Json Object -- json object of full list template with buttom button
"""
self.type = "list"
json_body = {"recipient": {"id": rec_ID}, "message": {"attachment": {"type": "template",
"payload": {"template_type": "list",
"top_element_style": topElementStyle,
"elements": elementsList,
"buttons": buttomButton}}}}
json_body = json.dumps(json_body)
return json_body
def createButtonTemplateJson(self, rec_ID, text, buttonList):
"""create the full Button template json
Arguments:
rec_ID {string} -- user id
text {string} -- UTF-8-encoded text of up to 640 characters. Text will appear above the buttons.
buttonList {list} -- Set of 1-3 buttons that appear as call-to-actions.
Returns:
Json Object -- json object of full Button template
"""
self.type = "button_temp"
json_body = {"recipient": {"id": rec_ID}, "message": {"attachment": {"type": "template",
"payload": {"template_type": "button",
"text": text,
"buttons": buttonList}}}}
json_body = json.dumps(json_body)
return json_body
def createOpenGraphElementJson(self, elementUrl, button):
"""object that describes the open graph object to display.
Arguments:
elementUrl {string} -- String to display as the title of the list item.
80 character limit. May be truncated if the title spans too many lines.
button {list} -- An array of buttons to append to the template.
Returns:
Json Object -- json object of element section
"""
json_body = {"url": elementUrl, "buttons": button}
json_body = json.dumps(json_body)
return json_body
def createOpenGraphTemplateJson(self, rec_ID, elements):
"""create the full open graph template json
Arguments:
rec_ID {string} -- user id
elements {list} -- Array of maximum 1 object that describes the open graph object to display.
Returns:
Json Object -- json object of open graph template
"""
json_body = {"recipient": {"id": rec_ID}, "message": {
"attachment": {"type": "template", "payload": {"template_type": "open_graph", "elements": elements}}}}
json_body = json.dumps(json_body)
return json_body
def createMediaTemplateUrlJson(self, rec_ID, mediaType, Url, button):
"""create the full media template json
Arguments:
rec_ID {string} -- user id
mediaType {string} -- The type of media being sent - image or video is supported.
Url {string} -- The URL of the image
button {list} -- An array of button objects to be appended to the template. A maximum of 1 button is supported.
Returns:
Json Object -- json object of media template
"""
json_body = {"recipient": {"id": rec_ID}, "message": {"attachment": {"type": "template",
"payload": {"template_type": "media",
"elements": [
{"media_type": mediaType,
"url": Url,
"buttons": button}]}}}}
json_body = json.dumps(json_body)
return json_body
def createMediaTemplateIdJson(self, rec_ID, mediaType, attID):
"""create the full media template json by assest id
Arguments:
rec_ID {string} -- user id
mediaType {string} -- The type of media being sent - image or video is supported.
attID {string} -- The attachment ID of the image or video.
Returns:
Json Object -- json object of media template
"""
json_body = {"recipient": {"id": rec_ID}, "message": {"attachment": {"type": "template",
"payload": {"template_type": "media",
"elements": [
{"media_type": mediaType,
"attachment_id": attID}]}}}}
json_body = json.dumps(json_body)
return json_body
def createReceiptTemplateSummaryJson(self, total_cost, subtotal="", shipping_cost="", total_tax=""):
"""The payment summary
Arguments:
total_cost {string} -- The total cost of the order, including sub-total, shipping, and tax.
Keyword Arguments:
subtotal {string} -- The sub-total of the order. (default: {""})
shipping_cost {string} -- The shipping cost of the order. (default: {""})
total_tax {string} -- The tax of the order. (default: {""})
Returns:
Json Object -- json object of Summary section
"""
json_body = {"subtotal": subtotal, "shipping_cost": shipping_cost, "total_tax": total_tax,
"total_cost": total_cost}
json_body = json.dumps(json_body)
return json_body
def createReceiptTemplateAdjustmentJson(self, name, amount):
"""An array of payment objects that describe payment adjustments, such as discounts.
Arguments:
name {string} -- Name of the adjustment.
amount {string} -- The amount of the adjustment.
Returns:
Json Object -- json object of Adjustment section
"""
json_body = {"name": name, "amount": amount}
json_body = json.dumps(json_body)
return json_body
def createReceiptTemplateElementsJson(self, title, price, subtitle="", quantity="", currency="", image_url=""):
""" Array of a maximum of 100 element objects that describe items in the order.
Sort order of the elements is not guaranteed.
Arguments:
title {string} -- The name to display for the item.
price {string} -- The price of the item. For free items, '0' is allowed.
Keyword Arguments:
subtitle {string} -- The subtitle for the item, usually a brief item description.
quantity {string} -- The quantity of the item purchased.
currency {string} -- The currency of the item price.
image_url {string} -- The URL of an image to be displayed with the item.
Returns:
Json Object -- json object of element section
"""
json_body = {"title": title, "subtitle": subtitle, "quantity": quantity, "price": price, "currency": currency,
"image_url": image_url}
json_body = json.dumps(json_body)
return json_body
def createReceiptTemplateAddressJson(self, street_1, city, postal_code, state, country, street_2=""):
"""The shipping address of the order.
Arguments:
street_1 {string} -- The street address, line 1
city {string} -- The city name of the address.
postal_code {string} -- The postal code of the address.
state {string} -- The state abbreviation for U.S. addresses, or the region/province for non-U.S. addresses.
country {string} -- The two-letter country abbreviation of the address.
Keyword Arguments:
street_2 {string} -- [description] (default: {""})
Returns:
Json Object -- json object of address section
"""
json_body = {"street_1": street_1, "street_2": street_2, "city": city, "postal_code": postal_code,
"state": state, "country": country}
json_body = json.dumps(json_body)
return json_body
def createReceiptTemplateJson(self, rec_ID, recipient_name, order_number, currency, payment_method, order_url,
summary, timestamp="",
address="", adjustments="", elements=""):
"""create the full Receipt template json
Arguments:
rec_ID {string} -- rec_ID {string} -- user id
recipient_name {string} -- The recipient's name.
order_number {string} -- The order number. Must be unique.
currency {string} -- The currency of the payment.
payment_method {string} -- The payment method used. Providing enough information for
the customer to decipher which payment method and account they used is recommended.
This can be a custom string, such as, "Visa 1234".
order_url {string} -- The order number. Must be unique.
summary {json} -- The payment summary
Keyword Arguments:
timestamp {string} -- Timestamp of the order in seconds. (default: {""})
address {string} -- The shipping address of the order. (default: {""})
adjustments {list} -- list of payment objects that describe payment adjustments, such as discounts. (default: {""})
elements {list} -- Optional. Array of a maximum of 100 element objects that describe items in the order.
Sort order of the elements is not guaranteed. (default: {""})
Returns:
Json Object -- json object of Receipt template
"""
json_body = {"recipient": {"id": rec_ID},
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "receipt",
"recipient_name": recipient_name,
"order_number": order_number,
"currency": currency,
"payment_method": payment_method,
"order_url": order_url,
"timestamp": timestamp,
"address": address,
"summary": summary,
"adjustments": adjustments,
"elements": elements}}}}
json_body = json.dumps(json_body)
return json_body | zoldyck | /messengerBot/structure/templates.py | templates.py |
import os
from itertools import chain
from ..prefs.common import dataDir
from whoosh.fields import *
from whoosh.index import create_in
from whoosh.index import open_dir
from whoosh.query import *
import re
def index_root():
root = os.path.join(dataDir(), 'index')
if not os.path.exists(root):
os.makedirs(root, exist_ok=True)
return root
def storage_root():
root = os.path.join(dataDir(), 'storage')
return root
def hash_dir(*fs):
from hashlib import md5
hl = md5()
for f in fs:
hl.update(f.encode('utf-8'))
for f in fs:
hl.update(str(os.stat(f).st_atime + os.stat(f).st_mtime + os.stat(f).st_ctime).encode())
return hl.hexdigest()
def index():
schema = Schema(title=TEXT(stored=True, spelling_prefix=True),
itemID=NUMERIC(stored=True),
contentType=KEYWORD(stored=True),
key=ID(stored=True),
content=TEXT(stored=True, spelling_prefix=True), path=TEXT(stored=True))
indexdir = index_root()
datadir = dataDir()
if not os.path.exists(indexdir):
os.mkdir(indexdir)
ix = create_in(indexdir, schema)
else:
ix = open_dir(indexdir)
writer = ix.writer()
from ..sqls.base import create_conn
from ..sqls.gets import get_attachments
with create_conn() as conn:
attachs = get_attachments(conn)
for attach in attachs:
_attach_f = os.path.join(datadir, attach.relpath)
_attach_dir = os.path.dirname(_attach_f)
_cache_f = os.path.join(_attach_dir, '.zotero-ft-cache')
if not os.path.exists(_cache_f) or not os.path.exists(_attach_f):
continue
_dir_hash = hash_dir(_cache_f, _attach_f)
_hash_cache_f = os.path.join(_attach_dir, '.cache')
if os.path.exists(_hash_cache_f):
with open(_hash_cache_f, 'r') as r:
_old_hash = r.read().strip()
if _dir_hash == _old_hash:
continue
pass
with open(_hash_cache_f, 'w') as w:
w.write(hash_dir(_cache_f, _attach_f))
with open(_cache_f, 'r', encoding='utf-8', errors='ignore') as r:
content = r.read()
_pre, _ = os.path.splitext(os.path.basename(_attach_f))
title = _pre.split(' - ')[-1]
writer.add_document(title=title, content=content,
itemID=attach.itemID,
key=attach.key, path=attach.relpath)
writer.commit()
return ix.doc_count() | zolocal | /zolocal-0.2.0-py3-none-any.whl/pyzolocal/files/base.py | base.py |
from enum import Enum, unique
@unique
class fileds(Enum):
title = 1
abstractNote = 2
artworkMedium = 3
medium = 4
artworkSize = 5
date = 6
language = 7
shortTitle = 8
archive = 9
archiveLocation = 10
libraryCatalog = 11
callNumber = 12
url = 13
accessDate = 14
rights = 15
extra = 16
audioRecordingFormat = 17
seriesTitle = 18
volume = 19
numberOfVolumes = 20
place = 21
label = 22
publisher = 23
runningTime = 24
ISBN = 25
billNumber = 26
number = 27
code = 28
codeVolume = 29
section = 30
codePages = 31
pages = 32
legislativeBody = 33
session = 34
history = 35
blogTitle = 36
publicationTitle = 37
websiteType = 38
type = 39
series = 40
seriesNumber = 41
edition = 42
numPages = 43
bookTitle = 44
caseName = 45
court = 46
dateDecided = 47
docketNumber = 48
reporter = 49
reporterVolume = 50
firstPage = 51
versionNumber = 52
system = 53
company = 54
programmingLanguage = 55
proceedingsTitle = 56
conferenceName = 57
DOI = 58
dictionaryTitle = 59
subject = 60
encyclopediaTitle = 61
distributor = 62
genre = 63
videoRecordingFormat = 64
forumTitle = 65
postType = 66
committee = 67
documentNumber = 68
interviewMedium = 69
issue = 70
seriesText = 71
journalAbbreviation = 72
ISSN = 73
letterType = 74
manuscriptType = 75
mapType = 76
scale = 77
country = 78
assignee = 79
issuingAuthority = 80
patentNumber = 81
filingDate = 82
applicationNumber = 83
priorityNumbers = 84
issueDate = 85
references = 86
legalStatus = 87
episodeNumber = 88
audioFileType = 89
presentationType = 90
meetingName = 91
programTitle = 92
network = 93
reportNumber = 94
reportType = 95
institution = 96
nameOfAct = 97
codeNumber = 98
publicLawNumber = 99
dateEnacted = 100
thesisType = 101
university = 102
studio = 103
websiteTitle = 104
@unique
class itemTypes(Enum):
artwork = 1
attachment = 2
audioRecording = 3
bill = 4
blogPost = 5
book = 6
bookSection = 7
case = 8
computerProgram = 9
conferencePaper = 10
dictionaryEntry = 11
document = 12
email = 13
encyclopediaArticle = 14
film = 15
forumPost = 16
hearing = 17
instantMessage = 18
interview = 19
journalArticle = 20
letter = 21
magazineArticle = 22
manuscript = 23
map = 24
newspaperArticle = 25
note = 26
patent = 27
podcast = 28
presentation = 29
radioBroadcast = 30
report = 31
statute = 32
thesis = 33
tvBroadcast = 34
videoRecording = 35
webpage = 36
class commonPrefs:
dataDir = "extensions.zotero.dataDir"
attachmentDir = "extensions.zotero.baseAttachmentPath" | zolocal | /zolocal-0.2.0-py3-none-any.whl/pyzolocal/beans/enum.py | enum.py |
import platform
import json
import configparser
import os
from functools import lru_cache
def is_win():
return 'windows' in platform.platform().lower()
def is_mac():
# TODO
raise NotImplementedError()
def is_linux():
raise NotImplementedError()
# return 'linux' in platform.platform().lower()
def read_profile_path(fn):
"""
load profile path from profiles.ini
:param fn:
:return:
"""
config = configparser.ConfigParser()
config.read(fn)
if len(config.sections()) == 2:
prof_key = config.sections()[-1]
else:
if config['General']['startwithlastprofile'] == '1':
prof_key = config.sections()[-1]
else:
raise NotImplementedError()
return config[prof_key]['Path']
def profile_root():
user_root = os.path.expanduser('~')
if is_win():
zotero_root = os.path.join(user_root, r'AppData\Roaming\Zotero\Zotero')
elif is_linux():
zotero_root = os.path.join(user_root, '.zotero/zotero')
elif is_mac():
zotero_root = os.path.join(user_root, 'Library/Application Support/Zotero')
else:
raise NotImplementedError()
return zotero_root
def prefs_root():
user_root = os.path.expanduser('~')
zotero_root = profile_root()
if is_win():
prof_relroot = read_profile_path(os.path.join(zotero_root, 'profiles.ini'))
return os.path.join(zotero_root, prof_relroot)
elif is_linux():
zotero_root = os.path.join(user_root, '.zotero/zotero')
elif is_mac():
zotero_root = os.path.join(user_root, 'Library/Application Support/Zotero')
else:
raise NotImplementedError()
@lru_cache(1)
def prefjs_fn():
return os.path.join(prefs_root(), 'prefs.js')
def try_parse_pref(value: str):
if value is None:
return value
if value.startswith('"'):
value = value.strip('"')
if value[0] in "[{":
value = value.replace('\\', '')
try:
value = json.loads(value)
except:
pass
return value
else:
if value in {'false', 'true'} or value.isnumeric():
return eval(value.title())
return value | zolocal | /zolocal-0.2.0-py3-none-any.whl/pyzolocal/prefs/base.py | base.py |
import os
import json
from ..sqls.base import exec_fetchall, pako_inflate
from typing import List, Dict
from ..beans.enum import fileds, itemTypes
from ..beans import types as t
from collections import defaultdict
def get_settings() -> dict:
sql = """
select value from settings
"""
_, values = exec_fetchall(sql)
return json.loads(pako_inflate(values[0][0]))
def get_creators() -> List[t.Creator]:
sql = 'select * from creators'
cursor, values = exec_fetchall(sql)
return [t.Creator(creatorID=i[0],
firstName=i[1], lastName=i[2], fieldMode=i[3]) for i in values]
def get_tags() -> List[t.Tag]:
sql = 'select * from tags'
cursor, values = exec_fetchall(sql)
return [t.Tag(tagId=i[0], name=i[1])
for i in values]
def get_collections() -> List[t.Collection]:
sql = """
select * from collections
"""
cursor, values = exec_fetchall(sql)
return [t.Collection(collectionID=i[0],
collectionName=i[1]) for i in values]
def get_itemids(include_delete=False) -> List[int]:
if include_delete:
sql = f"""
select itemID from items
"""
else:
sql = f"""
select itemID from items
where itemID not in (select itemID from deletedItems)
"""
cursor, values = exec_fetchall(sql)
return [i[0] for i in values]
def get_items_info() -> List[t.Item]:
sql = f"""
select * from
(select * from itemData)
left join itemDataValues
using (valueID)
where itemID not in (select itemID from deletedItems)
"""
cursor, values = exec_fetchall(sql)
if len(values) == 0:
return []
item_value_map_ = defaultdict(list)
for value in values:
item_value_map_[value[0]].append(value)
res = []
for item_id, val in item_value_map_.items():
item_datas = [t.ItemData(fileds(i[1]), i[2], i[3]) for i in val]
item = t.Item(itemID=item_id,
key=get_item_key_by_itemid(item_id),
itemDatas=item_datas)
res.append(item)
return res
def get_item_info_by_itemid(itemID: int) -> t.Item:
sql = f"""
select * from
(select * from itemData where itemID={itemID})
inner join itemDataValues using (valueID)
"""
cursor, values = exec_fetchall(sql)
if len(values) == 0:
return t.Item(-1)
item_id = values[0][0]
item_datas = [t.ItemData(fileds(i[1]), i[2], i[3]) for i in values]
return t.Item(itemID=item_id,
key=get_item_key_by_itemid(itemID),
itemDatas=item_datas)
def get_attachments() -> List[t.Attachment]:
"""
all attached files
:param conn:
:return:
"""
sql = """
select itemID,key,contentType,path from (
itemAttachments inner join items using (itemID)
)
"""
cursor, values = exec_fetchall(sql)
res = []
for (itemID, key, contentType, path) in values:
relpath = os.path.join('storage', key, path.replace('storage:', ''))
file = t.Attachment(itemID=itemID, key=key,
contentType=contentType, relpath=relpath)
res.append(file)
return res
def get_attachments_by_parentid(parentItemID: int) -> List[t.Attachment]:
"""
get attached file from parent
:param conn:
:param parentItemID:
:return:
"""
sql = f"""
select itemID,contentType,path from itemAttachments
where itemID in (select itemID from itemAttachments where parentItemID={parentItemID})
"""
cursor, values = exec_fetchall(sql)
if len(values) == 0:
return []
item_value_map_ = {}
for value in values:
item_value_map_[value[0]] = value
res = []
# item_id_type_map = get_items_type_by_itemids(*list(item_value_map_.keys()))
item_id_key_map = get_items_key_by_itemid(*list(item_value_map_.keys()))
for item_id, val in item_value_map_.items():
path = val[2] # type:str
key = item_id_key_map[item_id]
relpath = os.path.join('storage', key, path.replace('storage:', ''))
item = t.Attachment(itemID=item_id,
key=key,
contentType=val[1],
relpath=relpath)
res.append(item)
return res
def get_item_attachments_by_parentid(parentItemID: int) -> List[t.Item]:
"""
get attached item from parent
:param conn:
:param parentItemID:
:return:
"""
sql = f"""
select * from
(select * from itemData)
inner join itemDataValues
using (valueID)
where itemID in (select itemID from itemAttachments where parentItemID={parentItemID})
"""
cursor, values = exec_fetchall(sql)
if len(values) == 0:
return []
item_value_map_ = defaultdict(list)
for value in values:
item_value_map_[value[0]].append(value)
res = []
item_id_type_map = get_items_type_by_itemids(*list(item_value_map_.keys()))
item_id_key_map = get_items_key_by_itemid(*list(item_value_map_.keys()))
for item_id, val in item_value_map_.items():
item_datas = [t.ItemData(fileds(i[1]), i[2], i[3]) for i in val]
item = t.Item(itemID=item_id,
key=item_id_key_map[item_id],
itemType=itemTypes(item_id_type_map[item_id]),
itemDatas=item_datas)
res.append(item)
return res
def get_items_info_from_tag_by_tagid(tagID: int) -> List[t.Item]:
sql = f"""
select * from
(select * from itemData)
inner join itemDataValues using (valueID)
inner join (select itemID from itemTags where tagID={tagID}) using (itemID)
"""
cursor, values = exec_fetchall(sql)
if len(values) == 0:
return []
item_value_map_ = defaultdict(list)
for value in values:
item_value_map_[value[0]].append(value)
res = []
item_id_type_map = get_items_type_by_itemids(*list(item_value_map_.keys()))
item_id_key_map = get_items_key_by_itemid(*list(item_value_map_.keys()))
for item_id, val in item_value_map_.items():
item_datas = [t.ItemData(fileds(i[1]), i[2], i[3]) for i in val]
item = t.Item(itemID=item_id,
key=item_id_key_map[item_id],
itemType=itemTypes(item_id_type_map[item_id]),
itemDatas=item_datas)
res.append(item)
return res
def get_items_info_from_coll_by_collid(collID: int) -> List[t.Item]:
sql = f"""
select * from
(select * from itemData)
inner join itemDataValues using (valueID)
inner join (select itemID from collectionItems where collectionID={collID}) using (itemID)
"""
cursor, values = exec_fetchall(sql)
if len(values) == 0:
return []
item_value_map_ = defaultdict(list)
for value in values:
item_value_map_[value[0]].append(value)
res = []
item_id_type_map = get_items_type_by_itemids(*list(item_value_map_.keys()))
item_id_key_map = get_items_key_by_itemid(*list(item_value_map_.keys()))
for item_id, val in item_value_map_.items():
item_datas = [t.ItemData(fileds(i[1]), i[2], i[3]) for i in val]
item = t.Item(itemID=item_id,
key=item_id_key_map[item_id],
itemType=itemTypes(item_id_type_map[item_id]),
itemDatas=item_datas)
res.append(item)
return res
def get_items_key_by_itemid(*itemID: int) -> Dict[int, str]:
itemID_ = ','.join(f'{i}' for i in itemID)
sql = f"""
select itemID,key from items where itemID in ({itemID_})
"""
cursor, values = exec_fetchall(sql)
items_type = {i[0]: i[1] for i in values}
return items_type
def get_item_key_by_itemid(itemID: int) -> str:
return get_items_key_by_itemid(itemID)[itemID]
def get_items_type_by_itemids(*itemID: int) -> Dict[int, itemTypes]:
itemID_ = ','.join(f'{i}' for i in itemID)
sql = f"""
select itemID,itemTypeID from items where itemID in ({itemID_})
"""
cursor, values = exec_fetchall(sql)
items_type = {i[0]: itemTypes(i[0]) for i in values}
return items_type
def get_item_type_by_itemid(itemID: int) -> itemTypes:
return get_item_type_by_itemid(itemID)[0]
def get_item_tags_by_itemid(itemID: int) -> List[t.Tag]:
sql = f"""
select * from
(select * from itemTags where itemID={itemID})
inner join tags using (tagID)
"""
cursor, values = exec_fetchall(sql)
return [t.Tag(i[0], i[1]) for i in values] | zolocal | /zolocal-0.2.0-py3-none-any.whl/pyzolocal/sqls/gets.py | gets.py |
# Zoloto
[](https://zoloto.readthedocs.io/en/stable/?badge=stable)






A fiducial marker system powered by OpenCV - Supports ArUco and April
[Documentation](https://zoloto.readthedocs.io/)
## Installation
```text
pip install zoloto
```
### OpenCV
OpenCV should be installed manually, ideally through your system package manager. This makes it easier to customize your OpenCV installation for your system, or use the optimal settings for your OS / hardware. Note that you may need to install `opencv-contrib` as well as `opencv`.
If you'd rather have one installed automatically, install the extra `opencv`:
```text
pip install zoloto[opencv]
```
Note that this version lacks hardware acceleration. See [the README](https://github.com/opencv/opencv-python#readme) for more details.
For storage-constrained environments, there's also `opencv-contrib-python-headless`, which should be installed manually.
## Examples
```python
from pathlib import Path
from zoloto import MarkerType
from zoloto.cameras import ImageFileCamera
with ImageFileCamera(Path("my-image.png"), marker_type=MarkerType.ARUCO_6X6) as camera:
camera.save_frame("my-annotated-image.png", annotate=True)
print("I saved an image with {} markers in.".format(len(camera.get_visible_markers())))
```
[More examples](./zoloto/cli/)
Zoloto ships with a CLI (aptly named `zoloto`), which contains some helpful utils for working with Zoloto and fiducial markers.
## Development setup
`./scripts/setup.sh` will create a virtual environment, and install all the required development dependencies into it.
Note that this will not install a version of OpenCV for you. For that, run `./scripts/setup.sh opencv`.
There are some additional useful scripts to assist:
- `./scripts/test.sh`: Run the unit tests and linters
- `./scripts/fix.sh`: Automatically fix issues from `black` and `isort`
- `./scripts/benchmark.sh`: Run benchmarks (these can take a couple minutes depending on your hardware)
| zoloto | /zoloto-0.8.0.tar.gz/zoloto-0.8.0/README.md | README.md |
Calibration
===========
To perform accurate pose estimation, each camera must be calibrated. To calibrate the camera, OpenCV ships with a tool_ to assist.
The resulting calibration file can be passed into a :class:`zoloto.cameras.camera.Camera`.
Note: Occasionally on Linux, the tool will fail to open the camera. This happens as it uses gstreamer backend by default, whereas Zoloto uses v4l2. To disable gstreamer, set the ``OPENCV_VIDEOIO_PRIORITY_GSTREAMER=0`` environment variable.
Calibration Parameters
----------------------
.. autoclass:: zoloto.calibration.CalibrationParameters
:members:
.. _tool: https://docs.opencv.org/4.5.3/d7/d21/tutorial_interactive_calibration.html
| zoloto | /zoloto-0.8.0.tar.gz/zoloto-0.8.0/docs/calibration.rst | calibration.rst |
Coordinates
============
Orientation
-----------
.. autoclass:: zoloto.coords.Orientation
:members:
Coordinates
-----------
.. autoclass:: zoloto.coords.Coordinates
:members:
:no-inherited-members:
ThreeDCoordinates
-----------------
.. autoclass:: zoloto.coords.ThreeDCoordinates
:members:
:no-inherited-members:
Spherical
---------
.. autoclass:: zoloto.coords.Spherical
:members:
:no-inherited-members:
Quaternion
----------
.. class:: pyquaternion.quaternion.Quaternion
See https://kieranwynn.github.io/pyquaternion/
| zoloto | /zoloto-0.8.0.tar.gz/zoloto-0.8.0/docs/coordinates.rst | coordinates.rst |
Save markers
============
The ``save-markers`` tool outputs the images of all the fiducial markers in a given type.
Each marker is surrounded by a white boarder, which is not considered part of the marker (it's not counted when working out the marker's size).
When `--raw` is passed, Markers are output as PNG files, at their smallest possible format. They can then be resized as necessary without losing quality.
Without `--raw`, images are saved 500px, plus a border with text identifying which marker is being used.
| zoloto | /zoloto-0.8.0.tar.gz/zoloto-0.8.0/docs/cli/save-markers.rst | save-markers.rst |
from argparse import ArgumentParser
import dataclasses
import os
import subprocess
import sys
@dataclasses.dataclass(kw_only=True)
class Target:
lang: str = 'c'
name: str = 'target'
btype: str = 'exec'
def __post_init__(self):
self._warn_flags = []
self._source_dir = f'{root()}/src'
self._sources = []
self._include_dirs = []
self._libs = []
self._lib_dirs = []
self._output_dir = f'{root()}/build'
self._output = self.name
self._ext = {
'c': 'c',
'cpp': 'cpp',
}[self.lang]
self._compiler = {
'c': 'CC',
'cpp': 'CXX',
}[self.lang]
def warn(self, *flags):
self._warn_flags = [f'-W{flag}' for flag in flags]
def include(self, *paths):
self._include_dirs.extend(paths)
def link(self, *, paths, libs):
self._lib_dirs.extend(paths)
self._libs.extend(libs)
def sources(self, path, *sources):
self._source_dir = path
self._sources.extend((os.path.join(path, src) for src in sources))
def compile(self, path):
self._output_dir = path
self._output = os.path.join(path, self.name)
if not self._sources:
raise Exception('No sources specified')
def __call__(self):
if len(sys.argv) < 2:
raise Exception('No command specified')
parser = ArgumentParser()
parser.add_argument('-B', '--build-dir', default=f'{root()}/build/ZoMake')
args, other = parser.parse_known_args(sys.argv[2:])
self._build_dir = args.build_dir
if sys.argv[1] == 'init':
self._build_makefile()
elif sys.argv[1] == 'build':
if not os.path.exists(self._build_dir):
raise Exception('No ZoMake directory found')
subprocess.run(['make', '-C', self._build_dir, '-B', *other])
elif sys.argv[1] == 'clean':
pass
def _build_makefile(self):
if not os.path.exists(self._build_dir):
os.makedirs(self._build_dir, exist_ok=True)
with open(f'{self._build_dir}/Makefile', 'w') as f:
if hasattr(self, 'compiler'):
f.write(f'{self._compiler} := {self.compiler}\n')
if hasattr(self, 'std'):
f.write(f'STD := -std={self.std}\n')
if self._lib_dirs:
f.write(f'LIBDIRS := {" ".join(self._lib_dirs)}\n')
if self._libs:
f.write(f'LIBS := {" ".join(self._libs)}\n')
if self._include_dirs:
f.write(f'INCLUDES := {" ".join(self._include_dirs)}\n')
if self._warn_flags:
f.write(f'WARN := {" ".join(self._warn_flags)}\n')
f.write(f'TARGET := {self._output}\n')
f.write(f'SOURCES := {" ".join(self._sources)}\n')
f.write(f'OBJECTS := $(patsubst {self._source_dir}/%.{self._ext}, {self._output_dir}/%.o, $(SOURCES))\n')
f.write(f'all: $(TARGET)\n')
f.write(f'$(TARGET): $(OBJECTS)\n')
f.write(f'\t$({self._compiler}) $(WARN) $(STD) $^ $(LIBS) -o $@\n')
f.write(f'{self._output_dir}/%.o: {self._source_dir}/%.{self._ext} {self._output_dir}\n')
f.write(f'\t$({self._compiler}) $(WARN) $(STD) $(INCLUDES) -c $< -o $@\n')
f.write(f'{self._output_dir}:\n')
f.write(f'\tmkdir -p {self._output_dir}\n')
f.write(f'clean: clean-obj clean-exec\n')
f.write(f'clean-obj:\n')
f.write(f'\trm -f $(OBJECTS)\n')
f.write(f'clean-exec:\n')
f.write(f'\trm -f $(TARGET)\n')
def root():
return os.getcwd() | zomake | /zomake-0.1.0.tar.gz/zomake-0.1.0/src/zo/__init__.py | __init__.py |
zomathon
========
.. image:: https://badge.fury.io/py/zomathon.svg
:target: https://badge.fury.io/py/zomathon
Python Module for the Zomato API.
About the Zomato API
--------------------
.. figure:: http://knowstartup.com/wp-content/uploads/2015/09/logo-300x212.png
:alt: zomato
See the official API documentation for more information.
https://developers.zomato.com/api
Install
-------
::
$ pip3 install zomathon
Only pip3 is supported for now. If you don’t have pip installed on your
system
::
$ git clone https://github.com/abhishtagatya/zomathon
$ cd zomathon
$ python3 setup.py install
Getting Started
---------------
Usage :
::
import os
import sys
import json
from zomathon import ZomatoAPI
API_KEY = os.environ.get('ZOMATO_API_KEY')
zom = ZomatoAPI(API_KEY)
# For complete help on the module
help(zom)
Make sure to check out ``example/basic_usage.py`` for demonstrations :
::
$ python3 example/basic_usage.py
Or check out the interactive documentation over at `Zomato Documentation <https://developers.zomato.com/documentation>`__.
Authors
-------
- Abhishta Gatya - Initial Work
License
-------
This project is licensed under the MIT License - see the `LICENSE <https://github.com/abhishtagatya/zomathon/blob/master/LICENSE>`__. file
for details
| zomathon | /zomathon-1.4.tar.gz/zomathon-1.4/README.rst | README.rst |
**Greetings!**
`This is a python API, which is a wrapper class for the zomato's web based API`
`This API contains various functions`
`get_collections -> returns all restaurants in a given city`
`get_cuisines -> returns all cuisines types in a given city`
`get_establishment_types -> returns all establishment types in a given city`
`get_nearby_restaurants -> returns the nearby restaurants given your geo coordinates`
`restaurant_search -> returns dictionary of restaurants within a radius of your location and/or of cusine/s types`
**Steps before using this API**
`Please "Generate API key" from https://developers.zomato.com/api#headline2`
**To Install this API**
`pip install zomato-distribution-api==0.2.3`
**To Use this API**
`you have to import the Zomato class`
`create a Zomato's instance for example, z = Zomato(your_key), to access it's methods` | zomato-distribution-api | /zomato_distribution_api-0.2.3.tar.gz/zomato_distribution_api-0.2.3/README.md | README.md |
import requests
import ast
import json
base_url = "https://developers.zomato.com/api/v2.1/"
class Zomato:
"""
Wrapper class to the zomato web api.
original source: https://github.com/sharadbhat/Zomatopy
"""
def __init__(self, key):
self.user_key = key
def get_categories(self):
"""
@params: None.
@return: Returns a dictionary of IDs and their respective category names.
"""
headers = {'Accept': 'application/json', 'user-key': self.user_key}
r = requests.get(base_url + "categories", headers=headers).content.decode("utf-8")
a = ast.literal_eval(r)
self.is_key_invalid(a)
self.is_rate_exceeded(a)
categories = {}
for category in a['categories']:
categories.update({category['categories']['id']: category['categories']['name']})
return categories
def get_city_id(self, city_name=None, state_name=None):
"""
@params: string, city_name.
@return:
Returns the ID for the city given as input.
If no parameters are passed, returns city id based on current location
"""
if city_name is None or state_name is None:
lat, lon = self.get_geo_coords()
headers = {'Accept': 'application/json', 'user-key': self.user_key}
r = requests.get(base_url + "cities?lat=" + str(lat) + "&lon=" + str(lon), headers=headers).\
content.decode("utf-8")
a = json.loads(r)
if len(a['location_suggestions']) == 0:
raise Exception("current city's ID cannot be found!")
else:
return a['location_suggestions'][0]['id']
if not city_name.isalpha():
raise ValueError('InvalidCityName')
headers = {'Accept': 'application/json', 'user-key': self.user_key}
r = requests.get(base_url + "cities?q=" + city_name, headers=headers).content.decode("utf-8")
a = json.loads(r)
self.is_key_invalid(a)
self.is_rate_exceeded(a)
if len(a['location_suggestions']) == 0:
raise Exception('invalid_city_name')
elif 'name' in a['location_suggestions'][0]:
city_state = a['location_suggestions'][0]['name'].lower()
city, state = str(city_state.split(',')[0]), str(city_state.split(',')[1])
if city == str(city_name).lower() and state == str(state_name):
return a['location_suggestions'][0]['id']
else:
raise ValueError('InvalidCityId')
def get_city_name(self, city_id):
"""
@params: City ID int or str.
@return: the name of the city ID.
"""
self.is_valid_city_id(city_id)
headers = {'Accept': 'application/json', 'user-key': self.user_key}
r = requests.get(base_url + "cities?city_ids=" + str(city_id), headers=headers).content.decode("utf-8")
a = json.loads(r)
self.is_key_invalid(a)
self.is_rate_exceeded(a)
if a['location_suggestions'][0]['country_name'] == "":
raise ValueError('InvalidCityId')
else:
temp_city_id = a['location_suggestions'][0]['id']
if temp_city_id == str(city_id):
return a['location_suggestions'][0]['name']
def get_collections(self, city_id, limit=None):
"""
@param
city_id: int/str City ID as input.
limit: optional parameter. displays limit number of result.
@return
python dictionary of Zomato restaurant collections in a city and their respective URLs.
"""
self.is_valid_city_id(city_id)
headers = {'Accept': 'application/json', 'user-key': self.user_key}
if limit is None:
r = requests.get(base_url + "collections?city_id=" + str(city_id), headers=headers).content.decode(
"utf-8")
else:
if str(limit).isalpha():
raise ValueError('LimitNotInteger')
else:
r = (requests.get(base_url + "collections?city_id=" + str(city_id) + "&count=" + str(limit),
headers=headers).content).decode("utf-8")
a = json.loads(r)
self.is_key_invalid(a)
self.is_rate_exceeded(a)
collections = {}
for collection in a['collections']:
collections.update({collection['collection']['title']: collection['collection']['url']})
return collections
def get_cuisines(self, city_id):
"""
@params: City ID int/str
@return:
a sorted dictionary by ID of all cuisine IDs and their respective cuisine names.
key: cuisine name
value: dictionary
"""
self.is_valid_city_id(city_id)
headers = {'Accept': 'application/json', 'user-key': self.user_key}
r = requests.get(base_url + "cuisines?city_id=" + str(city_id), headers=headers).content.decode("utf-8")
a = ast.literal_eval(r)
self.is_key_invalid(a)
self.is_rate_exceeded(a)
if len(a['cuisines']) == 0:
raise ValueError('InvalidCityId')
temp_cuisines = {}
cuisines = {}
for cuisine in a['cuisines']:
# temp_cuisines.update({cuisine['cuisine']['cuisine_id']: cuisine['cuisine']['cuisine_name']})
temp_cuisines.update({cuisine['cuisine']['cuisine_name']: cuisine['cuisine']['cuisine_id']})
for cuisine in sorted(temp_cuisines):
cuisines.update({cuisine: temp_cuisines[cuisine]})
return cuisines
def get_establishment_types(self, city_id):
"""
@params: City ID (int/str).
@return: sorted dictionary of all establishment type IDs and their respective establishment type names.
"""
self.is_valid_city_id(city_id)
headers = {'Accept': 'application/json', 'user-key': self.user_key}
r = requests.get(base_url + "establishments?city_id=" + str(city_id), headers=headers).content.decode("utf-8")
a = ast.literal_eval(r)
self.is_key_invalid(a)
self.is_rate_exceeded(a)
temp_establishment_types = {}
establishment_types = {}
if 'establishments' in a:
for establishment_type in a['establishments']:
temp_establishment_types.update(
{establishment_type['establishment']['id']: establishment_type['establishment']['name']})
for establishment_type in sorted(temp_establishment_types):
establishment_types.update({establishment_type: temp_establishment_types[establishment_type]})
return establishment_types
else:
raise ValueError('InvalidCityId')
def get_nearby_restaurants(self, latitude="", longitude=""):
"""
@params: latitude and longitude of current or interested location.
@return: a dictionary of Restaurant IDs and their corresponding Zomato URLs.
"""
"""obtains the current location's latitude and longitude if none is provided"""
if latitude == "" or longitude == "":
latitude, longitude = self.get_geo_coords()
try:
float(latitude)
float(longitude)
except ValueError:
raise ValueError('InvalidLatitudeOrLongitude')
headers = {'Accept': 'application/json', 'user-key': self.user_key}
r = (requests.get(base_url + "geocode?lat=" + str(latitude) + "&lon=" + str(longitude),
headers=headers).content).decode("utf-8")
a = json.loads(r)
nearby_restaurants = {}
for nearby_restaurant in a['nearby_restaurants']:
nearby_restaurants.update({nearby_restaurant['restaurant']['id']: nearby_restaurant['restaurant']['url']})
return nearby_restaurants
def get_restaurant(self, restaurant_id):
"""
@params: Restaurant ID (int/str) as input.
@return: a dictionary of restaurant details.
"""
self.is_valid_restaurant_id(restaurant_id)
headers = {'Accept': 'application/json', 'user-key': self.user_key}
r = requests.get(base_url + "restaurant?res_id=" + str(restaurant_id), headers=headers).content.decode(
"utf-8")
a = json.loads(r)
if 'code' in a:
if a['code'] == 404:
raise ('InvalidRestaurantId')
restaurant_details = {}
restaurant_details.update({"name": a['name']})
restaurant_details.update({"url": a['url']})
restaurant_details.update({"location": a['location']['address']})
restaurant_details.update({"city": a['location']['city']})
restaurant_details.update({"city_ID": a['location']['city_id']})
restaurant_details.update({"user_rating": a['user_rating']['aggregate_rating']})
restaurant_details = DotDict(restaurant_details)
return restaurant_details
def restaurant_search(self, query="", latitude="", longitude="", radius="", cuisines="", limit=5):
"""
@params
query: string keyword to query.
latitude: latitude of interested place.
longitude: longitude of interested place.
radius: search restaurants within a radius in meters
cuisines: multiple cuisines as input in string format.
@return: a list of Restaurants.
"""
cuisines = "%2C".join(cuisines.split(","))
"""obtains the current location's latitude and longitude if none is provided"""
if latitude == "" or longitude == "":
latitude, longitude = self.get_geo_coords()
if str(limit).isalpha():
raise ValueError('LimitNotInteger')
headers = {'Accept': 'application/json', 'user-key': self.user_key}
r = (requests.get(
base_url + "search?q=" + str(query) + "&count=" + str(limit) + "&lat=" + str(latitude) + "&lon=" + str(
longitude) + "&radius=" + str(radius) + "&cuisines=" + str(cuisines), headers=headers).content).decode("utf-8")
a = json.loads(r)
if a['results_found'] == 0:
return []
else:
return a # dictionary of all restaurants
def is_valid_restaurant_id(self, restaurant_ID):
"""
Checks if the Restaurant ID is valid or invalid.
If invalid, throws a InvalidRestaurantId Exception.
@param: id of a restaurant
@return:
None
"""
restaurant_ID = str(restaurant_ID)
if not restaurant_ID.isnumeric():
raise ValueError('InvalidRestaurantId')
def is_valid_city_id(self, city_ID):
"""
Checks if the City ID is valid or invalid.
If invalid, throws a InvalidCityId Exception.
@param: id of a city
@return: None
"""
city_ID = str(city_ID)
if not city_ID.isnumeric():
raise ValueError('InvalidCityId')
def is_key_invalid(self, a):
"""
Checks if the API key provided is valid or invalid.
If invalid, throws a InvalidKey Exception.
@params: return of the web request in 'json'
@return: None
"""
if 'code' in a:
if a['code'] == 403:
raise ValueError('InvalidKey')
def is_rate_exceeded(self, a):
"""
Checks if the request limit for the API key is exceeded or not.
If exceeded, throws a ApiLimitExceeded Exception.
@params: return of the web request in 'json'
@return: None
"""
if 'code' in a:
if a['code'] == 440:
raise Exception('ApiLimitExceeded')
def get_geo_coords(self):
"""
captures latitude and longitude based on current location
@params: None
@return: latitude, longitude
"""
ip_request = requests.get('https://get.geojs.io/v1/ip.json')
my_ip = ip_request.json()['ip']
geo_request_url = 'https://get.geojs.io/v1/ip/geo/' + my_ip + '.json'
geo_request = requests.get(geo_request_url)
geo_data = geo_request.json()
return geo_data['latitude'], geo_data['longitude'] # latitude, longitude
class DotDict(dict):
"""
Dot notation access to dictionary attributes
"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__ | zomato-distribution-api | /zomato_distribution_api-0.2.3.tar.gz/zomato_distribution_api-0.2.3/zomato_distribution_api/zomato_wrapper.py | zomato_wrapper.py |
MIT License
Copyright (c) [2017] [Ujjwal Gupta]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. | zomato-sdk | /zomato-sdk-0.1.0.tar.gz/zomato-sdk-0.1.0/LICENSE.rst | LICENSE.rst |
from zomato.modules.Fundamentals.base_fundamental import BaseFundamental
from collections.abc import Sequence
from zomato.modules.Fundamentals.collections import Collections
from zomato.modules.Fundamentals.cuisines import Cuisines
from zomato.modules.Fundamentals.establishments import Establishments
class Cities(BaseFundamental, Sequence):
def __len__(self):
return len(self.location_suggestions)
def __getitem__(self, index):
return self.location_suggestions[index]
def __init__(self, data, headers, request):
super().__init__(data, headers, request)
self.location_suggestions = []
self.process_location_suggestions(data['location_suggestions'])
self.status = data['status']
self.has_more = data['has_more']
self.has_total = data['has_total']
def process_location_suggestions(self, location_suggestions):
for location_suggestion in location_suggestions:
self.location_suggestions.append(LocationSuggestion(location_suggestion, self.r))
class LocationSuggestion:
def __init__(self, location_suggestion, request):
self.r = request
self.id = location_suggestion['id']
self.name = location_suggestion['name']
self.country_id = location_suggestion['country_id']
self.country_name = location_suggestion['country_name']
self.should_experiment_with = location_suggestion['should_experiment_with']
self.discovery_enabled = location_suggestion['discovery_enabled']
self.has_new_ad_format = location_suggestion['has_new_ad_format']
self.is_state = location_suggestion['is_state']
self.state_id = location_suggestion['state_id']
self.state_name = location_suggestion['state_name']
self.state_code = location_suggestion['state_code']
def get_collections(self):
data, headers = self.r.request('collections', payload={'city_id': self.id})
return Collections(data, headers, self.r)
def get_cuisines(self):
data, headers = self.r.request('cuisines', payload={'city_id': self.id})
return Cuisines(data, headers, self.r)
def get_establishments(self):
data, headers = self.r.request('establishments', payload={'city_id': self.id})
return Establishments(data, headers, self.r) | zomato-sdk | /zomato-sdk-0.1.0.tar.gz/zomato-sdk-0.1.0/zomato/modules/Fundamentals/cities.py | cities.py |
from zomato.modules.Fundamentals.base_fundamental import BaseFundamental
from collections.abc import Sequence
from zomato.modules.Fundamentals.location_suggestion import LocationSuggestion
from zomato.modules.Fundamentals.daily_menu import DailyMenu
from zomato.modules.Fundamentals.reviews import Reviews
class LocationDetails(BaseFundamental, Sequence):
def __len__(self):
return len(self.best_rated_restaurant)
def __getitem__(self, index):
return self.best_rated_restaurant[index]
def __init__(self, data, headers, request):
super().__init__(data, headers, request)
self.best_rated_restaurant = []
self.popularity = data['popularity']
self.nightlife_index = data['nightlife_index']
self.nearby_res = data['nearby_res']
self.top_cuisines = data['top_cuisines']
self.popularity_res = data['popularity_res']
self.nightlife_res = data['nightlife_res']
self.subzone = data['subzone']
self.subzone_id = data['subzone_id']
self.city = data['city']
self.location = LocationSuggestion(data['location'], self.r)
self.num_restaurant = data['num_restaurant']
self.process_best_rated_restaurant(data['best_rated_restaurant'])
def process_best_rated_restaurant(self, best_rated_restaurant):
for restaurant in best_rated_restaurant:
self.best_rated_restaurant.append(BestRatedRestaurant(restaurant['restaurant'], self.r))
class UserRating:
def __init__(self, rating, request):
self.r = request
self.aggregate_rating = rating['aggregate_rating']
self.rating_text = rating['rating_text']
self.rating_color = rating['rating_color']
self.votes = rating['votes']
class Location:
def __init__(self, location, request):
self.r = request
self.address = location['address']
self.locality = location['locality']
self.city = location['city']
self.city_id = location['city_id']
self.latitude = location['latitude']
self.longitude = location['longitude']
self.zipcode = location['zipcode']
self.country_id = location['country_id']
self.locality_verbose = location['locality_verbose']
class BestRatedRestaurant:
def __init__(self, restaurant, request):
self.r = request
self.apikey = restaurant['apikey']
self.id = restaurant['id']
self.name = restaurant['name']
self.url = restaurant['url']
self.location = Location(restaurant['location'], self.r)
self.switch_to_order_menu = restaurant['switch_to_order_menu']
self.cuisines = restaurant['cuisines']
self.average_cost_for_two = restaurant['average_cost_for_two']
self.price_range = restaurant['price_range']
self.currency = restaurant['currency']
self.offers = restaurant['offers']
self.thumb = restaurant['thumb']
self.user_rating = UserRating(restaurant['user_rating'], self.r)
self.photos_url = restaurant['photos_url']
self.menu_url = restaurant['menu_url']
self.featured_image = restaurant['featured_image']
self.has_online_delivery = restaurant['has_online_delivery']
self.is_delivering_now = restaurant['is_delivering_now']
self.deeplink = restaurant['deeplink']
self.has_table_booking = restaurant['has_table_booking']
self.events_url = restaurant['events_url']
self.r = request
def get_daily_menu(self):
data, headers = self.r.request('daily_menu', payload={'res_id': self.id})
return DailyMenu(data, headers, self.r)
def get_reviews(self):
data, headers = self.r.request('reviews', payload={'res_id': self.id})
return Reviews(data, headers, self.r) | zomato-sdk | /zomato-sdk-0.1.0.tar.gz/zomato-sdk-0.1.0/zomato/modules/Fundamentals/location_details.py | location_details.py |
from PyQt5.QtGui import QIcon, QGuiApplication
from PyQt5.QtCore import pyqtSignal as Signal, QObject, Qt, QCoreApplication, QTranslator, QEvent, QLocale
from PyQt5.QtWidgets import QApplication, QMessageBox, QMainWindow, QWidget, QCheckBox, QDialog, QHeaderView, QTableWidgetItem, QStatusBar, QGraphicsOpacityEffect, QLabel, QActionGroup, QAction
from PyQt5.QtWinExtras import QWinTaskbarButton
from qt_material import build_stylesheet, QtStyleTools
from bidict import bidict
from dataclasses import dataclass
from enum import Enum, unique
from typing import List
import os
import sys
import time
import threading
import seedFinder
import asmInject
import webbrowser
import copy
import pyperclip
cwd = os.path.dirname(os.path.abspath(__file__))
sys.path.append(cwd)
from gui.introduction import Ui_introductionWindow
from gui.main import Ui_mainWindow
from gui.mode1 import Ui_mode1Window
from gui.mode2 import Ui_mode2Window
from gui.msg import Ui_msgWindow
from gui.modify import Ui_modifyWindow
from config import Config
_translate = QCoreApplication.translate
def apply_stylesheet(
app,
theme='',
style=None,
save_as=None,
invert_secondary=False,
extra={},
parent='theme',
):
if style:
try:
try:
app.setStyle(style)
except: # snake_case, true_property
app.style = style
except:
#logging.error(f"The style '{style}' does not exist.")
pass
if extra.get("QMenu") != True and "QMenu" in extra:
for k in extra['QMenu']:
extra[f'qmenu_{k}'] = extra['QMenu'][k]
extra['QMenu'] = True
stylesheet = build_stylesheet(theme, invert_secondary, extra, parent, os.path.join(cwd, "pack_resources/qt_material/material.css.template"))
if stylesheet is None:
return
if save_as:
with open(save_as, 'w') as file:
file.writelines(stylesheet)
try:
app.setStyleSheet(stylesheet)
except:
app.style_sheet = stylesheet
class introductionWindow(QMainWindow, Ui_introductionWindow, QtStyleTools):
def __init__(self, config, parent=None):
super(introductionWindow, self).__init__(parent)
self.configManager = config
self.setupUi(self)
self.setWindowIcon(QIcon(os.path.join(cwd, "pack_resources/icon.ico")))
def apply_stylesheet(
self, parent, theme, invert_secondary=False, extra={}, callable_=None
):
if theme == 'default':
try:
parent.setStyleSheet('')
except:
parent.style_sheet = ''
return
apply_stylesheet(
parent,
theme=theme,
invert_secondary=invert_secondary,
extra=extra,
)
if callable_:
callable_()
def update_theme_event(self, parent):
density = [
action.text()
for action in self.menu_density_.actions()
if action.isChecked()
][0]
theme = [
action.text()
for action in self.menu_theme_.actions()
if action.isChecked()
][0]
if theme == "default":
theme = self.configManager.config["defaultTheme"]
else:
self.configManager.config["defaultTheme"] = theme
self.configManager.config["defaultDensity"] = density
self.configManager.config["extra"]["density_scale"] = density
self.configManager.updateConfig(self.configManager.config)
self.extra_values['density_scale'] = density
self.apply_stylesheet(
parent,
theme=theme,
invert_secondary=theme.startswith('light'),
extra=self.extra_values,
callable_=self.update_buttons,
)
def add_menu_density(self, parent, menu):
self.menu_density_ = menu
action_group = QActionGroup(menu)
action_group.setExclusive(True)
for density in map(str, range(-3, 4)):
action = QAction(parent)
action.triggered.connect(lambda: self.update_theme_event(parent))
action.setText(density)
action.setCheckable(True)
action.setChecked(density == self.configManager.config["defaultDensity"])
action.setActionGroup(action_group)
menu.addAction(action)
action_group.addAction(action)
def changeEvent(self, event):
if event.type() == QEvent.LanguageChange:
self.retranslateUi(self)
class mode1Window(QWidget, Ui_mode1Window):
def __init__(self, config, parent=None):
super(mode1Window, self).__init__(parent)
self.configManager = config
self.setupUi(self)
self.setWindowIcon(QIcon(os.path.join(cwd, "pack_resources/icon.ico")))
self.setAttribute(Qt.WA_DeleteOnClose)
class mode2Window(QWidget, Ui_mode2Window):
def __init__(self, config, parent=None):
super(mode2Window, self).__init__(parent)
self.configManager = config
self.setupUi(self)
self.setWindowIcon(QIcon(os.path.join(cwd, "pack_resources/icon.ico")))
self.setAttribute(Qt.WA_DeleteOnClose)
self.waveTable.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
self.waveTable.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
self.waveTable.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
class msgWindow(QDialog, Ui_msgWindow):
def __init__(self, config, parent=None):
super(msgWindow, self).__init__(parent)
self.configManager = config
self.setupUi(self)
self.setWindowIcon(QIcon(os.path.join(cwd, "pack_resources/icon.ico")))
self.setAttribute(Qt.WA_DeleteOnClose)
self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowMinimizeButtonHint)
class modifyWindow(QWidget, Ui_modifyWindow):
def __init__(self, config, parent=None):
super(modifyWindow, self).__init__(parent)
self.configManager = config
self.setupUi(self)
self.setWindowIcon(QIcon(os.path.join(cwd, "pack_resources/icon.ico")))
self.setAttribute(Qt.WA_DeleteOnClose)
self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint)
self.statusBar = QStatusBar()
self.statusLabel = QLabel()
self.statusBar.addWidget(self.statusLabel, 1)
self.statusBar.setSizeGripEnabled(False)
opacityEffect = QGraphicsOpacityEffect()
self.statusBar.setGraphicsEffect(opacityEffect)
opacityEffect.setOpacity(0.7)
self.layout().addWidget(self.statusBar)
self.getInitSeed()
def getInitSeed(self):
self.injecter = asmInject.seedInject()
self.seed_Input.setValue(self.injecter.getRandomSeed())
self.compareResult(self.injecter.findResult)
def compareResult(self, res):
if res == self.injecter.OK:
color = self.configManager.config["alertColor"]["ok"]
info = _translate("calculator", "Successfully found game.")
self.statusLabel.setText(f"<font color=\"{color}\" style=\"font-style: italic;\">{info}</font>")
return True
elif res == self.injecter.WrongVersion:
color = self.configManager.config["alertColor"]["warning"]
info = _translate("calculator", "No support versions.")
self.statusLabel.setText(f"<font color=\"{color}\" style=\"font-style: italic;\">{info}</font>")
return False
elif res == self.injecter.NotFound:
color = self.configManager.config["alertColor"]["error"]
info = _translate("calculator", "Game not found.")
self.statusLabel.setText(f"<font color=\"{color}\" style=\"font-style: italic;\">{info}</font>")
return False
elif res == self.injecter.OpenError:
color = self.configManager.config["alertColor"]["error"]
info = _translate("calculator", "Process open error")
self.statusLabel.setText(f"<font color=\"{color}\" style=\"font-style: italic;\">{info}</font>")
return False
class mainWindow(Ui_mainWindow):
def __init__(self):
super(mainWindow, self).__init__()
self.setWindowIcon(QIcon(os.path.join(cwd, "pack_resources/icon.ico")))
class calculator:
class signalStore(QObject):
msgUpdate = Signal(str)
titleUpdate = Signal(str)
processUpdate = Signal(int)
alert = Signal()
@dataclass
class waveRequire:
level_beginning : int
level_ending : int
idNeeded : List[int]
idRefused : List[int]
@unique
class taskBarUpdateSignal(Enum):
init = -1
stop = -2
#工具方法&初始化
def __init__(self):
self.configManager = Config()
self.configManager.updateConfig(self.configManager.readConfig())
self.logInterval = self.configManager.config["logInterval"]
QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
QGuiApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
self.app = QApplication(sys.argv)
apply_stylesheet(self.app, self.configManager.config["defaultTheme"], invert_secondary="light_" in self.configManager.config["defaultTheme"], extra=copy.deepcopy(self.configManager.config["extra"]))
language = QLocale().language()
self.trans = QTranslator()
if language == QLocale.Chinese:
self.trans.load(os.path.join(cwd, "pack_resources/language/zh_CN.qm"))
self.app.installTranslator(self.trans)
self.store = self.signalStore()
self.store.msgUpdate.connect(self.msgUpdate)
self.store.titleUpdate.connect(self.titleUpdate)
self.store.processUpdate.connect(self.updateTaskBar)
self.store.alert.connect(self.completeAlert)
self.introWindowInit()
def changeLanguage(self):
language = self.introW.sender().text()
if language == "English":
self.app.removeTranslator(self.trans)
elif language == "中文":
self.trans.load(os.path.join(cwd, "pack_resources/language/zh_CN.qm"))
self.app.installTranslator(self.trans)
def start(self):
self.introW.show()
sys.exit(self.app.exec_())
def rBtnGroupClicked(self, sender):
if sender == "mode1":
btn = self.mode1W.sceneGroup.checkedButton()
self.scene = btn.objectName()[:-5]
elif sender == "mode2":
btn = self.mode2W.sceneGroup.checkedButton()
self.scene = btn.objectName()[:-5]
def nCheckBoxClicked(self):
box = self.mode2W.sender()
id = self.typeName[box.text()]
if box.isChecked():
self.idNeeded.add(id)
else:
self.idNeeded.remove(id)
def rCheckBoxClicked(self):
box = self.mode2W.sender()
id = self.typeName[box.text()]
if box.isChecked():
self.idRefused.add(id)
else:
self.idRefused.remove(id)
#开始窗口
def introWindowInit(self):
self.introW = introductionWindow(self.configManager)
self.introW.set_extra(copy.deepcopy(self.configManager.config["extra"]))
self.introW.add_menu_density(self.app, self.introW.menuDensity)
self.introW.add_menu_theme(self.app, self.introW.menuStyle)
self.introW.start_btn.clicked.connect(self.showMainWindow)
self.introW.inject_btn.clicked.connect(self.modifyWindowInit)
self.introW.exit_btn.clicked.connect(self.app.quit)
self.introW.help_btn.clicked.connect(lambda : webbrowser.open(os.path.join(cwd, "pack_resources/help/help.html")))
for action in self.introW.menuLanguage.actions():
action.triggered.connect(self.changeLanguage)
#主窗口
def mainWindowInit(self):
self.mainW = mainWindow()
self.mode2WindowInit()
self.mode1WindowInit()
self.mainW.tabWidget.addTab(self.mode1W, _translate("calculator", "Mode1"))
self.mainW.tabWidget.addTab(self.mode2W, _translate("calculator", "Mode2"))
def showMainWindow(self):
self.mainWindowInit()
self.mainW.show()
def borderCheck(self, parent, flags_beginning, flags_ending):
if not flags_beginning % 2 or flags_ending % 2:
QMessageBox.critical(parent, _translate("calculator", "Error"), _translate("calculator", "startingFlag should be odds, endingFlags should be even."))
return False
if hasattr(self, "scene") == False:
QMessageBox.critical(parent, _translate("calculator", "Error"), _translate("calculator", "Please select scene."))
return False
return True
#模式1
def mode1WindowInit(self):
self.mode1W = mode1Window(self.configManager)
self.mode1W.calc_btn.clicked.connect(self.mode1Calc)
self.mode1W.sceneGroup.buttonClicked.connect(lambda : self.rBtnGroupClicked("mode1"))
self.mode1W.return_btn.clicked.connect(self.mainW.close)
self.mode1W.help_btn.clicked.connect(lambda : webbrowser.open(os.path.join(cwd, "pack_resources/help/help.html")))
additional = bidict({_translate("calculator", "Normal") : 0, _translate("calculator", "Flag") : 1})
self.typeName.update(additional)
def mode1Calc(self):
try:
uid = self.mode1W.uid_Input.value()
mode = self.mode1W.mode_Input.value()
flags_beginning = self.mode1W.startFlag_Input.value()
flags_ending = self.mode1W.endFlag_Input.value()
level_beginning = (flags_beginning - 1) // 2
level_ending = flags_ending // 2
seed = self.mode1W.seed_Input.value()
if not self.borderCheck(self.mode1W, flags_beginning, flags_ending):
return
except:
QMessageBox.critical(self.mode1W, _translate("calculator", "Error"), _translate("calculator", "Unexpected exceptions happened!"))
else:
try:
self.result = ""
for lvl in range(level_beginning, level_ending):
zombies = seedFinder.appear(uid, mode, self.scene, lvl, seed)
self.result += "{} {} {} {}".format(lvl * 2 + 1, _translate("calculator", "to"), lvl * 2 + 2, _translate("calculator", "flags spawn zombies:"))
amount = 0
for i in range(len(zombies)):
if zombies[i]:
amount += 1
self.result += self.typeName.inverse[i] + " "
self.result += "{} {} {}\n\n".format(_translate("calculator", "Total"), amount, _translate("calculator", "zombies"))
self.msgWindowInit()
self.store.msgUpdate.emit(self.result)
self.store.titleUpdate.emit(_translate("calculator", "Calculation completed."))
self.store.alert.emit()
except:
QMessageBox.critical(self.mode1W, _translate("calculator", "Error"), _translate("calculator", "Unexpected exceptions happened!"))
#模式2
def mode2WindowInit(self):
self.mode2W = mode2Window(self.configManager)
self.mode2W.calc_btn.clicked.connect(self.mode2Calc)
self.mode2W.join_btn.clicked.connect(self.joinTable)
self.mode2W.del_btn.clicked.connect(self.delTable)
self.mode2W.return_btn.clicked.connect(self.mainW.close)
self.mode2W.help_btn.clicked.connect(lambda : webbrowser.open(os.path.join(cwd, "pack_resources/help/help.html")))
self.mode2W.sceneGroup.buttonClicked.connect(lambda : self.rBtnGroupClicked("mode2"))
self.typeName = bidict()
for box in self.mode2W.needGroup.findChildren(QCheckBox):
box.stateChanged.connect(self.nCheckBoxClicked)
for box in self.mode2W.refuseGroup.findChildren(QCheckBox):
box.stateChanged.connect(self.rCheckBoxClicked)
for box in self.mode2W.needGroup.findChildren(QCheckBox):
id = int(box.objectName()[8:])
text = box.text()
self.typeName.put(key=text, val=id)
self.windowsTaskbarButton = QWinTaskbarButton()
self.windowsTaskbarButton.setWindow(self.introW.windowHandle())
self.windowsTaskbarProcess = self.windowsTaskbarButton.progress()
self.windowsTaskbarProcess.setRange(0, 10000)
self.idNeeded = set()
self.idRefused = set()
self.wave = []
def mode2Calc(self):
try:
self.calcDone = False
uid = self.mode2W.uid_Input.value()
mode = self.mode2W.mode_Input.value()
seed = self.mode2W.seed_Input.value()
if not self.wave:
QMessageBox.critical(self.mode2W, _translate("calculator", "Error"), _translate("calculator", "At least one requirement."))
return
waveBeginning = sorted([i.level_beginning for i in self.wave])
waveEnding = sorted([i.level_ending for i in self.wave])
for i in range(1, len(waveBeginning)):
if waveBeginning[i] < waveEnding[i - 1]:
QMessageBox.critical(self.mode2W, _translate("calculator", "Error"), _translate("calculator", "Please check the entered sections have overlapping borders."))
return
self.wave.sort(key=lambda x : x.level_ending)
maxWave = self.wave[-1].level_ending - 1
idNeeded = [[] for i in range(maxWave)]
idRefused = [[] for i in range(maxWave)]
for eachWave in self.wave:
for i in range(eachWave.level_beginning - 1, eachWave.level_ending - 1):
idNeeded[i] = eachWave.idNeeded
idRefused[i] = eachWave.idRefused
except:
QMessageBox.critical(self.mode2W, _translate("calculator", "Error"), _translate("calculator", "Unexpected exceptions happened!"))
else:
self.finder = seedFinder.requestToSeed(uid, mode, self.scene, self.wave[0].level_beginning, self.wave[-1].level_ending, seed)
self.thdList = (threading.Thread(target=self.mode2CalcThread, args=(idNeeded, idRefused)),
threading.Thread(target=self.seedLogger))
for thd in self.thdList:
thd.start()
self.msgWindowInit()
def mode2CalcThread(self, idNeeded, idRefused):
self.result = self.finder.calc(idNeeded, idRefused)
self.calcDone = True
def seedLogger(self):
self.store.processUpdate.emit(self.taskBarUpdateSignal.init.value)
while self.calcDone == False and self.finder.seed >= 0:
try:
lastSeed = self.finder.seed
time.sleep(self.logInterval)
remainTime = self.logInterval * (0x7FFFFFFF - self.finder.seed) / (self.finder.seed - lastSeed) / 60
self.store.msgUpdate.emit("{}\n{}{:#x}\n{}{:.2%} {}{:.2f}mins".format(
_translate("calculator", "Calculating... Please wait."), _translate("calculator", "Current seachered seed is "), self.finder.seed, _translate("calculator", "Processing:"),
self.finder.seed / 0x7FFFFFFF, _translate("calculator", "Remainning time:"), remainTime))
self.store.titleUpdate.emit("{}{:.2%}".format(_translate("calculator", "Calculating... Processing:"), self.finder.seed / 0x7FFFFFFF))
self.store.processUpdate.emit(int(self.finder.seed / 0x7FFFFFFF * 10000))
except ZeroDivisionError:
self.store.titleUpdate.emit(_translate("calculator", "Calculation completed."))
self.store.processUpdate.emit(self.taskBarUpdateSignal.stop.value)
if self.finder.seed >= 0:
self.store.msgUpdate.emit("{}{:#x}".format(_translate("calculator", "Found satisfying seed:"), self.result))
self.store.titleUpdate.emit(_translate("calculator", "Calculation completed."))
else:
self.finder.stopThread = True
self.store.msgUpdate.emit(_translate("calculator", "No satisfying seed found."))
self.store.titleUpdate.emit(_translate("calculator", "No satisfying seed found."))
if not self.finder.stopThread:
self.store.alert.emit()
def updateTaskBar(self, process):
if process == self.taskBarUpdateSignal.stop.value:
self.windowsTaskbarProcess.setValue(0)
self.windowsTaskbarProcess.setVisible(False)
elif process == self.taskBarUpdateSignal.init.value:
self.windowsTaskbarProcess.show()
else:
self.windowsTaskbarProcess.setValue(process)
def joinTable(self):
flags_beginning = self.mode2W.startFlag_Input.value()
flags_ending = self.mode2W.endFlag_Input.value()
level_beginning = (flags_beginning - 1) // 2
level_ending = flags_ending // 2
if not self.borderCheck(self.mode2W, flags_beginning, flags_ending):
return
for i in self.idNeeded:
if i in self.idRefused:
QMessageBox.critical(self.mode2W, _translate("calculator", "Error"), _translate("calculator", "Requirements conflicts with exceptions."))
return
if 2 in self.idRefused and 5 in self.idRefused:
QMessageBox.critical(self.mode2W, _translate("calculator", "Error"), _translate("calculator", "Either conehead or newspaper should spawn."))
return
idNeededShow = [self.typeName.inverse[i] for i in self.idNeeded]
idRefusedShow = [self.typeName.inverse[i] for i in self.idRefused]
waveShow = ((flags_beginning, flags_ending), idNeededShow, idRefusedShow)
waveInstance = self.waveRequire(level_beginning, level_ending, list(self.idNeeded), list(self.idRefused))
if self.wave.count(waveInstance):
return
self.wave.append(waveInstance)
row = self.mode2W.waveTable.rowCount()
self.mode2W.waveTable.insertRow(row)
for i in range(len(waveShow)):
item = QTableWidgetItem(str(waveShow[i]))
self.mode2W.waveTable.setItem(row, i, item)
if self.wave:
self.mode2W.uidGroupBox.setEnabled(False)
self.mode2W.sceneGroupBox.setEnabled(False)
def delTable(self):
try:
row = self.mode2W.waveTable.currentRow()
flags_beginning = eval(self.mode2W.waveTable.item(row, 0).text())[0]
flags_ending = eval(self.mode2W.waveTable.item(row, 0).text())[1]
level_beginning = (flags_beginning - 1) // 2
level_ending = flags_ending // 2
idNeeded = eval(self.mode2W.waveTable.item(row, 1).text())
idRefused = eval(self.mode2W.waveTable.item(row, 2).text())
idNeeded = list(map(lambda x : self.typeName[x], idNeeded))
idRefused = list(map(lambda x : self.typeName[x], idRefused))
waveInstance = self.waveRequire(level_beginning, level_ending, idNeeded, idRefused)
self.wave.remove(waveInstance)
if not self.wave:
self.mode2W.uidGroupBox.setEnabled(True)
self.mode2W.sceneGroupBox.setEnabled(True)
self.mode2W.waveTable.removeRow(row)
except AttributeError:
return
#消息展示窗口
def msgUpdate(self, msg):
self.msgW.msgLabal.setText(msg)
def titleUpdate(self, title):
self.msgW.setWindowTitle(title)
def completeAlert(self):
self.app.alert(self.mainW)
self.app.beep()
self.msgW.copy_btn.setEnabled(True)
def msgWindowInit(self):
self.msgW = msgWindow(self.configManager)
self.msgW.return_btn.clicked.connect(self.msgExit)
self.msgW.copy_btn.clicked.connect(self.msgCopy)
self.msgW.show()
def msgExit(self):
if self.mainW.tabWidget.currentIndex():
self.finder.stopThread = True
self.store.processUpdate.emit(self.taskBarUpdateSignal.stop.value)
isExit = False
while isExit == False:
isExit = not(self.thdList[0].is_alive()) and not(self.thdList[1].is_alive())
self.msgW.close()
def msgCopy(self):
if self.mainW.tabWidget.currentIndex():
if self.calcDone and self.finder.seed >= 0:
pyperclip.copy(f"{self.result:x}")
QMessageBox.information(self.mode2W, _translate("calculator", "Successfully"), "{}{:#x}{}".format(_translate("calculator", "Seed: "), self.result, _translate("calculator", " has copied.")))
self.msgExit()
else:
pyperclip.copy(self.result)
QMessageBox.information(self.mode1W, _translate("calculator", "Successfully"), _translate("calculator", "Spawn zombies have copied."))
self.msgExit()
#种子修改窗口
def modifyWindowInit(self):
self.modifyW = modifyWindow(self.configManager)
self.modifyW.getSeed_btn.clicked.connect(lambda : self.modifyW.seed_Input.setValue(self.modifyW.injecter.getRandomSeed()))
self.modifyW.modifySeed_btn.clicked.connect(lambda : self.modifySeed(self.modifyW.seed_Input.value()))
self.modifyW.findGame_btn.clicked.connect(self.reFindGame)
self.modifyW.show()
def reFindGame(self):
self.modifyW.injecter.findGame()
self.modifyW.compareResult(self.modifyW.injecter.findResult)
def modifySeed(self, seed):
if self.modifyW.compareResult(self.modifyW.injecter.findResult):
self.modifyW.injecter.setRandomSeed(seed)
self.modifyW.injecter.internalSpawn()
if __name__ == "__main__":
calculator().start() | zombie-calculator | /zombie_calculator-0.0.4.3-py3-none-any.whl/zombie_calculator/zombie_calculator.py | zombie_calculator.py |
# **出怪计算器** #
----------
## 前言 ##
本计算器是在[@SKOSKX版](https://tieba.baidu.com/p/7713362872)基础上制作的魔改版。相较于原版,有以下特性:
1. **更更更更更高的效率**(高了多少请自行体会)
2. 将原模式1与模式3合并为新模式1,将原模式2与模式4合并为新模式2,原模式5有朝一日不咕的话……(
3. 加了gui(废话
4. 如果觉得该程序不错,不如star一个吧!
## 模式1使用示例 ##
计算1号玩家,PE(存档编号为13)在种子114514下2021-2030旗的出怪:
<img src="mode1.png" title="模式1" />
结果如下:
<img src="mode1Result.png" title="结果" />
## 模式2使用示例
计算节操掉尽的1号玩家PE从第3面旗到第16面旗均出扶梯且不出车丑红的种子:
<img src="mode2_1.png" title="模式2"/>
作出如下设置后依次点击“加入”和“运行计算”,稍等片刻即可得出结果:
<img src="mode2_1Result.png" title="结果" />
另一个例子:
计算节操掉尽的2号玩家PE 3-4F 出丑炸荷叶,5-10F出梯不出车丑,11-12F出车碾盆的种子:
<img src="mode2_2.1.png" title="模式2"/>
输入以上信息后点击“加入”
如法炮制,最终输入完成的示意:
<img src="mode2_2.2.png" title="模式2" style="zoom:85%"/>
运行计算的结果:
<img src="mode2_2Result.png" title="结果"/>
## 关于参数的一些解释
### 用户编号
第几个创建的用户就是几,以本人的游戏举例:
<img src="users.png" title="用户编号"/>
### 存档编号
正常情况下,**DE,NE,PE,FE,RE分别为11,12,13,14,15**
如果使用修改器改变了场景,存档编号以修改前的场景(也是右下角显示的场景)为准
但游戏场景以修改后的场景为准
## 种子如何查看、修改?
1. 在启动窗口点击***修改种子***按钮。窗口启动时会自动查找游戏并获取存档出怪种子,若游戏未启动则会视具体问题在状态栏显示。也可以在游戏启动后点击***查找游戏***与***获取当前种子***手动查找。
2. 如截图所示,当前为种子**0x11**在泳池无尽3-4波下的预览。利用模式一进行检验。
<img src="check.png" title="修改检验"/>
<img src="check_2.png" title="修改检验"/>
现在修改为**0x12**,效果如图。与模式一预测结果相同。
<img src="modify.png" title="修改完成"/>
<img src="modify_2.png" title="修改完成"/>
------
# 开发者文档
### 总述
该程序基于*python3.8&pyqt5*开发,使用*qt_material*作为皮肤。其中cpu密集计算部分(模式2)使用*c++&pybind11*多线程编写充分利用cpu多核资源。该程序较初版程序速度快500~1000倍左右,使得在int32范围内短时间穷举全部种子成为现实。
- seedFinder模块由[@SKOSKX版](https://tieba.baidu.com/p/7713362872)c++重写为多线程程序而来。
- asmInject模块由[@pvztools](https://github.com/lmintlcx/PvZTools)的部分代码改写而来,并且重写为64位。
### seedFinder模块
**该模块必须在python3.8下使用。**在其他版本下使用请自行编译。
- #### 方法
- **`appear(uid:int, mode:int, scene:str, level:int, seed:int)`**用于获取在当前波数下的出怪类型,返回值为list。
- #### 类
- **`requestToSeed(uid:int, mode:int, scene:str, level_beginning:int, level_ending:int, seed:int)`** 用于获取指定条件下的种子。
- ##### 类属性
- **`seed:int`**用于获取当前计算到的种子。**在seed小于0时表示没有找到合适的种子。**
- `stopThread:bool`用于中断计算线程。
- ##### 类方法
- **`calc(idNeeded:list[list], idRefused:list[list]):int`**两个参数均为二维列表,每个元素为每波要求的出怪类型列表(空列表为无要求)。计算时会堵塞线程,为获取实时进度请使用多线程。
### asmInject模块
**该模块必须在python3.8下使用。**在其他版本下使用请自行编译。
- #### 类
- **`seedInject()`**初始化时尝试获取查找一次游戏。
- ##### 类属性
- **`Result`**
- **`NotFound`**没有找到游戏。
- **`WrongVersion`**不支持的游戏版本。
- **`OK`**成功找到游戏。
- **`OpenError`**游戏进程打开错误。
- **`findResult:Result`**在当前状态下的查找游戏状态,Result枚举类型。
- ##### 类方法
- **`getRandomSeed():int`**获取当前游戏存档种子。
- **`setRandomSeed(seed:int)`**设置当前游戏存档种子。
- **`internalSpawn()`**刷新游戏准备时预览。 | zombie-calculator | /zombie_calculator-0.0.4.3-py3-none-any.whl/zombie_calculator/pack_resources/help/help.md | help.md |
# Zombie Dice
This package is based on Zombie Dice - a popular dice-rolling, push-your-luck boardgame by Steve Jackson.
By running a series of simple functions within a Python environment, you can push your luck to get the most BRAAAAIINS!! 🧠 as possible. At the same time you need to avoid shotgun blasts 💥 while pushing your luck whether to pursue survivors 👣
You can also analyse your results by checking out the logs of your rounds and overall game.
- STEP 1: Once initialised, players are required to pick 3 dice from the bucket by running ```pick_dice()```
- STEP 2: After they've picked the dice with specific colours, players are required to roll the dice by running ```roll_dice()```
- STEP 3: Player can pick more dice and re-roll if they choose to - remember footprints are included in the re-pick and re-throw, so keep in mind of the colours
- STEP 4: Player can keep pick and roll untill the 13 dice are exhausted and the round finished or player can end the round when they feel like they've amounted enough points. Run ```end_round()``` to end the round and the next player can continue
The first player to reach a total of 13 points wins the game!

For a formal how-to-play guide, check out the [original website](http://www.sjgames.com/dice/zombiedice/) or [BGG here](https://boardgamegeek.com/boardgame/62871/zombie-dice).
### Initiate in terminal
```
pip install zombie-dice
```
### Play example
```
import zombie_dice
player_one = zombie_dice.Zombiedice(1)
player_one.pick_dice()
You have the following dice to roll:
Yellow
Green
Green
player_one.roll_dice()
Die 1: Yellow Brain
Die 2: Green Footprints
Die 3: Green Brain
You're score this round so far is 2!
You've rolled 1 footprint(s).
Do you wanna pick more dice to re-roll?
Remember, you can only pick three dice including one of the footprints.
player_one.roll_dice()
You have the following dice to roll:
Green
Yellow
Green
The footprints dice from the previous roll is:
Green
player_one.roll_dice()
Die 1: Green Footprints
Die 2: Yellow Footprints
Die 3: Green Shotgun
You're score this round so far is 1!
You've rolled 2 footprint(s).
Do you wanna pick more dice to re-roll?
Remember, you can only pick three dice including one of the footprints.
player_one.roll_dice()
Die 1: Red Shotgun
Die 2: Red Footprints
Die 3: Green Brain
You're score this round so far is 1!
You've rolled 1 footprint(s).
Do you wanna pick more dice to re-roll?
Remember, you can only pick three dice including one of the footprints.
player_one.end_round()
You're total score is: 1
```
Enjoy!
| zombie-dice | /zombie_dice-0.6.tar.gz/zombie_dice-0.6/README.md | README.md |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.