library
The YetiForceClient is a custom library that contains all the functions that are used in the code.
The file that contains them is the client.py file, the other documents contained in the wrapper are external
sources for the library itself.
Here are described all the functions of the client.py file:
def __init__():
This __init__ method initializes an instance of the YetiForceClient class, setting up the necessary
configurations and performing an initial login to the YetiForce API.
Parameters
base_url: The base URL of the YetiForce API endpoint (e.g.,https://example.com/api).api_key: An instance ofApiKeyused for authentication.x_api_key: An additional security key for accessing the API.api_user: An instance ofAuthUserrepresenting the user credentials for login.
Initialization Steps
-
Set Attributes:
self.lastTokenRenewal: Tracks the last token renewal time, initialized to0.self.base_url: Stores the base URL for making API requests.self.api_key: Stores theApiKeyinstance.self.x_api_key: Stores the extra security key.self.user: Stores the user credentials.
-
Set Headers:
HeaderAPI headers are a section of the requests used to transfer metadata about the request and the desired response
The
self.headersdictionary contains:Authorization: The complete authentication string fromapi_key.getCompleteAuth().Content-Type: Ensures JSON data is sent.x-api-key: Adds the additional security key.x-session-infoandx-session-uptime: Metadata for session tracking.
JSONJavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications.
-
Perform Login:
self.login_data = self.database_user_login(): Logs in the user by calling thedatabase_user_login()method, which presumably interacts with the YetiForce API to authenticate.self.token = self.login_data.get("token"): Extracts the API token from the login response for future API requests.self.loggedUser = self.login_data.get("name"): Extracts the logged-in user's name.
-
Log Success Messages:
- Logs a message indicating successful login with the username.
- Logs a message that the
YetiForceClientwas initialized with the providedbase_url.
Purpose
This method serves as the setup for the YetiForceClient, ensuring it is ready to make authenticated API calls to the YetiForce system by:
- Setting required attributes.
- Preparing HTTP headers for secure communication.
- Authenticating with the API and storing necessary tokens and user details.
Example Code Usage
client = YetiForceClient(
base_url="https://api.example.com",
api_key=ApiKey("my-key-id", "my-key-secret"),
x_api_key="secure-x-api-key",
api_user=AuthUser("username", "password")
)
Upon initialization:
- The client authenticates with the YetiForce API.
- Tokens and user details are stored for subsequent API calls.
_requesttoyeti()
This function is designed to make HTTP requests to the YetiForce API. It is a versatile method to interact with the API, supporting various HTTP methods (GET, POST, etc.), with automatic token handling for authentication.
Parameters
method: The HTTP method to be used for the request (e.g.,GET,POST,PUT,DELETE).path: The specific API endpoint path (relative to the base URL).data: The data to be sent in the request body. This is usually required for methods likePOSTorPUT, but may beNonefor methods likeGET.TokenNeeded: A boolean flag indicating whether an API token is required for the request. IfTrue, the function will include the token in the request headers.additional_headers: Any additional headers that the caller wants to include in the request. These will be merged with the default headers.
Initialization steps
-
Construct the Full URL:
- The function constructs the full URL for the request by combining the base URL (
self.base_url) with the specific API endpoint path (path). - The resulting URL will be in the format:
https://<base_url>/webservice/WebserviceStandard/<path>
- The function constructs the full URL for the request by combining the base URL (
-
Headers Setup:
- The
headersdictionary is copied fromself.headers(which was set during initialization) to avoid modifying the original header data. - If the
TokenNeededflag isTrue, it checks if the token needs to be renewed (i.e., if it has been more than 3000 seconds since the last renewal). If so, it calls the_RenewToken()method to refresh the token. - The
x-tokenheader is set to the current API token (self.token), allowing authentication for the request.
- The
-
Additional Headers:
- If any
additional_headersare provided, they are merged into theheadersdictionary, allowing the caller to add custom headers (such as for custom authentication or special configurations).
- If any
-
Logging:
- The function logs the HTTP request being made, including the method and URL, for debugging purposes.
-
Sending the Request:
- The request is sent using
requests.request(), which is a flexible method for sending any type of HTTP request. The method, URL, headers, and body data (if provided) are passed to it.
- The request is sent using
-
Return the Response:
- The response from the API request is returned to the caller. This is typically a
Responseobject from therequestslibrary, which contains details like the status code, headers, and body content of the response.
- The response from the API request is returned to the caller. This is typically a
Purpose
This method is a core function for interacting with the YetiForce API, providing a simple interface for making authenticated API requests with flexible options for headers and request methods.
The _requesttoyeti method simplifies making authenticated requests to the YetiForce API, handling token management and flexible header setup while supporting different HTTP methods and endpoints.
Example Code Usage
client = YetiForceClient(
base_url="https://api.example.com",
api_key=ApiKey("my-key-id", "my-key-secret"),
x_api_key="secure-x-api-key",
api_user=AuthUser("username", "password")
)
# Example GET request
response = client._requesttoyeti(
method="GET",
path="users",
TokenNeeded=True
)
# Example POST request with data
data = {"name": "New User", "email": "user@example.com"}
response = client._requesttoyeti(
method="POST",
path="users",
data=data,
TokenNeeded=True
)
In the example:
- The client sends a
GETrequest to theusersendpoint of the YetiForce API, including the necessary authentication token. - It then sends a
POSTrequest to create a new user with the provided data.
def CreateUsers():
Parameters
The CreateUsers function takes two parameters:
userName: A string representing the username of the new user to be created.password: A string representing the password for the new user.
Initialization Steps
-
Logging:
- The function logs a debug message indicating that a user with the given
userNameis being created. This helps in tracking the process for debugging purposes.
- The function logs a debug message indicating that a user with the given
-
Create User Instance:
- The function creates and returns an instance of the
AuthUserclass, passing theuserNameandpasswordas arguments to the constructor ofAuthUser. This instance represents the newly created user.
- The function creates and returns an instance of the
Purpose
The CreateUsers function is designed to create a new AuthUser instance by taking a userName and password as input parameters. It logs the action for debugging and returns the created user instance, allowing the application to interact with this user object further, for example, to authenticate or store in a database.
Example Code Usage
# Create a new user
new_user = CreateUsers("john_doe", "securepassword123")
# Access the newly created user's attributes
print(new_user.userName) # Output: john_doe
print(new_user.password) # Output: securepassword123
In the example above, the CreateUsers function is called with a username and password to create a new AuthUser instance. The new_user object can then be used to interact with the user data in the application.
def CreateApiKey():
Parameters
The CreateApiKey function takes two parameters:
Name: A string representing the name associated with the API key. This can be a descriptive label used to identify the API key.Password: A string representing the password for the API key. This is used for authentication when using the API key.
Initialization Steps
-
Logging:
- The function logs a debug message indicating that an API key with the given
Nameis being created. This helps with tracking the action for debugging purposes.
- The function logs a debug message indicating that an API key with the given
-
Create ApiKey Instance:
- The function creates and returns an instance of the
ApiKeyclass, passing theNameandPasswordas arguments to its constructor. This instance represents the newly created API key, containing the name and password for authentication.
- The function creates and returns an instance of the
Purpose
The CreateApiKey function is responsible for creating a new ApiKey instance with a provided name and password. It logs the action and returns the created instance, allowing the application to use this API key for subsequent interactions with services that require authentication.
Example Code Usage
# Create a new API key
api_key = CreateApiKey("myApiKey", "securepassword123")
# Access the newly created API key's attributes
print(api_key.Name) # Output: myApiKey
print(api_key.Password) # Output: securepassword123
In this example, the CreateApiKey function is called with a name and password to create a new ApiKey instance. The api_key object can then be used for authentication in API requests.
def database_user_login():
Parameters
The database_user_login function does not take any parameters directly. It uses the self.user attribute, which is presumably set during the initialization of the class that this method belongs to. This self.user attribute contains the user credentials (username and password) that are needed to log in to the YetiForce API.
Initialization Steps
-
Logging:
- The function logs a debug message indicating that it is attempting to log in with the specified
usernamefromself.user.
- The function logs a debug message indicating that it is attempting to log in with the specified
-
Prepare Login Data:
- The
pathvariable is set to"Users/Login", which is the API endpoint used for user authentication. - The
payloadis created by callingself.user.toObject(), which converts theself.userobject into a format suitable for the API request, likely a dictionary with the username and password.
- The
-
Make the API Request:
- The function calls the
_requesttoyetimethod with the following parameters:- HTTP method:
POST - Endpoint path:
"Users/Login" - Data:
payload(user credentials) TokenNeeded:False(indicating that no token is required for the login request)
- HTTP method:
- The
responseobject contains the result of the API request.
- The function calls the
-
Handle Response:
- If the response status code is
200, it indicates a successful login. The function logs the success and returns theresultfrom the response JSON. - If the response status code is
401, it indicates authentication failure. The function logs the error and raises anAuthenticationErrorwith a specific message depending on the error returned by the API (such as "Invalid username or password"). - For any other response code, the function logs a critical error and raises a
YetiForceErrorindicating a connection issue with the YetiForce API.
- If the response status code is
Purpose
The purpose of the database_user_login function is to authenticate a user against the YetiForce API. It sends the user's credentials to the YetiForce login endpoint, handles different response codes (successful login, authentication failure, and connection issues), and raises appropriate exceptions when necessary. This function is a key part of the authentication process, ensuring that only valid users can interact with the API.
Example Code Usage
# Assuming `self.user` is an instance of AuthUser with the credentials
try:
login_data = self.database_user_login()
print("Login successful, token:", login_data["token"])
except AuthenticationError as e:
print("Authentication failed:", e)
except YetiForceError as e:
print("Connection error:", e)
In this example, the database_user_login method is called to log the user in. If the login is successful, the token and other login data are returned and can be used for subsequent API requests. If authentication fails or if there is a connection issue, appropriate exceptions are raised and caught, providing meaningful error messages.
def _CheckTokenExsist():
Parameters
The _CheckTokenExsist function does not take any parameters directly. It uses the self.token attribute. This self.token attribute is expected to contain the authentication token needed for subsequent API requests.
Initialization Steps
-
Logging:
- The function logs an informational message: "Checking if token exists" to track when the token check is happening.
-
Check Token:
- The function checks if the
self.tokenattribute is not set (i.e.,if not self.token). If the token isNone, empty, or evaluates toFalse, it indicates that the token does not exist or is invalid.
- The function checks if the
-
Handle Missing Token:
- If the token is missing, the function logs an error message: "Token not found".
- It then raises a
TokenErrorexception with the message"Token not found", indicating that the authentication token is required but was not found.
Purpose
The _CheckTokenExsist function is used to ensure that an authentication token exists before making further API requests. It performs a simple check to verify whether the self.token is present. If the token is missing, it raises an error, preventing any further actions that require authentication. This is crucial for maintaining secure and valid communication with the API.
Example Code Usage
try:
self._CheckTokenExsist() # Ensure the token exists
# Proceed with API requests that require authentication
except TokenError as e:
print("Token error:", e)
In this example, the function _CheckTokenExsist is called to verify that the authentication token is available. If the token is missing, the function raises a TokenError, which is caught and handled by printing an error message. If the token exists, the program can proceed with subsequent actions that require authentication.
def _getToken():
Parameters
The _getToken function does not take any parameters. It relies on the database_user_login method, which handles user authentication and returns login data, including the authentication token.
Initialization Steps
-
Logging:
- The function logs a warning message: "Retrieving new token" to indicate that a new token is being requested.
-
Call to
database_user_login:- The function calls
self.database_user_login(), which logs the user into the YetiForce API and retrieves the login data (including the token) from the API.
- The function calls
-
Extract Token:
- It then accesses the
tokenkey in the returned login data dictionary (.get("token")) and returns the token as the result of the function.
- It then accesses the
Purpose
The purpose of the _getToken function is to retrieve a new authentication token from the YetiForce API. This is essential for ensuring that the application has a valid token to perform subsequent API requests. The function relies on the database_user_login method for the authentication process and extracts the token from the returned login data.
Example Code Usage
try:
token = self._getToken() # Retrieve a new token
print("New token:", token)
except AuthenticationError as e:
print("Authentication failed:", e)
In this example, the function _getToken is called to retrieve a new token. If successful, the token is printed. If the database_user_login method raises an error (e.g., if authentication fails), the exception is caught and an error message is printed. This ensures that the token retrieval process is handled properly before making further API requests.
Here's a more accurate documentation for the _RenewToken method:
def _RenewToken(self, forcedTOKEN=True, forcedurl=None):
Method Signature
def _RenewToken(self, forcedTOKEN=True, forcedurl=None)
Parameters
forcedTOKEN(bool, optional):- Default is
True - When
True, forces the method to retrieve a new token
- Default is
forcedurl(str, optional):- Default is
None - Allows specifying an alternative URL for token retrieval (if needed)
- Default is
Functionality
The _RenewToken method is designed to ensure a valid authentication token is available for API interactions.
Key Behaviors
-
Token Retrieval:
- When
forcedTOKENisTrue, the method callsself._getToken()to obtain a new token - This guarantees a fresh token is available for API requests
- When
-
Timestamp Tracking:
- Updates
self.lastTokenRenewalwith the current timestamp usingtime.time() - Helps track when the token was last renewed
- Updates
-
Logging:
- Logs an informational message before token renewal
- Logs a warning message after successful token renewal
Example Usage
# Standard token renewal
client._RenewToken() # Uses default parameters
# Force token renewal even if current token seems valid
client._RenewToken(forcedTOKEN=True)
# Potentially override token retrieval URL (uncommon)
client._RenewToken(forcedurl='https://custom-token-endpoint.com')
def get_all_users():
Parameters
The get_all_users function does not take any parameters. It relies on the self.token attribute (checked by the _CheckTokenExsist method) for authentication when making the API request.
Initialization Steps
-
Logging:
- The function logs an informational message: "Retrieving all users" to indicate that it is initiating the process of retrieving user data.
-
Check Token Validity:
- Before making the API request, the function calls
self._CheckTokenExsist(), which verifies that a valid authentication token is available. If no valid token is found, this method raises an error.
- Before making the API request, the function calls
-
Define Request Path:
- The
pathvariable is constructed using theDefaultModules.ShortTermmodule and theRecordsListendpoint, which is used to retrieve the list of users from the YetiForce API.
- The
-
Send API Request:
- The function calls the
_requesttoyetimethod with the following parameters:- HTTP method:
GET - Path: The constructed path for retrieving user data.
- Additional headers:
"x-max-rows": "20000": Specifies the maximum number of rows to return (20,000 in this case).'x-fields': '["sid", "pin", "fullname"]': Defines the fields to be retrieved for each user (in this case,sid,pin, andfullname).
- HTTP method:
- The
_requesttoyetimethod sends the API request and returns the response.
- The function calls the
-
Return Response Data:
- The function returns the JSON data from the response, which contains the list of all users retrieved from the YetiForce API.
Purpose
The get_all_users function is designed to retrieve a list of all users from the YetiForce API. It performs the necessary checks to ensure that the authentication token is valid before making the request. It constructs the API path, sends the request with appropriate headers, and returns the JSON response containing user data. This function is useful for getting a comprehensive list of users and their associated data from the YetiForce system.
Example Code Usage
try:
users_data = self.get_all_users() # Retrieve all users from the YetiForce API
print("All users retrieved successfully:", users_data)
except TokenError as e:
print("Authentication error:", e)
except Exception as e:
print("Error retrieving users:", e)
In this example, the function get_all_users is called to fetch all users from the YetiForce API. The retrieved user data is printed out. If the authentication token is invalid or another error occurs during the request, the corresponding exception is caught and an error message is displayed.
def get_user_by_query():
A query in database management is a request for data.
Parameters
The get_user_by_query function takes two parameters:
sid: The unique identifier for the user (likely a system ID or similar).pin: The personal identification number (PIN) associated with the user.
Both parameters are used to search for a specific user in the YetiForce system by matching the sid and pin values.
Initialization Steps
-
Logging:
- The function logs the
sidandpinparameters to track the query being executed.
- The function logs the
-
Check Token Validity:
- Before proceeding with the request, the function calls
self._CheckTokenExsist(), which checks if a valid authentication token is available. If no valid token is found, an error is raised.
- Before proceeding with the request, the function calls
-
Validate
sidandpin:- The function checks whether the
sidorpinparameters are missing. If either of them is not provided, it logs an error and returns a response indicating that thesidorpinwas not found.
- The function checks whether the
-
Set Request Headers:
- The
headers_to_adddictionary is created, containing:x-condition: A JSON-encoded condition to filter records based onsidandpin. The operator"e"indicates an exact match.x-fields: Specifies which fields to retrieve for the user (in this case:sid,pin,fullname, andassignedgroup).
- The
-
Send API Request:
- The function calls
self._requesttoyetito send aGETrequest to the API with the specified path and additional headers.
- The function calls
-
Handle API Response:
- If the API returns a valid response with user data, the function checks the
numberOfRecordsfield to determine if a user was found. If no records are found, it logs the event and returns an appropriate error message. - If records are found, the first user's details are retrieved, and the function checks if the user’s assigned group is valid for login using
YetiForceClient.getRawAssignedGroupForLogin. - The function also checks if the user’s assigned group is within the acceptable date range using
is_today_in_range. - If the user passes these checks, the function prepares a response with the user's details.
- If the API returns a valid response with user data, the function checks the
-
Error Handling:
- If no user is found, if the user is not in the valid range, or if any errors occur during the API request, the function logs the error and returns a failure response or raises an exception.
Purpose
The purpose of the get_user_by_query function is to retrieve a user’s data from the YetiForce API based on the provided sid and pin. The function performs several checks to ensure the validity of the query, including validating the token, ensuring that the sid and pin are provided, and confirming the user's assigned group and date range. It returns detailed information about the user if found, or an error message if any of the checks fail. This function is useful for fetching specific user data securely and reliably.
Example Code Usage
# Example: Retrieving a user by SID and PIN
sid = "12345"
pin = "67890"
try:
user_info = self.get_user_by_query(sid, pin) # Retrieve user information by SID and PIN
if user_info["code"] == "200":
print("User found:", user_info["data"])
else:
print("Error:", user_info["data"]) # Error message (e.g., user not found or invalid range)
except APIError as e:
print("Error calling the API:", e)
In this example, the function get_user_by_query is called with a specific sid and pin. If a user is found, their information is printed. If no user is found, or if any error occurs (e.g., invalid token or date range), an appropriate error message is displayed. The APIError exception is raised if there is an issue with the API call itself.
def try_login():
Parameters
The try_login function takes two parameters:
sid: The unique identifier for the user (likely a system ID or similar).pin: The personal identification number (PIN) associated with the user.
These parameters are passed to the get_user_by_query function to search for the user in the system.
Initialization Steps
-
Call
get_user_by_query:- The function calls
get_user_by_query(sid, pin)to check if a user with the givensidandpinexists in the system.
- The function calls
-
Evaluate Query Response:
- The function checks the response (
qury) fromget_user_by_query. Specifically, it looks at the"code"field to determine if the user was found.
- The function checks the response (
-
Return Appropriate Response:
- If the
"code"returned fromget_user_by_queryis"200", indicating that the user exists, it returns a dictionary with:code:200to indicate a successful login.data: A success message ("User exists").
- If the
"code"is anything other than"200", it returns a dictionary with:code: The code returned fromget_user_by_query(indicating an error or failure).data: The error message returned fromget_user_by_query.
- If the
Purpose
The purpose of the try_login function is to attempt to log a user in by validating the provided sid and pin. It leverages the get_user_by_query function to check the user's credentials, and based on the result, it returns a response indicating whether the user exists or if there was an error (e.g., user not found, invalid credentials). This function serves as a higher-level utility for logging in users and handling login-related errors.
Example Code Usage
# Example: Attempting to log in a user with SID and PIN
sid = "12345"
pin = "67890"
login_result = self.try_login(sid, pin)
if login_result["code"] == 200:
print("Login successful:", login_result["data"])
else:
print("Login failed:", login_result["data"])
In this example, the try_login function is called with a specific sid and pin. If the login is successful (i.e., the user exists), it prints a success message. If the login fails (e.g., user not found or invalid credentials), it prints an error message based on the response data.
def get_related_fields():
Parameters:
- sid: A session ID used to identify the current user or session.
- pin: A personal identification number (PIN) associated with the user.
- moduleName: The name of the module from which related fields are being fetched.
- relatedModuleName: The name of the related module that contains the relevant data.
- additional_headers (optional): Additional headers to be included in the request, useful for authentication or passing extra information.
Initialization Steps:
-
Initialize a
returnerdictionary: This dictionary is used to store the function’s output. It starts with a code "1" (indicating some failure) and data set to "null". -
Get user record: The function calls
get_user_by_query(sid, pin)to fetch user details. If the status code is not "200", the function returns the error code and message from therecord. -
Check for a valid record ID: The function checks if the
recordIdis present in the response. If not, it logs an error and returns an error code "401" with the message "Record ID not found". -
Construct URL for related records: The path is dynamically generated to retrieve the related fields, using the provided
moduleName,relatedModuleName, and therecordId. -
Make an API request: The function sends a
GETrequest to the generated path with any additional headers. -
Process the response: If the response contains related records, they are returned; otherwise, an error is logged indicating no related fields were found.
Purpose:
This function is designed to fetch related fields of a record from a specific module in a database or API, given a user's session ID and personal PIN. It handles errors such as missing user records or related fields and provides structured feedback through the returner dictionary. It is useful in systems where users need to retrieve related data from different modules based on a specific record.
Example Code Usage:
# Initialize parameters
sid = "user_session_123"
pin = "user_pin_123"
moduleName = "Users"
relatedModuleName = "Contacts"
additional_headers = {"Authorization": "Bearer token123"}
# Call the function to get related fields
result = self.get_related_fields(sid, pin, moduleName, relatedModuleName, additional_headers)
# Check the returned result
if result["code"] == "200":
print("Related fields retrieved successfully:")
print(result["data"])
else:
print(f"Error: {result['data']}")
In this example, the function attempts to retrieve related contact information for a user in the "Users" module. If successful, it prints the related records; if not, it shows an error message.
def _create_entry():
Parameters:
- module: The name of the module where the new entry will be created (e.g., "Users," "Products").
- data: A dictionary containing the information that needs to be created in the module.
- additional_headers (optional): Extra headers to be included in the request, such as for authentication or content type specification.
Initialization Steps:
-
Log the module name: The function logs an informational message to indicate that a new entry is being created in the specified module.
-
Check Token Existence: The function calls
_CheckTokenExsist()to ensure that the necessary authentication token is available for the request. This step likely handles token validation or renewal. -
Construct URL for request: The URL path is dynamically generated using the provided
modulename, specifically targeting theRecordendpoint for creating new entries. -
Make POST request: A
POSTrequest is made to the generated path with the provideddata, optionaladditional_headers, and a flag indicating that a token is needed for the request.
Purpose:
This function is used to create a new record in a specified module. It sends a POST request to an API endpoint designed for creating records, with the provided data. It handles authentication and sends the data as part of the request. The function returns the JSON response containing the details of the newly created entry, which might include success or error messages depending on the outcome.
Example Code Usage:
# Initialize parameters
module = "Users"
data = {
"name": "John Doe",
"email": "john.doe@example.com",
"age": 30
}
additional_headers = {"Authorization": "Bearer token123"}
# Call the function to create a new user entry
response = self._create_entry(module, data, additional_headers)
# Check the returned response
if response.get("status") == "success":
print("User created successfully:", response["data"])
else:
print(f"Error creating user: {response.get('message')}")
In this example, the function attempts to create a new user in the "Users" module with the provided data. The result is checked for success, and the newly created user's information is printed if successful, or an error message is shown otherwise.
def _edit_entry():
Parameters:
- module: This specifies the module where the entry is located, which is a string representing the name of the module (e.g., "users", "products").
- data: This is the data to be updated for the specified entry. It could be a dictionary containing the new values for the entry fields.
- record_id: This is the unique identifier (ID) of the entry to be edited. It helps locate the specific record in the module.
- additional_headers: This is an optional parameter that allows adding extra headers to the HTTP request. It defaults to
Noneif no extra headers are needed.
Initialization Steps:
- Logging: The function logs an info message to indicate that an entry in the given module is being edited.
- Token Check: The function calls
self._CheckTokenExsist()to ensure a valid token exists before proceeding with the request. - Path Setup: The URL path for the API request is constructed using the
moduleandrecord_idto target the correct record. - HTTP Request: The function sends an HTTP
PUTrequest to the API endpoint using the constructed path and provided data. It also includes any additional headers if provided.
Purpose:
This function is used to edit or update an existing entry in a specified module. It performs the update by making an API request with the given data and record ID. The purpose is to allow modifications to a record within the specified module on the server, typically as part of a web service or API interaction.
Example Code Usage:
module = "users"
data = {
"name": "John Doe",
"email": "johndoe@example.com"
}
record_id = 12345
additional_headers = {"Authorization": "Bearer some-token"}
response = api_instance._edit_entry(module, data, record_id, additional_headers)
print(response) # This will print the JSON response containing the edited entry.
In this example, the function is used to update the user's name and email in the "users" module, targeting the record with ID 12345. It sends the updated data along with an authorization token in the headers.
def getRawFamily():
Parameters:
- response: This parameter is expected to be a dictionary containing the response data, typically from an API or web service. The function specifically looks for a key named
'data'in the dictionary, which should contain family-related information.
Initialization Steps:
- Logging: The function logs a debug message to indicate the process of retrieving the raw family from the given
response. - Date Setup: The function gets the current date formatted as
DD/MM/YYYYusingdatetime.now().strftime('%d/%m/%Y')and stores it in thetodayvariable. - Variable Initialization: It initializes
raw_familytoNone, which will be updated if the correct family is found. - Try-Except Block: The function is wrapped in a
try-exceptblock to handle potential errors (such as missing or malformed data) gracefully.
Purpose:
The function is designed to extract the "raw" family data from the response dictionary, specifically looking for a family that is available based on the current date. It checks whether the available date range (from 'available_from' to 'available_to') encompasses the current date, and if so, it retrieves the "raw" family information within the 'host_family' key. The function returns this "raw" family data or None if no such data is found or an error occurs.
Example Code Usage:
response = {
'data': {
'family_1': {
'available_from': '01/12/2024',
'available_to': '15/12/2024',
'host_family': {'raw': 'Family_A'}
},
'family_2': {
'available_from': '20/12/2024',
'available_to': '25/12/2024',
'host_family': {'raw': 'Family_B'}
}
}
}
raw_family = getRawFamily(response)
print(raw_family) # This would print 'Family_A' if the current date is between 01/12/2024 and 15/12/2024.
In this example, the function checks the availability of families in the response, and since family_1 is available during the current date, it returns 'Family_A'.
def getRawAssignedGroup():
Parameters
- response (dict): The function takes a dictionary
responseas input. It expects the dictionary to contain a key'data'and within that, another key'assignedgroup'. The function will look for the'raw'key inside'assignedgroup'to return its value.
Initialization Steps
- assigned_group_raw (None): The function initializes a variable
assigned_group_rawtoNone. This will hold the value of the'raw'key if it exists in the response, or remainNoneif not found.
Purpose
The purpose of the function is to check if the provided response contains the necessary nested keys ('data', 'assignedgroup', and 'raw'). If these keys are present, it returns the value of raw inside 'assignedgroup'. If any of these keys are missing, it will return None.
Example Code Usage
response = {
'data': {
'assignedgroup': {
'raw': 'group_data_value'
}
}
}
# Call the function with the response dictionary
result = getRawAssignedGroup(response)
print(result) # Output: 'group_data_value'
In this example, the function successfully retrieves the value 'group_data_value' from the raw key inside the 'assignedgroup' object within the data field.
Another Example (Missing Data)
response = {
'data': {
'assignedgroup': {}
}
}
result = getRawAssignedGroup(response)
print(result) # Output: None
In this case, the 'raw' key is missing, so the function will return None.
def getRawAssignedGroupForLogin():
Parameters
- response (dict): The function accepts a dictionary
response, which is expected to contain several nested keys. Specifically, the function looks for the'result'key, which should contain a dictionary with a'records'key. Each record within'records'should have an'assignedgroup'key, from which it extracts the'raw'value.
Initialization Steps
- first_record (dict): The function attempts to retrieve the first record in the
response['result']['records']dictionary usingnext(iter(response['result']['records'].values())). This gets the first item in the'records'dictionary, assuming it's not empty. - assigned_group_raw (None): The function initializes
assigned_group_rawtoNone. This will hold the'raw'value from the'assignedgroup'field if it exists, or remainNoneif any error occurs (e.g., missing keys or invalid data types).
Purpose
The purpose of this function is to extract the 'raw' value from the 'assignedgroup' key for the first record in the response data. The function ensures that even if the 'assignedgroup' or its 'raw' key is missing, or if the response structure is not as expected, it gracefully handles the situation by returning None. This makes the function resilient to variations in the input structure.
Example Code Usage
response = {
'status': 1,
'result': {
'headers': {
'sid': 'SID',
'pin': 'PIN',
'fullname': 'Full Name',
'assignedgroup': 'Assigned Group'
},
'records': {
'81463': {
'recordLabel': 'Michele Parenti',
'sid': '200000',
'pin': '0000',
'fullname': 'Michele Parenti',
'assignedgroup': {
'value': 'Cumacini',
'raw': 78839,
'referenceModule': 'ClosedGroups',
'state': 'Active',
'isPermitted': True
}
}
},
'permissions': {
'81463': {
'isEditable': True,
'moveToTrash': True
}
},
'numberOfRecords': 1,
'isMorePages': False
}
}
# Call the function with the response dictionary
result = getRawAssignedGroupForLogin(response)
print(result) # Output: 78839
In this example, the function successfully retrieves the value 78839 from the 'raw' key inside the 'assignedgroup' field for the first record in 'records'.
Another Example (Missing Data)
response = {
'status': 1,
'result': {
'records': {}
}
}
result = getRawAssignedGroupForLogin(response)
print(result) # Output: None
In this case, the 'records' dictionary is empty, so the function will return None as there is no 'assignedgroup' field to extract the 'raw' value from.
def create_feedback_family():
Parameters
- sid (str): The SID (Student ID or unique identifier) of the user for whom the feedback is being created.
- pin (str): The PIN associated with the user for authentication and lookup.
- feedbackBody (str): The main feedback content that the user is submitting.
- additional_headers (dict, optional): Any additional headers that should be included in the request when creating the feedback. This is an optional parameter.
- genralScore (int, optional): The general score for the feedback, if applicable. This is an optional parameter.
- foodScore (int, optional): The food-related score for the feedback, if applicable. This is an optional parameter.
- cleaningScore (int, optional): The cleaning-related score for the feedback, if applicable. This is an optional parameter.
- content (str, optional): Any extra content or remarks related to the feedback. This is an optional parameter.
Initialization Steps
- record (dict): The function first retrieves the user record using
self.get_user_by_query(sid, pin), which returns the user's details based on the providedsidandpin. - recordid (str): The
recordidis extracted from the user record. If norecordidis found, an error is logged, and the function returns a failure response. - family (dict): The function retrieves the related family fields using
self.get_related_fields(sid, pin, DefaultModules.ShortTerm, DefaultModules.Hostfamilies), which pulls in the family data associated with the user. - raw_fam_id (str): The raw family ID is obtained from the
YetiForceClient.getRawFamily(family)function. If the family ID is missing, an error is logged, and the function returns a failure response. - raw_assigned_group (str): The raw assigned group for the user is fetched from
YetiForceClient.getRawAssignedGroup(record). Similarly, if the assigned group is missing, an error is logged, and the function returns a failure response.
Purpose
The purpose of this function is to create a new feedback entry or update an existing one for a user in the host family feedback module. It ensures that necessary information, such as the user record, family ID, and assigned group, are valid before creating the feedback. Additionally, it supports scoring (general, food, cleaning) and allows extra content or headers to be added. Based on whether the user already has feedback, the function either creates a new feedback entry or edits an existing one.
Example Code Usage
# Example feedback creation
sid = "200000"
pin = "0000"
feedbackBody = "The family was very welcoming and supportive."
genralScore = 8
foodScore = 7
cleaningScore = 9
content = "The food was good, but could use more variety."
response = create_feedback_family(sid, pin, feedbackBody, genralScore=genralScore, foodScore=foodScore, cleaningScore=cleaningScore, content=content)
print(response)
Another Example (No Scores)
# Example feedback creation without scores
sid = "200001"
pin = "1234"
feedbackBody = "The family was friendly and the experience was great."
response = create_feedback_family(sid, pin, feedbackBody)
print(response)
In this example, the feedback is created without scores for food, general, or cleaning, and only the text of the feedback is provided.
Key Functional Flow:
- Record Retrieval: It first retrieves the user record using the
sidandpin. - Family and Group Validation: It checks if both the family ID and the assigned group are present.
- Feedback Construction: It constructs the feedback dictionary, including optional score parameters if provided.
- Feedback Creation or Edit: It checks if feedback already exists for the user. If it does, the feedback is edited; otherwise, a new entry is created.
Return Value
- The function returns a JSON response containing the newly created or edited feedback entry. This could include success or failure data, depending on the outcome.
def create_job_placement_feedback():
Parameters
- sid (str): The SID (Student ID or unique identifier) of the user submitting the feedback.
- pin (str): The PIN associated with the user for authentication and data retrieval.
- feedbackBody (str): The main content of the feedback provided by the user about their job placement experience.
- overallResult (str, optional): The overall result of the job placement (e.g., positive, negative). This is an optional parameter.
- typeOftasks (str, optional): Describes the type of tasks the user was involved with during their job placement. This is an optional parameter.
- haveYouLearned (str, optional): Indicates whether the user has learned something new during the placement. This is an optional parameter.
- expirianceSatis (str, optional): The user's satisfaction level with the overall experience. This is an optional parameter.
- overallExperience (str, optional): A description of the user's overall experience during the job placement. This is an optional parameter.
- comments (str, optional): Any additional comments the user wants to add about their job placement. This is an optional parameter.
- whynottell (str, optional): A reason provided by the user if they are withholding feedback or certain details. This is an optional parameter.
- additional_headers (dict, optional): Additional headers to be included with the feedback request. This is an optional parameter.
- problemsawareness (str, optional): Describes the user's awareness of any problems or challenges faced during the job placement. This is an optional parameter.
Initialization Steps
- record (dict): The function starts by retrieving the user record using
self.get_user_by_query(sid, pin), which returns the user's details, including theirrecordId. - raw_assigned_group (str): The function retrieves the raw assigned group ID using
YetiForceClient.getRawAssignedGroup(record), which helps in identifying the user's group. - raw_job_placement_id (str): It fetches the job placement ID using
YetiForceClient.getCompanyrawidFromInternPlace(job_placement), which is based on the user's job placement record. - Validation: The function checks for the presence of the
recordId,raw_assigned_group, andraw_job_placement_id. If any of these are missing, it logs an error and returns a failure response with the appropriate error message.
Purpose
The purpose of this function is to facilitate the creation or updating of a job placement feedback entry. It collects various pieces of feedback from the user, such as overall satisfaction, tasks performed, learning outcomes, and comments. It ensures that all necessary information, like the user's record ID, assigned group, and job placement ID, is valid before proceeding with creating the feedback. The function also supports both creating new feedback entries and editing existing ones, depending on whether the user has already submitted feedback for the job placement.
Example Code Usage
# Example job placement feedback creation
sid = "200000"
pin = "0000"
feedbackBody = "The job placement was challenging but very rewarding."
overallResult = "Positive"
typeOftasks = "Software development"
haveYouLearned = "Yes, I learned new programming skills."
expirianceSatis = "Very satisfied"
overallExperience = "Great learning experience with hands-on projects."
comments = "Would love to work with this company again."
whynottell = "N/A"
additional_headers = {"Authorization": "Bearer token"}
problemsawareness = "None"
response = create_job_placement_feedback(sid, pin, feedbackBody, overallResult=overallResult, typeOftasks=typeOftasks,
haveYouLearned=haveYouLearned, expirianceSatis=expirianceSatis,
overallExperience=overallExperience, comments=comments, whynottell=whynottell,
additional_headers=additional_headers, problemsawareness=problemsawareness)
print(response)
Another Example (Without Optional Parameters)
# Example job placement feedback creation with only required parameters
sid = "200001"
pin = "1234"
feedbackBody = "The placement was good, and I gained valuable experience."
response = create_job_placement_feedback(sid, pin, feedbackBody)
print(response)
In this case, the function creates a job placement feedback entry with just the required parameters, without including optional ones like comments, typeOftasks, or problemsawareness.
Key Functional Flow:
- User and Job Placement Validation: It retrieves the user record and validates the presence of necessary fields, including the
recordId,assigned group, andjob placement ID. - Feedback Construction: The function constructs a feedback dictionary containing all the feedback-related fields, including any optional parameters if provided.
- Feedback Creation or Edit: It checks if the user has already submitted feedback for the job placement. If so, it edits the existing feedback; otherwise, it creates a new feedback entry.
- API Interaction: The function interacts with the backend API to create or edit the feedback entry and logs the response.
Return Value
- The function returns a JSON response containing either the newly created or edited job placement feedback entry. This response includes success or failure data, depending on the outcome of the creation or edit operation.
def create_erasmus_feedback():
Parameters
- sid (str): The SID (Student ID or unique identifier) of the user providing the feedback.
- pin (str): The PIN associated with the user for authentication and data retrieval.
- feedbackBody (str): The main content of the feedback about the user's Erasmus visit.
- visitunderstanding (str): The user's understanding of the Erasmus visit.
- professionalism (str): The professionalism demonstrated during the Erasmus visit.
- visittopic (str): The topic or subject of the Erasmus visit.
- visitinterest (str): The level of interest the user had in the Erasmus visit.
- adequacy (str): The adequacy of the Erasmus visit or related activities.
- overallexperience (str): The user's overall experience during the Erasmus visit.
- suggestionworkshop (str, optional): Suggestions related to the workshop during the Erasmus visit (optional).
- suggestionpremises (str, optional): Suggestions for the premises or facilities during the Erasmus visit (optional).
Initialization Steps
- user (dict): The function retrieves the user record using
self.get_user_by_query(sid, pin), which returns the user's details, including theirrecordId. - recordid (str): The
recordIdis extracted from the user record. If norecordIdis found, the function logs an error and returns a failure response. - groupraw (str): The function retrieves the raw assigned group ID using
YetiForceClient.getRawAssignedGroup(user), which helps identify the user's assigned group. - Validation: The function checks whether the
recordIdandgroupraware present. If either is missing, it logs an error and returns a failure response with an appropriate error message.
Purpose
The purpose of this function is to manage the creation or updating of Erasmus feedback for a user. It collects various pieces of feedback regarding the Erasmus visit, such as understanding, professionalism, topics, interest, experience, and suggestions. The function ensures that the necessary information is available before proceeding to either create a new feedback entry or update an existing one. It interacts with the backend system to store or modify the feedback.
Example Code Usage
# Example Erasmus feedback creation
sid = "200000"
pin = "0000"
feedbackBody = "The Erasmus visit was highly educational, and the workshop was well-organized."
visitunderstanding = "Clear understanding of the visit."
professionalism = "The visit was conducted professionally."
visittopic = "The topic covered was related to international collaboration."
visitinterest = "I was very interested in the topic."
adequacy = "The visit was adequately planned."
overallexperience = "Overall, it was a great experience with valuable insights."
suggestionworkshop = "More interactive activities in future workshops."
suggestionpremises = "Improvement in premises accessibility would be helpful."
response = create_erasmus_feedback(sid, pin, feedbackBody, visitunderstanding=visitunderstanding,
professionalism=professionalism, visittopic=visittopic,
visitinterest=visitinterest, adequacy=adequacy,
overallexperience=overallexperience,
suggestionworkshop=suggestionworkshop,
suggestionpremises=suggestionpremises)
print(response)
Another Example (Without Optional Parameters)
# Example Erasmus feedback creation without optional parameters
sid = "200001"
pin = "1234"
feedbackBody = "The Erasmus visit was informative and helpful."
response = create_erasmus_feedback(sid, pin, feedbackBody, visitunderstanding="Good understanding",
professionalism="Professional", visittopic="Cultural exchange",
visitinterest="Very interested", adequacy="Adequate",
overallexperience="Great overall experience")
print(response)
Key Functional Flow:
- User and Group Validation: The function retrieves the user’s record and validates the presence of both
recordIdandgroupraw. - Feedback Construction: The function constructs a feedback dictionary with all relevant fields, including any optional parameters such as suggestions for workshops or premises.
- Feedback Creation or Edit: It checks if feedback has already been submitted for the user. If feedback exists, it updates the existing entry; otherwise, it creates a new feedback entry.
- API Interaction: The function interacts with the backend API to create or edit the feedback entry and logs the response.
Return Value
- The function returns a JSON response containing either the newly created or updated Erasmus feedback entry. The response includes data about the success or failure of the feedback creation or update operation.
create_hybrid_feedback():
Parameters
- sid (str): The SID (Student ID or unique identifier) of the user providing the feedback.
- pin (str): The PIN associated with the user for authentication and data retrieval.
- feedbackbody (str): The main content of the feedback regarding the hybrid experience, summarizing the user's thoughts and opinions.
- overallexperience2 (str): The user's overall experience with the hybrid program or event.
- learning_experience (str): The user's learning experience during the hybrid program or event.
- like_visits (str): The user's opinion about the visits related to the hybrid program.
- overallexperience (str): The user's overall opinion about the hybrid program or event.
- typeactivities (str): The type of activities involved in the hybrid program or event (e.g., workshops, discussions, etc.).
- satisfied (str): The user's level of satisfaction with the hybrid program or event.
- comments (str, optional): Any additional comments the user might have about their experience (optional).
Initialization Steps
- user (dict): The function first retrieves the user’s record using
self.get_user_by_query(sid, pin)to obtain therecordIdand other relevant details. - recordid (str): The
recordIdis extracted from the user record. If norecordIdis found, the function returns a failure response with a message indicating that theRecord IDwas not found. - groupid (str): The function retrieves the raw assigned group ID using
YetiForceClient.getRawAssignedGroup(user)to identify the group to which the user belongs. If thegroupidis not found, the function logs an error and returns a failure response.
Purpose
The primary purpose of this function is to gather feedback from users regarding their experience with a hybrid program. The feedback includes both qualitative data (comments, learning experience) and quantitative data (satisfaction levels, type of activities). After collecting this data, the function constructs a feedback entry and submits it to the system. The function also checks for the existence of required data (e.g., recordId, groupid) to ensure the feedback can be properly recorded. If any required data is missing, it returns an error response.
Example Code Usage
# Example hybrid feedback creation
sid = "200000"
pin = "0000"
feedbackbody = "The hybrid program was engaging and informative, especially the interactive workshops."
overallexperience2 = "Excellent"
learning_experience = "I learned a lot about new technologies and practical applications."
like_visits = "The site visits were very informative and well organized."
overallexperience = "Overall, I had a positive experience and would recommend it."
typeactivities = "Workshops, Site visits, Group discussions"
satisfied = "Very satisfied"
comments = "I look forward to similar future programs."
response = create_hybrid_feedback(sid, pin, feedbackbody, overallexperience2=overallexperience2,
learning_experience=learning_experience, like_visits=like_visits,
overallexperience=overallexperience, typeactivities=typeactivities,
satisfied=satisfied, comments=comments)
print(response)
Another Example (Without Optional Parameters)
# Example hybrid feedback creation without comments
sid = "200001"
pin = "1234"
feedbackbody = "The hybrid event was very interactive and provided a great mix of learning and practical activities."
overallexperience2 = "Good"
learning_experience = "I learned a lot about project management and team collaboration."
like_visits = "The industry visits were insightful."
overallexperience = "The overall experience was good and enriching."
typeactivities = "Team projects, Presentations, Case studies"
satisfied = "Satisfied"
response = create_hybrid_feedback(sid, pin, feedbackbody, overallexperience2=overallexperience2,
learning_experience=learning_experience, like_visits=like_visits,
overallexperience=overallexperience, typeactivities=typeactivities,
satisfied=satisfied)
print(response)
Key Functional Flow:
- User Validation: The function retrieves the user’s record and checks if the
recordIdis present. If it is missing, an error response is returned. - Group Validation: The function retrieves the
groupid(raw assigned group) for the user to associate the feedback with the correct group. If the group is not found, an error response is returned. - Feedback Construction: The function constructs a feedback dictionary containing the provided feedback details (e.g., overall experience, learning experience, type of activities).
- Feedback Submission: The feedback dictionary is submitted to the backend system using
_create_entry, which stores the feedback in the appropriate module.
Return Value
- The function returns a JSON response that contains the result of the feedback submission. If the feedback is successfully created, it will return a success message; otherwise, it will return an error response indicating which piece of information was missing or invalid.
def getCompanyrawidFromInternPlace():
Parameters
- data (dict): A dictionary that contains the data structure representing internship placement details. This data is expected to include nested keys where the company ID can be found under
'assigned_partner'->'raw'.
Initialization Steps
- first_key (str): The function retrieves the first key from the dictionary located under the
'data'key. It usesnext(iter(data['data']))to access the first item in the dictionary. - raw_company_id (str or None): The function attempts to retrieve the
rawcompany ID from the nested structure of theassigned_partnerkey. If there is an issue (e.g., the expected key or data is missing), it handles theTypeErrorand setsraw_company_idtoNone.
Purpose
The primary purpose of this function is to extract and return the raw company ID from an internship placement record. The company ID is essential for further processing or for linking the internship placement to the appropriate company in a database or system. The function ensures that if the data structure is not as expected, it doesn't raise an error but returns None instead.
Example Code Usage
# Example data structure representing internship placement details
data = {
'data': {
'internship1': {
'assigned_partner': {
'raw': 12345
}
}
}
}
# Call the function to get the company raw ID
company_raw_id = getCompanyrawidFromInternPlace(data)
print(company_raw_id) # Output: 12345
Example with Missing Data
# Example data structure where the raw company ID is missing or malformed
data = {
'data': {
'internship1': {
'assigned_partner': {}
}
}
}
# Call the function to get the company raw ID
company_raw_id = getCompanyrawidFromInternPlace(data)
print(company_raw_id) # Output: None
Key Functional Flow:
- Accessing the Data: The function accesses the first key in the
'data'dictionary, which represents an individual internship placement. - Extracting the Company ID: It attempts to extract the
rawcompany ID from theassigned_partnerfield. - Error Handling: If the data structure is not as expected (e.g., if the
assigned_partnerkey is missing or malformed), it catches theTypeErrorand returnsNone.
Return Value
- Success: The function returns the raw company ID (a numeric or string value).
- Failure: If the data structure is invalid or the company ID cannot be found, it returns
None.
def get_group_from_group_record_id():
Parameters
- grid (str): The group record ID. This ID is used to identify a specific group in the system and is passed to the function in order to retrieve its details.
Initialization Steps
- Logging: The function logs the action of retrieving the group associated with the given group record ID using
logging.info. - Token Check: It calls
self._CheckTokenExsist()to ensure that a valid authentication token exists before making the request. - Path Construction: The function constructs the API request path using the group record ID (
grid). The path is dynamically created using the format stringf"{DefaultModules.Groups}/Record/{grid}", whereDefaultModules.Groupsis likely a predefined constant representing the groups module in the system. - API Request: The function sends a GET request to the specified path using
self._requesttoyeti("GET", path). This method likely interacts with the backend API to fetch the group data.
Purpose
The function's purpose is to fetch and return the group details (likely including the group name) corresponding to a specific group record ID (grid). This is useful when trying to identify or display the group associated with a given record ID in the system.
Example Code Usage
# Example usage of get_group_from_group_record_id
grid = "12345" # Group record ID
group_info = get_group_from_group_record_id(grid)
# Print the JSON response returned by the function
print(group_info)
Key Functional Flow:
- Logging: Logs the process of retrieving group information based on the provided group record ID.
- Token Validation: Ensures that a valid authentication token exists by calling
self._CheckTokenExsist(). - API Request: Constructs the request path using the
gridand sends a GET request to the server to retrieve the group information. - Response: The response from the API is expected to be in JSON format, and the function returns this JSON data.
Return Value
The function returns the response from the API as a JSON object. This JSON response likely contains information about the group, such as the group name and possibly other details associated with the group. If the request fails, an error response or an empty result may be returned depending on the implementation of _requesttoyeti.
Example Response:
{
"group_name": "Engineering Group",
"group_id": "12345",
"description": "This is a group for engineering students."
}
This output shows the expected group information based on the provided grid (group record ID).
def checkIfUserHasAlreadyMadeFeedback():
Parameters
- response (dict): This is the response from an API or data source, expected to contain feedback records in the
'data'field. The format of the response is typically a dictionary with a'data'key, which contains a collection of records (e.g., feedback entries) indexed by record IDs.
Initialization Steps
- Initial Print Statement: The function first prints the
responseparameter for debugging or logging purposes, which helps to see the structure of the data. - Check for Empty Data: The function checks if the
'data'field in the response is empty or not. If no data is found (i.e.,'data'isNoneor empty), it returnsFalse. - Check for "No related fields" Message: If the
'data'key contains a specific message like"No related fields found", the function also returnsFalse, indicating that no feedback records were found. - Initialize
last_record_id: A variablelast_record_idis initialized toNoneto hold the last record ID found during the iteration over the records.
Purpose
The purpose of the function is to check if a user has already made feedback by processing the response data. It does this by looking for existing records in the 'data' field. If records are found, it returns the last record ID (indicating that feedback exists); otherwise, it returns False to indicate no feedback has been made.
Example Code Usage
# Example response where feedback records exist
response = {
'code': '200',
'data': {
'108946': {},
'108947': {},
'108950': {},
'108951': {}
}
}
# Check if the user has already made feedback
last_record_id = checkIfUserHasAlreadyMadeFeedback(response)
print(last_record_id) # Output: 108951 (the last feedback record ID)
# Example response where no feedback records exist
response_empty = {
'code': '200',
'data': {}
}
# Check if the user has already made feedback
last_record_id_empty = checkIfUserHasAlreadyMadeFeedback(response_empty)
print(last_record_id_empty) # Output: False (no feedback records found)
Key Functional Flow:
- Check for Data Existence: The function first checks if the
'data'field in the response exists and contains feedback records. If not, it returnsFalse. - Check for Specific Message: If the response contains the message
"No related fields found", it returnsFalse, indicating no feedback was made. - Iterate through Feedback Records: If records exist in the
'data'field, the function iterates through the records, updating thelast_record_idwith the most recent feedback record ID. - Return Last Record ID: Once the iteration completes, the function returns the
last_record_id, which is the ID of the most recent feedback record found in the response.
Return Value
- Success: The function returns the last feedback record ID (a string or number representing the last entry).
- Failure: If no records are found or if the response contains a "No related fields found" message, the function returns
False.
Example Response:
{
"code": "200",
"data": {
"108946": {},
"108947": {},
"108950": {},
"108951": {}
}
}
In this case, the function will return the last record ID, 108951. If the 'data' field is empty or contains the "No related fields found" message, the function will return False.
def check_families_feedbacks():
Parameters
- sid (str): The student's identification number, used to identify the user whose feedback status needs to be checked.
- pin (str): The student's personal identification number, which is used in combination with
sidto fetch specific records for the user.
Initialization Steps
- Logging: The function begins by logging the action of checking whether the user has made feedback. This is done for tracking purposes and debugging.
- Token Validation: It calls
self._CheckTokenExsist()to ensure that the necessary authentication token is available for making a valid request. - Fetching Related Fields: The function then calls
self.get_related_fields()to fetch the relevant data associated with the user’s host family feedback, usingsid,pin, and theDefaultModules.ShortTermandDefaultModules.HostfamiliesFeedBackmodules. The request also includes an optional"x-fields": '[""]'parameter, which likely filters or specifies certain fields in the response. - Feedback Check: The function delegates the actual feedback check to the
YetiForceClient.checkIfUserHasAlreadyMadeFeedback()function by passing the fetched response data.
Purpose
The primary purpose of this function is to determine whether a user has already submitted feedback for their host family in a short-term program. It does so by making a request to fetch related fields and then checking the response for existing feedback records. If feedback is found, it returns the last feedback record ID; otherwise, it returns False.
Example Code Usage
# Example SID and PIN of a user
sid = "123456"
pin = "7890"
# Call the function to check if the user has already made feedback
last_record_id = check_families_feedbacks(sid, pin)
# Print the result
if last_record_id:
print(f"User has already made feedback with record ID: {last_record_id}")
else:
print("User has not made any feedback yet.")
Key Functional Flow:
- Logging: The function logs that it is checking for existing feedback for the given user.
- Token Validation: Ensures that a valid authentication token exists before proceeding with the API request.
- Fetch Related Data: It retrieves relevant data related to the user’s host family feedback using the provided
sidandpin. - Check Feedback: The function then delegates the task of checking whether feedback exists to
checkIfUserHasAlreadyMadeFeedback(), passing the response obtained in the previous step.
Return Value
- Success: If feedback records are found, the function returns the last record ID associated with the user's feedback.
- Failure: If no feedback records exist, it returns
False.
Example Response:
{
"code": "200",
"data": {
"108946": {},
"108947": {},
"108950": {},
"108951": {}
}
}
In this case, if feedback records exist, the function will return the last record ID (108951). If no feedback records are found or if the response indicates that no related fields are present, the function will return False.
check_job_placement_feedback():
Parameters
- sid (str): The student identification number, used to uniquely identify the user whose feedback status is being checked.
- pin (str): The personal identification number of the student, used in combination with
sidto query the user’s specific data.
Initialization Steps
- Logging: The function begins by logging the action of checking whether the user has made feedback. This helps with tracking and debugging.
- Token Validation: It calls
self._CheckTokenExsist()to ensure that the necessary authentication token is present and valid before making the request. - Fetching Related Fields: The function calls
self.get_related_fields()to retrieve the relevant data for the user’s job placement feedback, usingsid,pin, and theDefaultModules.ShortTermandDefaultModules.PlacementFeedBackmodules. The request includes an optional"x-fields": '[""]'parameter, which might be used to filter specific fields in the response data. - Feedback Check: The function then passes the fetched response to
YetiForceClient.checkIfUserHasAlreadyMadeFeedback()to check if feedback has been submitted already.
Purpose
The primary purpose of this function is to determine whether a user has already submitted feedback for their job placement. It retrieves the relevant feedback data associated with the user and delegates the actual feedback check to another function, which checks if any feedback exists. If feedback is found, it returns the last record ID; otherwise, it returns False.
Example Code Usage
# Example SID and PIN of a user
sid = "654321"
pin = "4321"
# Call the function to check if the user has already made feedback for job placement
last_record_id = check_job_placement_feedback(sid, pin)
# Print the result
if last_record_id:
print(f"User has already made feedback with record ID: {last_record_id}")
else:
print("User has not made any job placement feedback yet.")
Key Functional Flow:
- Logging: Logs that it is checking if the user has made feedback for their job placement.
- Token Validation: Ensures that the request is authenticated by validating the token before proceeding with fetching the data.
- Fetch Related Data: Retrieves the relevant data for the user’s job placement feedback using
sidandpinthrough theget_related_fields()function, with theDefaultModules.ShortTermandDefaultModules.PlacementFeedBackmodules. - Check Feedback: The function then delegates the task of checking for existing feedback to
checkIfUserHasAlreadyMadeFeedback(), passing the response data it received.
Return Value
- Success: If feedback records are found, the function returns the last record ID associated with the feedback.
- Failure: If no feedback records exist or if the response indicates that no related fields are present, the function returns
False.
Example Response:
{
"code": "200",
"data": {
"109001": {},
"109002": {},
"109003": {}
}
}
In this case, if feedback records exist, the function will return the last record ID (109003). If no feedback records are found or if the response contains a message like "No related fields found", the function will return False.
check_erasmus_feedback():
Parameters
- sid (str): The student identification number. This is used to identify the specific user whose feedback status is being checked.
- pin (str): The personal identification number of the user. It is used in combination with
sidto retrieve the correct user data.
Initialization Steps
- Logging: The function starts by logging an informational message indicating that it is checking if the user has already made feedback. This log helps with tracking and debugging.
- Token Validation: It calls
self._CheckTokenExsist()to ensure the necessary authentication token is available before proceeding with any requests. - Fetching Related Fields: The function calls
self.get_related_fields()to fetch data related to the Erasmus feedback using thesid,pin, and theDefaultModules.ShortTermandDefaultModules.ErasmusFeedBackmodules. It also includes a parameter"x-fields": '[""]', which likely filters or specifies certain fields to retrieve in the response. - Feedback Check: After retrieving the data, the function passes the response to
YetiForceClient.checkIfUserHasAlreadyMadeFeedback()to check whether feedback has been previously submitted for the Erasmus program.
Purpose
The main purpose of this function is to verify whether a user has already submitted feedback for their Erasmus program. It does this by fetching the relevant user data and passing it to a helper function that checks for existing feedback records. If feedback is found, it returns the last record ID; otherwise, it returns False.
Example Code Usage
# Example SID and PIN for the user
sid = "987654"
pin = "1234"
# Call the function to check if the user has already provided Erasmus feedback
last_record_id = check_erasmus_feedback(sid, pin)
# Print the result
if last_record_id:
print("User has already made Erasmus feedback with record ID: {last_record_id}")
else:
print("User has not made any Erasmus feedback yet.")
Key Functional Flow:
- Logging: Logs the action of checking for Erasmus feedback for the given user.
- Token Validation: Ensures that the necessary authentication token is available to make the request.
- Fetch Related Data: Retrieves the relevant data for Erasmus feedback using the
sidandpinof the user, fetching information from theShortTermandErasmusFeedBackmodules. - Check Feedback: The function delegates the task of checking whether feedback exists to
checkIfUserHasAlreadyMadeFeedback(), passing the fetched response data.
Return Value
- Success: If the user has already made feedback, the function returns the last feedback record ID.
- Failure: If no feedback records are found, it returns
False.
Example Response:
{
"code": "200",
"data": {
"120001": {},
"120002": {},
"120003": {}
}
}
If feedback records exist, the function will return the last record ID (120003). If no feedback is found or if the response contains a message such as "No related fields found", the function will return False.
check_hybrid_feedback():
Parameters
- sid (str): The student identification number, used to uniquely identify the user whose feedback status is being checked.
- pin (str): The personal identification number associated with the user, used alongside
sidto query the user's feedback data.
Initialization Steps
- Logging: The function starts by logging an informational message indicating that it is checking whether the user has already provided feedback. This log helps track the execution and debug any potential issues.
- Token Validation: The function calls
self._CheckTokenExsist(), which ensures that an authentication token is available before making any requests to the API or server. This step is crucial to prevent unauthorized access. - Fetching Related Fields: The function uses
self.get_related_fields()to fetch data related to the hybrid feedback using the providedsidandpin. It specifies theDefaultModules.ShortTermandDefaultModules.HybridFeedBackmodules, which are likely related to short-term programs and hybrid feedback data. The request also includes an optional parameter"x-fields": '[""]', which may be used to filter or specify which fields to retrieve from the server.
Purpose
The purpose of this function is to determine whether a user has already submitted feedback for a hybrid program. It does this by querying the relevant feedback data associated with the user and then passing the response data to an external function (likely checkIfUserHasAlreadyMadeFeedback) to check if feedback already exists. If feedback is found, it returns the last record ID; otherwise, it returns False.