Introduction
Empress Framework is a Python-based, full-stack web framework that comes bundled with a rich set of utility functions. These functions are designed to simplify common operations such as DateTime management, date and currency formatting, PDF generation, and much more. This guide provides an in-depth guide on these utility functions and how developers can integrate them into their applications for enhanced functionality and efficiency.
Introduction to Empress Utility Functions
Empress Utility Functions, accessible through the frappe.utils module, are a set of predefined methods that enable developers to perform common operations effortlessly. By understanding and leveraging these functions, developers can expedite the development process, reduce the amount of code written, and improve the overall efficiency and performance of the application.
These utility functions can be imported from the frappe.utils module and its nested modules like frappe.utils.data and frappe.utils.logger in any Python file of your Empress App.
Here is a comprehensive guide on some of the most commonly used Empress utility functions:
Date and Time Functions
now
The now() function returns the current datetime in the format yyyy-mm-dd hh:mm:ss.
from frappe.utils import now
print(now()) # '2021-05-25 06:38:52.242515'
getdate
The getdate(string_date=None) function converts a string_date (yyyy-mm-dd) to a datetime.date object. If no input is provided, the current date is returned. The function throws an exception if string_date is an invalid date string.
from frappe.utils import getdate
print(getdate()) # datetime.date(2021, 5, 25)
print(getdate('2000-03-18')) # datetime.date(2000, 3, 18)
today
The today() function returns the current date in the format yyyy-mm-dd.
from frappe.utils import today
print(today()) # '2021-05-25'
add_to_date
The add_to_date function is used for performing date/datetime deltas, for instance, adding or subtracting a certain number of days from a particular date/datetime.
from datetime import datetime
from frappe.utils import add_to_date
today = datetime.now().strftime('%Y-%m-%d')
print(today) # '2021-05-21'
after_10_days = add_to_date(datetime.now(), days=10, as_string=True)
print(after_10_days) # '2021-05-31'
String Manipulation Functions
pretty_date
The pretty_date(iso_datetime) function takes an ISO time and returns a string representing how long ago the date represents. This is commonly used in communication applications like instant messengers.
from frappe.utils import pretty_date, now, add_to_date
print(pretty_date(now())) # 'just now'
format_duration
The format_duration(seconds, hide_days=False) function converts the given duration value in seconds (float) to a duration format.
from frappe.utils import format_duration
print(format_duration(50)) # '50s'
print(format_duration(10000)) # '2h 46m 40s'
comma_and
The comma_and(some_list, add_quotes=True) function takes a list or tuple some_list and returns a string of the format 1st item, 2nd item, .... and last item.
from frappe.utils import comma_and
print(comma_and([1, 2, 3])) # "'1', '2' and '3'"
print(comma_and(['Apple', 'Ball', 'Cat'], add_quotes=False)) # 'Apple, Ball and Cat'
print(comma_and('abcd')) # 'abcd'
PDF Generation Function
get_pdf
The get_pdf(html, options=None, output=None) function uses pdfkit and pyPDF2 modules to generate PDF files from HTML.
import frappe
from frappe.utils.pdf import get_pdf
@frappe.whitelist(allow_guest=True)
def generate_invoice():
html = '<h1>Invoice from Star Electronics e-Store!</h1>'
frappe.local.response.filename = 'invoice.pdf'
frappe.local.response.filecontent = get_pdf(html)
frappe.local.response.type = 'pdf'
Email Validation Function
validate_email_address
The validate_email_address(email_str, throw=False) function is used to validate the given email_str.
from frappe.utils import validate_email_address
print(validate_email_address('[email protected]')) # '[email protected]'
Phone Number Validation Function
validate_phone_number
The validate_phone_number(phone_number, throw=False) function is used to validate the given phone_number.
from frappe.utils import validate_phone_number
print(validate_phone_number('753858375')) # True
Redis Cache
frappe.cache()
The frappe.cache() function returns the redis connection, which is an instance of class RedisWrapper.
import frappe
cache = frappe.cache()
print(cache.set('name', 'frappe')) # True
print(cache.get('name')) # b'frappe'
Email Sending Function
frappe.sendmail()
The frappe.sendmail() function is used to send email using user’s default Email Account or global default Email Account.
import frappe
recipients = [
'[email protected]',
'[email protected]'
]
frappe.sendmail(
recipients=recipients,
subject=frappe._('Birthday Reminder'),
template='birthday_reminder',
args=dict(
reminder_text=reminder_text,
birthday_persons=birthday_persons,
message=message,
),
header=_('Birthday Reminder 🎂')
)
Empress Framework’s utility functions offer a broad spectrum of functionalities that developers can use to enhance their applications. Understanding these functions and how to properly integrate them into your application can significantly improve your development efficiency and application performance.