本文整理汇总了Python中errorhandler.ErrorHandler类的典型用法代码示例。如果您正苦于以下问题:Python ErrorHandler类的具体用法?Python ErrorHandler怎么用?Python ErrorHandler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ErrorHandler类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub',
desired_capabilities=None, browser_profile=None, proxy=None):
"""
Create a new driver that will issue commands using the wire protocol.
:Args:
- command_executor - Either a command.CommandExecutor object or a string that specifies the URL of a remote server to send commands to.
- desired_capabilities - Dictionary holding predefined values for starting a browser
- browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested.
"""
if desired_capabilities is None:
raise WebDriverException("Desired Capabilities can't be None")
if not isinstance(desired_capabilities, dict):
raise WebDriverException("Desired Capabilities must be a dictionary")
if proxy is not None:
proxy.add_to_capabilities(desired_capabilities)
self.command_executor = command_executor
if type(self.command_executor) is str or type(self.command_executor) is unicode:
self.command_executor = RemoteConnection(command_executor)
self._is_remote = True
self.session_id = None
self.capabilities = {}
self.error_handler = ErrorHandler()
self.start_client()
self.start_session(desired_capabilities, browser_profile)
示例2: __init__
def __init__(self, command_executor='http://localhost:4444/wd/hub',
desired_capabilities = None,
browser_profile=None):
"""Create a new driver that will issue commands using the wire protocol.
Args:
command_executor - Either a command.CommandExecutor object or a string
that specifies the URL of a remote server to send commands to.
desired_capabilities - Dictionary holding predefined values for starting
a browser
browser_profile: A browser profile directory as a Base64-encoded
zip file. Only used if Firefox is requested.
"""
if desired_capabilities is None:
raise WebDriverException(" Desired Capabilities can't be None")
self.command_executor = command_executor
if type(self.command_executor) is str:
self.command_executor = RemoteConnection(command_executor)
self.session_id = None
self.capabilities = {}
self.error_handler = ErrorHandler()
self.start_client()
self.start_session(desired_capabilities, browser_profile)
示例3: __init__
def __init__(self, command_executor, browser_name, platform, version='',
javascript_enabled=True):
"""Create a new driver that will issue commands using the wire protocol.
Args:
command_executor - Either a command.CommandExecutor object or a string
that specifies the URL of a remote server to send commands to.
browser_name - A string indicating which browser to request a new
session for from the remote server. Should be one of
{mobile safari|firefox|internet explorer|htmlunit|chrome}.
platform - A string indicating the desired platform to request from
the remote server. Should be one of
{WINDOWS|XP|VISTA|MAC|LINUX|UNIX|ANY}.
version - A string indicating a specific browser version to request,
or an empty string ot use any available browser. Defaults to the
empty string.
javascript_enabled - Whether the requested browser should support
JavaScript. Defaults to True.
"""
self.command_executor = command_executor
if type(self.command_executor) is str:
self.command_executor = RemoteConnection(command_executor)
self.session_id = None
self.capabilities = {}
self.error_handler = ErrorHandler()
self.start_client()
self.start_session(browser_name=browser_name,
platform=platform,
version=version,
javascript_enabled=javascript_enabled)
示例4: __init__
def __init__(self, level=logging.ERROR, message="No output as errors have occurred."):
from errorhandler import ErrorHandler
self.handler = ErrorHandler(level)
self.message = message
示例5: ErrorFilter
class ErrorFilter(BaseReader, BaseWriter):
temp_path = None
def __init__(self, level=logging.ERROR, message="No output as errors have occurred."):
from errorhandler import ErrorHandler
self.handler = ErrorHandler(level)
self.message = message
def start(self, create=True):
self.prefix = 0
self.handler.reset()
if self.temp_path is not None:
rmtree(self.temp_path)
if create:
self.temp_path = mkdtemp()
else:
self.temp_path = None
BaseWriter.start(self)
def get_stream(self, filename):
self.prefix += 1
return open(os.path.join(self.temp_path, str(self.prefix) + "-" + filename), "wb")
def get_workbooks(self):
if self.temp_path is None:
return
filenames = []
for name in os.listdir(self.temp_path):
d = name.split("-", 1)
d.append(name)
filenames.append(d)
filenames.sort()
for i, filename, pathname in filenames:
yield (
# We currently don't open with on_demand=True here
# as error filters should be lastish in the chain
# so there's not much win.
# However, if we did, getting rid of the temp dirs
# becomes a problem as, on Windows, they can't be
# deleted until the xlrd.Book object is done with
# and we don't know when that might be :-(
xlrd.open_workbook(
os.path.join(self.temp_path, pathname),
pickleable=0,
formatting_info=1,
on_demand=False,
ragged_rows=True,
),
filename,
)
def sheet(self, rdsheet, wtsheet_name):
self.rdsheet = rdsheet
BaseWriter.sheet(self, rdsheet, wtsheet_name)
def cell(self, rdrowx, rdcolx, wtrowx, wtcolx):
cell = self.rdsheet.cell(rdrowx, rdcolx)
if cell.ctype == xlrd.XL_CELL_EMPTY:
return
if cell.ctype == xlrd.XL_CELL_ERROR:
logger.error(
"Cell %s of sheet %r contains a bad value: %s"
% (
xlrd.cellname(rdrowx, rdcolx),
quoted_sheet_name(self.rdsheet.name),
cell_display(cell, self.rdbook.datemode),
)
)
return
BaseWriter.cell(self, rdrowx, rdcolx, wtrowx, wtcolx)
def finish(self):
BaseWriter.finish(self)
if self.handler.fired:
logger.error(self.message)
else:
self(self.next)
self.start(create=False)
for attr in ("rdbook", "rdsheet"):
if hasattr(self, attr):
delattr(self, attr)
示例6: __init__
def __init__(self):
self.db_name = current_app.config["DB"]["name"]
self.collection_name = ""
self.content = None
self.error_handle = ErrorHandler()
示例7: Model
class Model(object):
""" Base class to all Models """
def __init__(self):
self.db_name = current_app.config["DB"]["name"]
self.collection_name = ""
self.content = None
self.error_handle = ErrorHandler()
def set_content(self):
"""
There should be a definition of this function in every child class.
This function prepares a dictionary of the child class object's parameters which
are to be saved, and set it to self.content
"""
pass
def set_objprops(self, data=None):
"""
This function should have a definition in a child class for when
a single result is expected from the DB query. (when findone=True).
Eg: When fetching a user from the DB.
This function should then populate the appropriate properties of the object
with the data fetched from the DB
"""
pass
def get_db_handler(self):
""" Return DB handler for the appropriate collection, returns None if no collection name provided """
if not self.collection_name=="":
return MongoClient()[self.db_name][self.collection_name]
else:
return None
def check_duplicate(self, fields):
"""
provided fields, this function will return true if there is a duplicate entry
false if no duplicate value found
eg: fields = {"name": "John", "age": 20}
"""
try:
dbh = self.get_db_handler()
if dbh.find(fields).count()>0:
return True
return False
except Exception as e:
return self.error_handle.get_error(error=str(e), occurred_at="mad.lib.Model.check_duplicate()")
def get(self, conditions=None, sort_by=[("_id", 1)], distinct=False, distinct_fieldname=None, limit=0, findone=False):
""" Return db items fullfilled by conditions, and sorted by ID """
try:
dbh = self.get_db_handler()
content = None
if conditions and "_id" in conditions:
if not "noobjectify" in conditions or conditions["noobjectify"]==False:
conditions.update({"_id": ObjectId(conditions["_id"])})
if "noobjectify" in conditions:
del conditions["noobjectify"]
if distinct==True and distinct_fieldname:
content = dbh.find(conditions).sort(sort_by).distinct(distinct_fieldname)
elif findone==True:
content = dbh.find_one(conditions)
else:
content = dbh.find(conditions).sort(sort_by)
if content and limit>0:
content = content.limit(limit)
return content
except Exception as e:
return self.error_handle.get_error(error=str(e), occurred_at="mad.lib.Model.get()")
def save(self, duplicate_fields_check=None, allow_duplicate=False):
""" Add a new item to the collection """
try:
# duplicate_fields_check should be a dict, with field and its corresponding value
self.set_content()
if not self.content==None:
if allow_duplicate==False and not duplicate_fields_check==None:
if self.check_duplicate(fields=duplicate_fields_check)==True:
return {"status": "failed", "message": "Could not save item. Duplicate entry found."}
dbh = self.get_db_handler()
dbh.save(self.content)
return {"status": "success", "message": "Successfully added item to the DB"}
return {"status": "failed", "message": "Content is empty" }
except Exception as e:
return self.error_handle.get_error(error=str(e), occurred_at="mad.lib.Model.save()")
def update(self, conditions={}, overwrite=False, upsert=False, noobjectify=False, multi=False):
""" Update a DB entry """
try:
self.set_content()
dbh = self.get_db_handler()
if "_id" in conditions or "_id" in self.content:
#.........这里部分代码省略.........
示例8: WebDriver
class WebDriver(object):
"""
Controls a browser by sending commands to a remote server.
This server is expected to be running the WebDriver wire protocol as defined
here: http://code.google.com/p/selenium/wiki/JsonWireProtocol
:Attributes:
- command_executor - The command.CommandExecutor object used to execute commands.
- error_handler - errorhandler.ErrorHandler object used to verify that the server did not return an error.
- session_id - The session ID to send with every command.
- capabilities - A dictionary of capabilities of the underlying browser for this instance's session.
"""
def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub',
desired_capabilities=None, browser_profile=None):
"""
Create a new driver that will issue commands using the wire protocol.
:Args:
- command_executor - Either a command.CommandExecutor object or a string that specifies the URL of a remote server to send commands to.
- desired_capabilities - Dictionary holding predefined values for starting a browser
- browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested.
"""
if desired_capabilities is None:
raise WebDriverException("Desired Capabilities can't be None")
self.command_executor = command_executor
if type(self.command_executor) is str:
self.command_executor = RemoteConnection(command_executor)
self.session_id = None
self.capabilities = {}
self.error_handler = ErrorHandler()
self.start_client()
self.start_session(desired_capabilities, browser_profile)
@property
def name(self):
"""Returns the name of the underlying browser for this instance.
:Usage:
- driver.name
"""
if 'browserName' in self.capabilities:
return self.capabilities['browserName']
else:
raise KeyError('browserName not specified in session capabilities')
def start_client(self):
"""
Called before starting a new session. This method may be overridden
to define custom startup behavior.
"""
pass
def stop_client(self):
"""
Called after executing a quit command. This method may be overridden
to define custom shutdown behavior.
"""
pass
def start_session(self, desired_capabilities, browser_profile=None):
"""
Creates a new session with the desired capabilities.
:Args:
- browser_name - The name of the browser to request.
- version - Which browser version to request.
- platform - Which platform to request the browser on.
- javascript_enabled - Whether the new session should support JavaScript.
- browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested.
"""
if browser_profile:
desired_capabilities['firefox_profile'] = browser_profile.encoded
response = self.execute(Command.NEW_SESSION, {
'desiredCapabilities': desired_capabilities,
})
self.session_id = response['sessionId']
self.capabilities = response['value']
def _wrap_value(self, value):
if isinstance(value, dict):
converted = {}
for key, val in value.items():
converted[key] = self._wrap_value(val)
return converted
elif isinstance(value, WebElement):
return {'ELEMENT': value.id}
elif isinstance(value, list):
return list(self._wrap_value(item) for item in value)
else:
return value
def create_web_element(self, element_id):
"""
Creates a web element with the specified element_id.
"""
return WebElement(self, element_id)
def _unwrap_value(self, value):
if isinstance(value, dict) and 'ELEMENT' in value:
#.........这里部分代码省略.........
示例9: WebDriver
class WebDriver(object):
"""Controls a browser by sending commands to a remote server.
This server is expected to be running the WebDriver wire protocol as defined
here:
http://code.google.com/p/selenium/wiki/JsonWireProtocol
Attributes:
command_executor - The command.CommandExecutor object used to execute
commands.
error_handler - errorhandler.ErrorHandler object used to verify that the
server did not return an error.
session_id - The session ID to send with every command.
capabilities - A dictionary of capabilities of the underlying browser for
this instance's session.
"""
def __init__(self, command_executor='http://localhost:4444/wd/hub',
desired_capabilities = None,
browser_profile=None):
"""Create a new driver that will issue commands using the wire protocol.
Args:
command_executor - Either a command.CommandExecutor object or a string
that specifies the URL of a remote server to send commands to.
desired_capabilities - Dictionary holding predefined values for starting
a browser
browser_profile: A browser profile directory as a Base64-encoded
zip file. Only used if Firefox is requested.
"""
if desired_capabilities is None:
raise WebDriverException(" Desired Capabilities can't be None")
self.command_executor = command_executor
if type(self.command_executor) is str:
self.command_executor = RemoteConnection(command_executor)
self.session_id = None
self.capabilities = {}
self.error_handler = ErrorHandler()
self.start_client()
self.start_session(desired_capabilities, browser_profile)
@property
def name(self):
"""Returns the name of the underlying browser for this instance."""
if 'browserName' in self.capabilities:
return self.capabilities['browserName']
else:
raise KeyError('browserName not specified in session capabilities')
def start_client(self):
"""Called before starting a new session.
This method may be overridden to define custom startup behavior.
"""
pass
def stop_client(self):
"""Called after executing a quit command.
This method may be overridden to define custom shutdown behavior.
"""
pass
def start_session(self, desired_capabilities, browser_profile=None):
"""Creates a new session with the desired capabilities.
Args:
browser_name: The name of the browser to request.
version: Which browser version to request.
platform: Which platform to request the browser on.
javascript_enabled: Whether the new session should support JavaScript.
browser_profile: A browser profile directory as a Base64-encoded
zip file. Only used if Firefox is requested.
"""
if browser_profile:
desired_capabilities['firefox_profile'] = browser_profile
response = self.execute(Command.NEW_SESSION, {
'desiredCapabilities': desired_capabilities
})
self.session_id = response['sessionId']
self.capabilities = response['value']
def _wrap_value(self, value):
if isinstance(value, dict):
converted = {}
for key, val in value.items():
converted[key] = self._wrap_value(val)
return converted
elif isinstance(value, WebElement):
return {'ELEMENT': value.id}
elif isinstance(value, list):
return list(self._wrap_value(item) for item in value)
else:
return value
def create_web_element(self, element_id):
#.........这里部分代码省略.........
示例10: WebDriver
class WebDriver(object):
"""Controls a browser by sending commands to a remote server.
This server is expected to be running the WebDriver wire protocol as defined
here:
http://code.google.com/p/selenium/wiki/JsonWireProtocol
Attributes:
command_executor - The command.CommandExecutor object used to execute
commands.
error_handler - errorhandler.ErrorHandler object used to verify that the
server did not return an error.
session_id - The session ID to send with every command.
capabilities - A dictionary of capabilities of the underlying browser for
this instance's session.
"""
def __init__(self, command_executor, browser_name, platform, version='',
javascript_enabled=True):
"""Create a new driver that will issue commands using the wire protocol.
Args:
command_executor - Either a command.CommandExecutor object or a string
that specifies the URL of a remote server to send commands to.
browser_name - A string indicating which browser to request a new
session for from the remote server. Should be one of
{mobile safari|firefox|internet explorer|htmlunit|chrome}.
platform - A string indicating the desired platform to request from
the remote server. Should be one of
{WINDOWS|XP|VISTA|MAC|LINUX|UNIX|ANY}.
version - A string indicating a specific browser version to request,
or an empty string ot use any available browser. Defaults to the
empty string.
javascript_enabled - Whether the requested browser should support
JavaScript. Defaults to True.
"""
self.command_executor = command_executor
if type(self.command_executor) is str:
self.command_executor = RemoteConnection(command_executor)
self.session_id = None
self.capabilities = {}
self.error_handler = ErrorHandler()
self.start_client()
self.start_session(browser_name=browser_name,
platform=platform,
version=version,
javascript_enabled=javascript_enabled)
@property
def name(self):
"""Returns the name of the underlying browser for this instance."""
if 'browserName' in self.capabilities:
return self.capabilities['browserName']
else:
raise KeyError('browserName not specified in session capabilities')
def start_client(self):
"""Called before starting a new session.
This method may be overridden to define custom startup behavior.
"""
pass
def stop_client(self):
"""Called after executing a quit command.
This method may be overridden to define custom shutdown behavior.
"""
pass
def start_session(self, browser_name, platform=None, version=None,
javascript_enabled=False):
"""Creates a new session with the desired capabilities.
Args:
browser_name: The name of the browser to request.
version: Which browser version to request.
platform: Which platform to request the browser on.
javascript_enabled: Whether the new session should support JavaScript.
"""
response = self._execute(Command.NEW_SESSION, {
'desiredCapabilities': {
'browserName': browser_name,
'platform': platform or 'ANY',
'version': version or '',
'javascriptEnabled': javascript_enabled
}
})
self.session_id = response['sessionId']
self.capabilities = response['value']
def _wrap_value(self, value):
if isinstance(value, dict):
converted = {}
for key, val in value.items():
converted[key] = self._wrap_value(val)
return converted
elif isinstance(value, WebElement):
#.........这里部分代码省略.........
示例11: WebDriver
class WebDriver(object):
"""Controls a browser by sending commands to a remote server.
This server is expected to be running the WebDriver wire protocol as defined
here: http://code.google.com/p/selenium/wiki/JsonWireProtocol
Attributes:
command_executor - The command.CommandExecutor object used to execute
commands.
error_handler - errorhandler.ErrorHandler object used to verify that the
server did not return an error.
session_id - The session ID to send with every command.
capabilities - A dictionary of capabilities of the underlying browser for
this instance's session."""
def __init__(
self, command_executor="http://127.0.0.1:4444/wd/hub", desired_capabilities=None, browser_profile=None
):
"""Create a new driver that will issue commands using the wire protocol.
Args:
command_executor - Either a command.CommandExecutor object or a string
that specifies the URL of a remote server to send commands to.
desired_capabilities - Dictionary holding predefined values for starting
a browser
browser_profile: A browser profile directory as a Base64-encoded
zip file. Only used if Firefox is requested.
"""
if desired_capabilities is None:
raise WebDriverException("Desired Capabilities can't be None")
self.command_executor = command_executor
if type(self.command_executor) is str:
self.command_executor = RemoteConnection(command_executor)
self.session_id = None
self.capabilities = {}
self.error_handler = ErrorHandler()
self.start_client()
self.start_session(desired_capabilities, browser_profile)
@property
def name(self):
"""Returns the name of the underlying browser for this instance.
Usage:
driver.name
"""
if "browserName" in self.capabilities:
return self.capabilities["browserName"]
else:
raise KeyError("browserName not specified in session capabilities")
def start_client(self):
"""Called before starting a new session. This method may be overridden
to define custom startup behavior."""
pass
def stop_client(self):
"""Called after executing a quit command. This method may be overridden
to define custom shutdown behavior."""
pass
def start_session(self, desired_capabilities, browser_profile=None):
"""Creates a new session with the desired capabilities.
Args:
browser_name: The name of the browser to request.
version: Which browser version to request.
platform: Which platform to request the browser on.
javascript_enabled: Whether the new session should support JavaScript.
browser_profile: A browser profile directory as a Base64-encoded
zip file. Only used if Firefox is requested.
"""
if browser_profile:
desired_capabilities["firefox_profile"] = browser_profile.encoded
response = self.execute(Command.NEW_SESSION, {"desiredCapabilities": desired_capabilities})
self.session_id = response["sessionId"]
self.capabilities = response["value"]
def _wrap_value(self, value):
if isinstance(value, dict):
converted = {}
for key, val in value.items():
converted[key] = self._wrap_value(val)
return converted
elif isinstance(value, WebElement):
return {"ELEMENT": value.id}
elif isinstance(value, list):
return list(self._wrap_value(item) for item in value)
else:
return value
def create_web_element(self, element_id):
"""Creates a web element with the specified element_id."""
return WebElement(self, element_id)
def _unwrap_value(self, value):
if isinstance(value, dict) and "ELEMENT" in value:
return self.create_web_element(value["ELEMENT"])
elif isinstance(value, list):
return list(self._unwrap_value(item) for item in value)
else:
return value
def execute(self, driver_command, params=None):
#.........这里部分代码省略.........
示例12: WebDriver
class WebDriver(object):
"""Controls a browser by sending commands to a remote server.
This server is expected to be running the WebDriver wire protocol as defined
here:
http://code.google.com/p/selenium/wiki/JsonWireProtocol
Attributes:
command_executor - The command.CommandExecutor object used to execute
commands.
error_handler - errorhandler.ErrorHandler object used to verify that the
server did not return an error.
session_id - The session ID to send with every command.
capabilities - A dictionary of capabilities of the underlying browser for
this instance's session.
"""
def __init__(self, command_executor, browser_name, platform, version="", javascript_enabled=True):
"""Create a new driver that will issue commands using the wire protocol.
Args:
command_executor - Either a command.CommandExecutor object or a string
that specifies the URL of a remote server to send commands to.
browser_name - A string indicating which browser to request a new
session for from the remote server. Should be one of
{mobile safari|firefox|internet explorer|htmlunit|chrome}.
platform - A string indicating the desired platform to request from
the remote server. Should be one of
{WINDOWS|XP|VISTA|MAC|LINUX|UNIX|ANY}.
version - A string indicating a specific browser version to request,
or an empty string ot use any available browser. Defaults to the
empty string.
javascript_enabled - Whether the requested browser should support
JavaScript. Defaults to True.
"""
self.command_executor = command_executor
if type(self.command_executor) is str:
self.command_executor = RemoteConnection(command_executor)
self.session_id = None
self.capabilities = {}
self.error_handler = ErrorHandler()
self.start_client()
self.start_session(
browser_name=browser_name, platform=platform, version=version, javascript_enabled=javascript_enabled
)
@property
def name(self):
"""Returns the name of the underlying browser for this instance."""
if "browserName" in self.capabilities:
return self.capabilities["browserName"]
else:
raise KeyError("browserName not specified in session capabilities")
def start_client(self):
"""Called before starting a new session.
This method may be overridden to define custom startup behavior.
"""
pass
def stop_client(self):
"""Called after executing a quit command.
This method may be overridden to define custom shutdown behavior.
"""
pass
def start_session(self, browser_name, platform=None, version=None, javascript_enabled=False):
"""Creates a new session with the desired capabilities.
Args:
browser_name: The name of the browser to request.
version: Which browser version to request.
platform: Which platform to request the browser on.
javascript_enabled: Whether the new session should support JavaScript.
"""
response = self.execute(
Command.NEW_SESSION,
{
"desiredCapabilities": {
"browserName": browser_name,
"platform": platform or "ANY",
"version": version or "",
"javascriptEnabled": javascript_enabled,
}
},
)
self.session_id = response["sessionId"]
self.capabilities = response["value"]
def _wrap_value(self, value):
if isinstance(value, dict):
converted = {}
for key, val in value.items():
converted[key] = self._wrap_value(val)
return converted
elif isinstance(value, WebElement):
#.........这里部分代码省略.........
示例13: __init__
def __init__(self):
self.error_handle = ErrorHandler()
self.cache_handle = Cache
示例14: Controller
class Controller(object):
""" Parent class to all Controller classes. """
def __init__(self):
self.error_handle = ErrorHandler()
self.cache_handle = Cache
def get_db_handler(self):
""" Returns the DB handler """
mc = MongoClient()
return mc[current_app.config["DB"]["name"]]
def add_db_item(self, collection=None, content=None, _id=None, upsert=False):
""" Save an item to the DB """
try:
if collection and content:
db = self.get_db_handler()
_id = db[collection].save(content)
return {"status": "success", "message": "Successfully added item to the DB", "_id": _id}
return None
except Exception as e:
return self.error_handle.get_error(error=str(e), occurred_at="mad.lib.controller.add_db_item()")
def update_db_item(self, collection=None, conditions=None, content=None, upsert=False, overwrite=False, noobjectify=False, multi=False):
""" Update/upsert a DB item """
try:
if collection and conditions and content:
db = self.get_db_handler()
if noobjectify==False and "_id" in conditions:
conditions["_id"] = ObjectId(conditions["_id"])
if overwrite:
db[collection].update(conditions, {"$set": content}, upsert=upsert, multi=multi)
else:
db[collection].update(conditions, content, upsert=upsert, multi=multi)
return {"status": "success", "message": "DB item updated successfully."}
except Exception as e:
return self.error_handle.get_error(error=str(e), occurred_at="mad.lib.controller.update_db_item()")
def get_db_items(self, collection=None, conditions=None, sort_by=[("_id", 1)]):
""" Get items from a collection in the DB and return results """
try:
if collection:
if conditions and "_id" in conditions:
# By default, if an _id is provided, it'll be converted into an ObjectId instance.
# "noobjectify" would prevent it from making use of the _id directly instead of
# converting it into an ObjectId instance.
if not "noobjectify" in conditions or conditions["noobjectify"]==False:
conditions.update({"_id": ObjectId(conditions["_id"])})
items = self.get_db_handler()[collection].find(conditions).sort(sort_by)
if items:
return items
return None
except Exception as e:
return self.error_handle.get_error(error=str(e), occurred_at="mad.lib.controller.get_db_items()")
def get_db_distinct_items(self, collection=None, fieldname=None, conditions=None, sort_by=[("_id", 1)]):
""" Get unique/distinct values from all records of the given field """
try:
if collection and fieldname:
return self.get_db_handler()[collection].find(conditions).sort(sort_by).distinct(fieldname)
return None
except Exception as e:
return self.error_handle.get_error(error=str(e), occurred_at="mad.lib.controller.get_db_distinct_items()")
def remove_db_item(self, collection=None, conditions=None, remove_all=False):
""" Remove an or all items from the collection, based on given conditions """
try:
if remove_all:
conditions = {}
if collection and conditions:
self.get_db_handler()[collection].remove(conditions)
return {"status": "success", "message": "Successfully removed item(s) from the DB"}
except Exception as e:
return self.error_handle.get_error(error=str(e), occurred_at="mad.lib.controller.remove_db_item()")