repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
scalative/haas
haas/result.py
ResultCollector.addError
python
def addError(self, test, exception): result = self._handle_result( test, TestCompletionStatus.error, exception=exception) self.errors.append(result) self._mirror_output = True
Register that a test ended in an error. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``.
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L521-L535
[ "def _handle_result(self, test, status, exception=None, message=None):\n \"\"\"Create a :class:`~.TestResult` and add it to this\n :class:`~ResultCollector`.\n\n Parameters\n ----------\n test : unittest.TestCase\n The test that this result will represent.\n status : haas.result.TestComplet...
class ResultCollector(object): """Collecter for test results. This handles creating :class:`~.TestResult` instances and handing them off the registered result output handlers. """ # Temporary compatibility with unittest's runner separator2 = separator2 def __init__(self, buffer=False, failfast=False): self.buffer = buffer self.failfast = failfast self._result_handlers = [] self._sorted_handlers = None self.testsRun = 0 self.expectedFailures = [] self.unexpectedSuccesses = [] self.skipped = [] self.failures = [] self.errors = [] self.shouldStop = False self._successful = True self._mirror_output = False self._stderr_buffer = None self._stdout_buffer = None self._original_stderr = sys.stderr self._original_stdout = sys.stdout self._test_timing = {} @property def _handlers(self): if self._sorted_handlers is None: from .plugins.result_handler import sort_result_handlers self._sorted_handlers = sort_result_handlers(self._result_handlers) return self._sorted_handlers @staticmethod def _testcase_to_key(test): return (type(test), test._testMethodName) def _setup_stdout(self): """Hook stdout and stderr if buffering is enabled. """ if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = StringIO() self._stdout_buffer = StringIO() sys.stdout = self._stdout_buffer sys.stderr = self._stderr_buffer def _restore_stdout(self): """Unhook stdout and stderr if buffering is enabled. """ if self.buffer: if self._mirror_output: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' self._original_stdout.write(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' self._original_stderr.write(STDERR_LINE % error) sys.stdout = self._original_stdout sys.stderr = self._original_stderr self._stdout_buffer.seek(0) self._stdout_buffer.truncate() self._stderr_buffer.seek(0) self._stderr_buffer.truncate() def printErrors(self): # pragma: no cover # FIXME: Remove pass def add_result_handler(self, handler): """Register a new result handler. """ self._result_handlers.append(handler) # Reset sorted handlers if self._sorted_handlers: self._sorted_handlers = None def startTest(self, test, start_time=None): """Indicate that an individual test is starting. Parameters ---------- test : unittest.TestCase The test that is starting. start_time : datetime An internal parameter to allow the parallel test runner to set the actual start time of a test run in a subprocess. """ if start_time is None: start_time = datetime.utcnow() self._test_timing[self._testcase_to_key(test)] = start_time self._mirror_output = False self._setup_stdout() self.testsRun += 1 for handler in self._handlers: handler.start_test(test) def stopTest(self, test): """Indicate that an individual test has completed. Parameters ---------- test : unittest.TestCase The test that has completed. """ for handler in self._handlers: handler.stop_test(test) self._restore_stdout() self._mirror_output = False def startTestRun(self): """Indicate that the test run is starting. """ for handler in self._handlers: handler.start_test_run() def stopTestRun(self): """Indicate that the test run has completed. """ for handler in self._handlers: handler.stop_test_run() def add_result(self, result): """Add an already-constructed :class:`~.TestResult` to this :class:`~.ResultCollector`. This may be used when collecting results created by other ResultCollectors (e.g. in subprocesses). """ for handler in self._handlers: handler(result) if self._successful and result.status not in _successful_results: self._successful = False def _handle_result(self, test, status, exception=None, message=None): """Create a :class:`~.TestResult` and add it to this :class:`~ResultCollector`. Parameters ---------- test : unittest.TestCase The test that this result will represent. status : haas.result.TestCompletionStatus The status of the test. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. message : str Optional message associated with the result (e.g. skip reason). """ if self.buffer: stderr = self._stderr_buffer.getvalue() stdout = self._stdout_buffer.getvalue() else: stderr = stdout = None started_time = self._test_timing.get(self._testcase_to_key(test)) if started_time is None and isinstance(test, ErrorHolder): started_time = datetime.utcnow() elif started_time is None: raise RuntimeError( 'Missing test start! Please report this error as a bug in ' 'haas.') completion_time = datetime.utcnow() duration = TestDuration(started_time, completion_time) result = TestResult.from_test_case( test, status, duration=duration, exception=exception, message=message, stdout=stdout, stderr=stderr, ) self.add_result(result) return result @failfast @failfast def addFailure(self, test, exception): """Register that a test ended with a failure. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.failure, exception=exception) self.failures.append(result) self._mirror_output = True def addSuccess(self, test): """Register that a test ended in success. Parameters ---------- test : unittest.TestCase The test that has completed. """ self._handle_result(test, TestCompletionStatus.success) def addSkip(self, test, reason): """Register that a test that was skipped. Parameters ---------- test : unittest.TestCase The test that has completed. reason : str The reason the test was skipped. """ result = self._handle_result( test, TestCompletionStatus.skipped, message=reason) self.skipped.append(result) def addExpectedFailure(self, test, exception): """Register that a test that failed and was expected to fail. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.expected_failure, exception=exception) self.expectedFailures.append(result) @failfast def addUnexpectedSuccess(self, test): """Register a test that passed unexpectedly. Parameters ---------- test : unittest.TestCase The test that has completed. """ result = self._handle_result( test, TestCompletionStatus.unexpected_success) self.unexpectedSuccesses.append(result) def wasSuccessful(self): """Return ``True`` if the run was successful. """ return self._successful def stop(self): """Set the ``shouldStop`` flag, used by the test cases to determine if they should terminate early. """ self.shouldStop = True
scalative/haas
haas/result.py
ResultCollector.addFailure
python
def addFailure(self, test, exception): result = self._handle_result( test, TestCompletionStatus.failure, exception=exception) self.failures.append(result) self._mirror_output = True
Register that a test ended with a failure. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``.
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L538-L552
[ "def _handle_result(self, test, status, exception=None, message=None):\n \"\"\"Create a :class:`~.TestResult` and add it to this\n :class:`~ResultCollector`.\n\n Parameters\n ----------\n test : unittest.TestCase\n The test that this result will represent.\n status : haas.result.TestComplet...
class ResultCollector(object): """Collecter for test results. This handles creating :class:`~.TestResult` instances and handing them off the registered result output handlers. """ # Temporary compatibility with unittest's runner separator2 = separator2 def __init__(self, buffer=False, failfast=False): self.buffer = buffer self.failfast = failfast self._result_handlers = [] self._sorted_handlers = None self.testsRun = 0 self.expectedFailures = [] self.unexpectedSuccesses = [] self.skipped = [] self.failures = [] self.errors = [] self.shouldStop = False self._successful = True self._mirror_output = False self._stderr_buffer = None self._stdout_buffer = None self._original_stderr = sys.stderr self._original_stdout = sys.stdout self._test_timing = {} @property def _handlers(self): if self._sorted_handlers is None: from .plugins.result_handler import sort_result_handlers self._sorted_handlers = sort_result_handlers(self._result_handlers) return self._sorted_handlers @staticmethod def _testcase_to_key(test): return (type(test), test._testMethodName) def _setup_stdout(self): """Hook stdout and stderr if buffering is enabled. """ if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = StringIO() self._stdout_buffer = StringIO() sys.stdout = self._stdout_buffer sys.stderr = self._stderr_buffer def _restore_stdout(self): """Unhook stdout and stderr if buffering is enabled. """ if self.buffer: if self._mirror_output: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' self._original_stdout.write(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' self._original_stderr.write(STDERR_LINE % error) sys.stdout = self._original_stdout sys.stderr = self._original_stderr self._stdout_buffer.seek(0) self._stdout_buffer.truncate() self._stderr_buffer.seek(0) self._stderr_buffer.truncate() def printErrors(self): # pragma: no cover # FIXME: Remove pass def add_result_handler(self, handler): """Register a new result handler. """ self._result_handlers.append(handler) # Reset sorted handlers if self._sorted_handlers: self._sorted_handlers = None def startTest(self, test, start_time=None): """Indicate that an individual test is starting. Parameters ---------- test : unittest.TestCase The test that is starting. start_time : datetime An internal parameter to allow the parallel test runner to set the actual start time of a test run in a subprocess. """ if start_time is None: start_time = datetime.utcnow() self._test_timing[self._testcase_to_key(test)] = start_time self._mirror_output = False self._setup_stdout() self.testsRun += 1 for handler in self._handlers: handler.start_test(test) def stopTest(self, test): """Indicate that an individual test has completed. Parameters ---------- test : unittest.TestCase The test that has completed. """ for handler in self._handlers: handler.stop_test(test) self._restore_stdout() self._mirror_output = False def startTestRun(self): """Indicate that the test run is starting. """ for handler in self._handlers: handler.start_test_run() def stopTestRun(self): """Indicate that the test run has completed. """ for handler in self._handlers: handler.stop_test_run() def add_result(self, result): """Add an already-constructed :class:`~.TestResult` to this :class:`~.ResultCollector`. This may be used when collecting results created by other ResultCollectors (e.g. in subprocesses). """ for handler in self._handlers: handler(result) if self._successful and result.status not in _successful_results: self._successful = False def _handle_result(self, test, status, exception=None, message=None): """Create a :class:`~.TestResult` and add it to this :class:`~ResultCollector`. Parameters ---------- test : unittest.TestCase The test that this result will represent. status : haas.result.TestCompletionStatus The status of the test. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. message : str Optional message associated with the result (e.g. skip reason). """ if self.buffer: stderr = self._stderr_buffer.getvalue() stdout = self._stdout_buffer.getvalue() else: stderr = stdout = None started_time = self._test_timing.get(self._testcase_to_key(test)) if started_time is None and isinstance(test, ErrorHolder): started_time = datetime.utcnow() elif started_time is None: raise RuntimeError( 'Missing test start! Please report this error as a bug in ' 'haas.') completion_time = datetime.utcnow() duration = TestDuration(started_time, completion_time) result = TestResult.from_test_case( test, status, duration=duration, exception=exception, message=message, stdout=stdout, stderr=stderr, ) self.add_result(result) return result @failfast def addError(self, test, exception): """Register that a test ended in an error. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.error, exception=exception) self.errors.append(result) self._mirror_output = True @failfast def addSuccess(self, test): """Register that a test ended in success. Parameters ---------- test : unittest.TestCase The test that has completed. """ self._handle_result(test, TestCompletionStatus.success) def addSkip(self, test, reason): """Register that a test that was skipped. Parameters ---------- test : unittest.TestCase The test that has completed. reason : str The reason the test was skipped. """ result = self._handle_result( test, TestCompletionStatus.skipped, message=reason) self.skipped.append(result) def addExpectedFailure(self, test, exception): """Register that a test that failed and was expected to fail. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.expected_failure, exception=exception) self.expectedFailures.append(result) @failfast def addUnexpectedSuccess(self, test): """Register a test that passed unexpectedly. Parameters ---------- test : unittest.TestCase The test that has completed. """ result = self._handle_result( test, TestCompletionStatus.unexpected_success) self.unexpectedSuccesses.append(result) def wasSuccessful(self): """Return ``True`` if the run was successful. """ return self._successful def stop(self): """Set the ``shouldStop`` flag, used by the test cases to determine if they should terminate early. """ self.shouldStop = True
scalative/haas
haas/result.py
ResultCollector.addSkip
python
def addSkip(self, test, reason): result = self._handle_result( test, TestCompletionStatus.skipped, message=reason) self.skipped.append(result)
Register that a test that was skipped. Parameters ---------- test : unittest.TestCase The test that has completed. reason : str The reason the test was skipped.
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L565-L578
[ "def _handle_result(self, test, status, exception=None, message=None):\n \"\"\"Create a :class:`~.TestResult` and add it to this\n :class:`~ResultCollector`.\n\n Parameters\n ----------\n test : unittest.TestCase\n The test that this result will represent.\n status : haas.result.TestComplet...
class ResultCollector(object): """Collecter for test results. This handles creating :class:`~.TestResult` instances and handing them off the registered result output handlers. """ # Temporary compatibility with unittest's runner separator2 = separator2 def __init__(self, buffer=False, failfast=False): self.buffer = buffer self.failfast = failfast self._result_handlers = [] self._sorted_handlers = None self.testsRun = 0 self.expectedFailures = [] self.unexpectedSuccesses = [] self.skipped = [] self.failures = [] self.errors = [] self.shouldStop = False self._successful = True self._mirror_output = False self._stderr_buffer = None self._stdout_buffer = None self._original_stderr = sys.stderr self._original_stdout = sys.stdout self._test_timing = {} @property def _handlers(self): if self._sorted_handlers is None: from .plugins.result_handler import sort_result_handlers self._sorted_handlers = sort_result_handlers(self._result_handlers) return self._sorted_handlers @staticmethod def _testcase_to_key(test): return (type(test), test._testMethodName) def _setup_stdout(self): """Hook stdout and stderr if buffering is enabled. """ if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = StringIO() self._stdout_buffer = StringIO() sys.stdout = self._stdout_buffer sys.stderr = self._stderr_buffer def _restore_stdout(self): """Unhook stdout and stderr if buffering is enabled. """ if self.buffer: if self._mirror_output: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' self._original_stdout.write(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' self._original_stderr.write(STDERR_LINE % error) sys.stdout = self._original_stdout sys.stderr = self._original_stderr self._stdout_buffer.seek(0) self._stdout_buffer.truncate() self._stderr_buffer.seek(0) self._stderr_buffer.truncate() def printErrors(self): # pragma: no cover # FIXME: Remove pass def add_result_handler(self, handler): """Register a new result handler. """ self._result_handlers.append(handler) # Reset sorted handlers if self._sorted_handlers: self._sorted_handlers = None def startTest(self, test, start_time=None): """Indicate that an individual test is starting. Parameters ---------- test : unittest.TestCase The test that is starting. start_time : datetime An internal parameter to allow the parallel test runner to set the actual start time of a test run in a subprocess. """ if start_time is None: start_time = datetime.utcnow() self._test_timing[self._testcase_to_key(test)] = start_time self._mirror_output = False self._setup_stdout() self.testsRun += 1 for handler in self._handlers: handler.start_test(test) def stopTest(self, test): """Indicate that an individual test has completed. Parameters ---------- test : unittest.TestCase The test that has completed. """ for handler in self._handlers: handler.stop_test(test) self._restore_stdout() self._mirror_output = False def startTestRun(self): """Indicate that the test run is starting. """ for handler in self._handlers: handler.start_test_run() def stopTestRun(self): """Indicate that the test run has completed. """ for handler in self._handlers: handler.stop_test_run() def add_result(self, result): """Add an already-constructed :class:`~.TestResult` to this :class:`~.ResultCollector`. This may be used when collecting results created by other ResultCollectors (e.g. in subprocesses). """ for handler in self._handlers: handler(result) if self._successful and result.status not in _successful_results: self._successful = False def _handle_result(self, test, status, exception=None, message=None): """Create a :class:`~.TestResult` and add it to this :class:`~ResultCollector`. Parameters ---------- test : unittest.TestCase The test that this result will represent. status : haas.result.TestCompletionStatus The status of the test. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. message : str Optional message associated with the result (e.g. skip reason). """ if self.buffer: stderr = self._stderr_buffer.getvalue() stdout = self._stdout_buffer.getvalue() else: stderr = stdout = None started_time = self._test_timing.get(self._testcase_to_key(test)) if started_time is None and isinstance(test, ErrorHolder): started_time = datetime.utcnow() elif started_time is None: raise RuntimeError( 'Missing test start! Please report this error as a bug in ' 'haas.') completion_time = datetime.utcnow() duration = TestDuration(started_time, completion_time) result = TestResult.from_test_case( test, status, duration=duration, exception=exception, message=message, stdout=stdout, stderr=stderr, ) self.add_result(result) return result @failfast def addError(self, test, exception): """Register that a test ended in an error. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.error, exception=exception) self.errors.append(result) self._mirror_output = True @failfast def addFailure(self, test, exception): """Register that a test ended with a failure. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.failure, exception=exception) self.failures.append(result) self._mirror_output = True def addSuccess(self, test): """Register that a test ended in success. Parameters ---------- test : unittest.TestCase The test that has completed. """ self._handle_result(test, TestCompletionStatus.success) def addExpectedFailure(self, test, exception): """Register that a test that failed and was expected to fail. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.expected_failure, exception=exception) self.expectedFailures.append(result) @failfast def addUnexpectedSuccess(self, test): """Register a test that passed unexpectedly. Parameters ---------- test : unittest.TestCase The test that has completed. """ result = self._handle_result( test, TestCompletionStatus.unexpected_success) self.unexpectedSuccesses.append(result) def wasSuccessful(self): """Return ``True`` if the run was successful. """ return self._successful def stop(self): """Set the ``shouldStop`` flag, used by the test cases to determine if they should terminate early. """ self.shouldStop = True
scalative/haas
haas/result.py
ResultCollector.addExpectedFailure
python
def addExpectedFailure(self, test, exception): result = self._handle_result( test, TestCompletionStatus.expected_failure, exception=exception) self.expectedFailures.append(result)
Register that a test that failed and was expected to fail. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``.
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L580-L593
[ "def _handle_result(self, test, status, exception=None, message=None):\n \"\"\"Create a :class:`~.TestResult` and add it to this\n :class:`~ResultCollector`.\n\n Parameters\n ----------\n test : unittest.TestCase\n The test that this result will represent.\n status : haas.result.TestComplet...
class ResultCollector(object): """Collecter for test results. This handles creating :class:`~.TestResult` instances and handing them off the registered result output handlers. """ # Temporary compatibility with unittest's runner separator2 = separator2 def __init__(self, buffer=False, failfast=False): self.buffer = buffer self.failfast = failfast self._result_handlers = [] self._sorted_handlers = None self.testsRun = 0 self.expectedFailures = [] self.unexpectedSuccesses = [] self.skipped = [] self.failures = [] self.errors = [] self.shouldStop = False self._successful = True self._mirror_output = False self._stderr_buffer = None self._stdout_buffer = None self._original_stderr = sys.stderr self._original_stdout = sys.stdout self._test_timing = {} @property def _handlers(self): if self._sorted_handlers is None: from .plugins.result_handler import sort_result_handlers self._sorted_handlers = sort_result_handlers(self._result_handlers) return self._sorted_handlers @staticmethod def _testcase_to_key(test): return (type(test), test._testMethodName) def _setup_stdout(self): """Hook stdout and stderr if buffering is enabled. """ if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = StringIO() self._stdout_buffer = StringIO() sys.stdout = self._stdout_buffer sys.stderr = self._stderr_buffer def _restore_stdout(self): """Unhook stdout and stderr if buffering is enabled. """ if self.buffer: if self._mirror_output: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' self._original_stdout.write(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' self._original_stderr.write(STDERR_LINE % error) sys.stdout = self._original_stdout sys.stderr = self._original_stderr self._stdout_buffer.seek(0) self._stdout_buffer.truncate() self._stderr_buffer.seek(0) self._stderr_buffer.truncate() def printErrors(self): # pragma: no cover # FIXME: Remove pass def add_result_handler(self, handler): """Register a new result handler. """ self._result_handlers.append(handler) # Reset sorted handlers if self._sorted_handlers: self._sorted_handlers = None def startTest(self, test, start_time=None): """Indicate that an individual test is starting. Parameters ---------- test : unittest.TestCase The test that is starting. start_time : datetime An internal parameter to allow the parallel test runner to set the actual start time of a test run in a subprocess. """ if start_time is None: start_time = datetime.utcnow() self._test_timing[self._testcase_to_key(test)] = start_time self._mirror_output = False self._setup_stdout() self.testsRun += 1 for handler in self._handlers: handler.start_test(test) def stopTest(self, test): """Indicate that an individual test has completed. Parameters ---------- test : unittest.TestCase The test that has completed. """ for handler in self._handlers: handler.stop_test(test) self._restore_stdout() self._mirror_output = False def startTestRun(self): """Indicate that the test run is starting. """ for handler in self._handlers: handler.start_test_run() def stopTestRun(self): """Indicate that the test run has completed. """ for handler in self._handlers: handler.stop_test_run() def add_result(self, result): """Add an already-constructed :class:`~.TestResult` to this :class:`~.ResultCollector`. This may be used when collecting results created by other ResultCollectors (e.g. in subprocesses). """ for handler in self._handlers: handler(result) if self._successful and result.status not in _successful_results: self._successful = False def _handle_result(self, test, status, exception=None, message=None): """Create a :class:`~.TestResult` and add it to this :class:`~ResultCollector`. Parameters ---------- test : unittest.TestCase The test that this result will represent. status : haas.result.TestCompletionStatus The status of the test. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. message : str Optional message associated with the result (e.g. skip reason). """ if self.buffer: stderr = self._stderr_buffer.getvalue() stdout = self._stdout_buffer.getvalue() else: stderr = stdout = None started_time = self._test_timing.get(self._testcase_to_key(test)) if started_time is None and isinstance(test, ErrorHolder): started_time = datetime.utcnow() elif started_time is None: raise RuntimeError( 'Missing test start! Please report this error as a bug in ' 'haas.') completion_time = datetime.utcnow() duration = TestDuration(started_time, completion_time) result = TestResult.from_test_case( test, status, duration=duration, exception=exception, message=message, stdout=stdout, stderr=stderr, ) self.add_result(result) return result @failfast def addError(self, test, exception): """Register that a test ended in an error. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.error, exception=exception) self.errors.append(result) self._mirror_output = True @failfast def addFailure(self, test, exception): """Register that a test ended with a failure. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.failure, exception=exception) self.failures.append(result) self._mirror_output = True def addSuccess(self, test): """Register that a test ended in success. Parameters ---------- test : unittest.TestCase The test that has completed. """ self._handle_result(test, TestCompletionStatus.success) def addSkip(self, test, reason): """Register that a test that was skipped. Parameters ---------- test : unittest.TestCase The test that has completed. reason : str The reason the test was skipped. """ result = self._handle_result( test, TestCompletionStatus.skipped, message=reason) self.skipped.append(result) @failfast def addUnexpectedSuccess(self, test): """Register a test that passed unexpectedly. Parameters ---------- test : unittest.TestCase The test that has completed. """ result = self._handle_result( test, TestCompletionStatus.unexpected_success) self.unexpectedSuccesses.append(result) def wasSuccessful(self): """Return ``True`` if the run was successful. """ return self._successful def stop(self): """Set the ``shouldStop`` flag, used by the test cases to determine if they should terminate early. """ self.shouldStop = True
scalative/haas
haas/result.py
ResultCollector.addUnexpectedSuccess
python
def addUnexpectedSuccess(self, test): result = self._handle_result( test, TestCompletionStatus.unexpected_success) self.unexpectedSuccesses.append(result)
Register a test that passed unexpectedly. Parameters ---------- test : unittest.TestCase The test that has completed.
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L596-L607
[ "def _handle_result(self, test, status, exception=None, message=None):\n \"\"\"Create a :class:`~.TestResult` and add it to this\n :class:`~ResultCollector`.\n\n Parameters\n ----------\n test : unittest.TestCase\n The test that this result will represent.\n status : haas.result.TestComplet...
class ResultCollector(object): """Collecter for test results. This handles creating :class:`~.TestResult` instances and handing them off the registered result output handlers. """ # Temporary compatibility with unittest's runner separator2 = separator2 def __init__(self, buffer=False, failfast=False): self.buffer = buffer self.failfast = failfast self._result_handlers = [] self._sorted_handlers = None self.testsRun = 0 self.expectedFailures = [] self.unexpectedSuccesses = [] self.skipped = [] self.failures = [] self.errors = [] self.shouldStop = False self._successful = True self._mirror_output = False self._stderr_buffer = None self._stdout_buffer = None self._original_stderr = sys.stderr self._original_stdout = sys.stdout self._test_timing = {} @property def _handlers(self): if self._sorted_handlers is None: from .plugins.result_handler import sort_result_handlers self._sorted_handlers = sort_result_handlers(self._result_handlers) return self._sorted_handlers @staticmethod def _testcase_to_key(test): return (type(test), test._testMethodName) def _setup_stdout(self): """Hook stdout and stderr if buffering is enabled. """ if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = StringIO() self._stdout_buffer = StringIO() sys.stdout = self._stdout_buffer sys.stderr = self._stderr_buffer def _restore_stdout(self): """Unhook stdout and stderr if buffering is enabled. """ if self.buffer: if self._mirror_output: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' self._original_stdout.write(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' self._original_stderr.write(STDERR_LINE % error) sys.stdout = self._original_stdout sys.stderr = self._original_stderr self._stdout_buffer.seek(0) self._stdout_buffer.truncate() self._stderr_buffer.seek(0) self._stderr_buffer.truncate() def printErrors(self): # pragma: no cover # FIXME: Remove pass def add_result_handler(self, handler): """Register a new result handler. """ self._result_handlers.append(handler) # Reset sorted handlers if self._sorted_handlers: self._sorted_handlers = None def startTest(self, test, start_time=None): """Indicate that an individual test is starting. Parameters ---------- test : unittest.TestCase The test that is starting. start_time : datetime An internal parameter to allow the parallel test runner to set the actual start time of a test run in a subprocess. """ if start_time is None: start_time = datetime.utcnow() self._test_timing[self._testcase_to_key(test)] = start_time self._mirror_output = False self._setup_stdout() self.testsRun += 1 for handler in self._handlers: handler.start_test(test) def stopTest(self, test): """Indicate that an individual test has completed. Parameters ---------- test : unittest.TestCase The test that has completed. """ for handler in self._handlers: handler.stop_test(test) self._restore_stdout() self._mirror_output = False def startTestRun(self): """Indicate that the test run is starting. """ for handler in self._handlers: handler.start_test_run() def stopTestRun(self): """Indicate that the test run has completed. """ for handler in self._handlers: handler.stop_test_run() def add_result(self, result): """Add an already-constructed :class:`~.TestResult` to this :class:`~.ResultCollector`. This may be used when collecting results created by other ResultCollectors (e.g. in subprocesses). """ for handler in self._handlers: handler(result) if self._successful and result.status not in _successful_results: self._successful = False def _handle_result(self, test, status, exception=None, message=None): """Create a :class:`~.TestResult` and add it to this :class:`~ResultCollector`. Parameters ---------- test : unittest.TestCase The test that this result will represent. status : haas.result.TestCompletionStatus The status of the test. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. message : str Optional message associated with the result (e.g. skip reason). """ if self.buffer: stderr = self._stderr_buffer.getvalue() stdout = self._stdout_buffer.getvalue() else: stderr = stdout = None started_time = self._test_timing.get(self._testcase_to_key(test)) if started_time is None and isinstance(test, ErrorHolder): started_time = datetime.utcnow() elif started_time is None: raise RuntimeError( 'Missing test start! Please report this error as a bug in ' 'haas.') completion_time = datetime.utcnow() duration = TestDuration(started_time, completion_time) result = TestResult.from_test_case( test, status, duration=duration, exception=exception, message=message, stdout=stdout, stderr=stderr, ) self.add_result(result) return result @failfast def addError(self, test, exception): """Register that a test ended in an error. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.error, exception=exception) self.errors.append(result) self._mirror_output = True @failfast def addFailure(self, test, exception): """Register that a test ended with a failure. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.failure, exception=exception) self.failures.append(result) self._mirror_output = True def addSuccess(self, test): """Register that a test ended in success. Parameters ---------- test : unittest.TestCase The test that has completed. """ self._handle_result(test, TestCompletionStatus.success) def addSkip(self, test, reason): """Register that a test that was skipped. Parameters ---------- test : unittest.TestCase The test that has completed. reason : str The reason the test was skipped. """ result = self._handle_result( test, TestCompletionStatus.skipped, message=reason) self.skipped.append(result) def addExpectedFailure(self, test, exception): """Register that a test that failed and was expected to fail. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = self._handle_result( test, TestCompletionStatus.expected_failure, exception=exception) self.expectedFailures.append(result) @failfast def wasSuccessful(self): """Return ``True`` if the run was successful. """ return self._successful def stop(self): """Set the ``shouldStop`` flag, used by the test cases to determine if they should terminate early. """ self.shouldStop = True
scalative/haas
haas/plugin_manager.py
PluginManager.add_plugin_arguments
python
def add_plugin_arguments(self, parser): for manager in self.hook_managers.values(): if len(list(manager)) == 0: continue manager.map(self._add_hook_extension_arguments, parser) for namespace, manager in self.driver_managers.items(): choices = list(sorted(manager.names())) if len(choices) == 0: continue option, dest = self._namespace_to_option(namespace) parser.add_argument( option, help=self._help[namespace], dest=dest, choices=choices, default='default') option_prefix = '{0}-'.format(option) dest_prefix = '{0}_'.format(dest) manager.map(self._add_driver_extension_arguments, parser, option_prefix, dest_prefix)
Add plugin arguments to argument parser. Parameters ---------- parser : argparse.ArgumentParser The main haas ArgumentParser.
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugin_manager.py#L105-L129
[ "def _namespace_to_option(self, namespace):\n parts = self._namespace_to_option_parts[namespace]\n option = '--{0}'.format('-'.join(parts))\n dest = '_'.join(parts)\n return option, dest\n" ]
class PluginManager(object): ENVIRONMENT_HOOK = 'haas.hooks.environment' RESULT_HANDLERS = 'haas.result.handler' TEST_RUNNER = 'haas.runner' TEST_DISCOVERY = 'haas.discovery' _help = { TEST_DISCOVERY: 'The test discovery implementation to use.', TEST_RUNNER: 'Test runner implementation to use.', RESULT_HANDLERS: 'Test result handler implementation to use.', } _namespace_to_option_parts = { TEST_DISCOVERY: ['discovery'], TEST_RUNNER: ['runner'], RESULT_HANDLERS: ['result', 'handler'], } def __init__(self): self.hook_managers = OrderedDict() self.hook_managers[self.ENVIRONMENT_HOOK] = ExtensionManager( namespace=self.ENVIRONMENT_HOOK, ) self.hook_managers[self.RESULT_HANDLERS] = ExtensionManager( namespace=self.RESULT_HANDLERS, ) self.driver_managers = OrderedDict() self.driver_managers[self.TEST_DISCOVERY] = ExtensionManager( namespace=self.TEST_DISCOVERY, ) self.driver_managers[self.TEST_RUNNER] = ExtensionManager( namespace=self.TEST_RUNNER, ) @classmethod def testing_plugin_manager(cls, hook_managers, driver_managers): """Create a fabricated plugin manager for testing. """ plugin_manager = cls.__new__(cls) plugin_manager.hook_managers = OrderedDict(hook_managers) plugin_manager.driver_managers = OrderedDict(driver_managers) return plugin_manager def _hook_extension_option_prefix(self, extension): name = uncamelcase(extension.name, sep='-').replace('_', '-') option_prefix = '--with-{0}'.format(name) dest_prefix = name.replace('-', '_') return option_prefix, dest_prefix def _namespace_to_option(self, namespace): parts = self._namespace_to_option_parts[namespace] option = '--{0}'.format('-'.join(parts)) dest = '_'.join(parts) return option, dest def _add_hook_extension_arguments(self, extension, parser): option_prefix, dest_prefix = self._hook_extension_option_prefix( extension) extension.plugin.add_parser_arguments( parser, extension.name, option_prefix, dest_prefix) def _create_hook_plugin(self, extension, args, **kwargs): option_prefix, dest_prefix = self._hook_extension_option_prefix( extension) plugin = extension.plugin.from_args( args, extension.name, dest_prefix, **kwargs) if plugin is not None and plugin.enabled: return plugin return None def _add_driver_extension_arguments(self, extension, parser, option_prefix, dest_prefix): extension.plugin.add_parser_arguments( parser, option_prefix, dest_prefix) def get_enabled_hook_plugins(self, hook, args, **kwargs): """Get enabled plugins for specified hook name. """ manager = self.hook_managers[hook] if len(list(manager)) == 0: return [] return [ plugin for plugin in manager.map( self._create_hook_plugin, args, **kwargs) if plugin is not None ] def get_driver(self, namespace, parsed_args, **kwargs): """Get mutually-exlusive plugin for plugin namespace. """ option, dest = self._namespace_to_option(namespace) dest_prefix = '{0}_'.format(dest) driver_name = getattr(parsed_args, dest, 'default') driver_extension = self.driver_managers[namespace][driver_name] return driver_extension.plugin.from_args( parsed_args, dest_prefix, **kwargs)
scalative/haas
haas/plugin_manager.py
PluginManager.get_enabled_hook_plugins
python
def get_enabled_hook_plugins(self, hook, args, **kwargs): manager = self.hook_managers[hook] if len(list(manager)) == 0: return [] return [ plugin for plugin in manager.map( self._create_hook_plugin, args, **kwargs) if plugin is not None ]
Get enabled plugins for specified hook name.
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugin_manager.py#L131-L142
null
class PluginManager(object): ENVIRONMENT_HOOK = 'haas.hooks.environment' RESULT_HANDLERS = 'haas.result.handler' TEST_RUNNER = 'haas.runner' TEST_DISCOVERY = 'haas.discovery' _help = { TEST_DISCOVERY: 'The test discovery implementation to use.', TEST_RUNNER: 'Test runner implementation to use.', RESULT_HANDLERS: 'Test result handler implementation to use.', } _namespace_to_option_parts = { TEST_DISCOVERY: ['discovery'], TEST_RUNNER: ['runner'], RESULT_HANDLERS: ['result', 'handler'], } def __init__(self): self.hook_managers = OrderedDict() self.hook_managers[self.ENVIRONMENT_HOOK] = ExtensionManager( namespace=self.ENVIRONMENT_HOOK, ) self.hook_managers[self.RESULT_HANDLERS] = ExtensionManager( namespace=self.RESULT_HANDLERS, ) self.driver_managers = OrderedDict() self.driver_managers[self.TEST_DISCOVERY] = ExtensionManager( namespace=self.TEST_DISCOVERY, ) self.driver_managers[self.TEST_RUNNER] = ExtensionManager( namespace=self.TEST_RUNNER, ) @classmethod def testing_plugin_manager(cls, hook_managers, driver_managers): """Create a fabricated plugin manager for testing. """ plugin_manager = cls.__new__(cls) plugin_manager.hook_managers = OrderedDict(hook_managers) plugin_manager.driver_managers = OrderedDict(driver_managers) return plugin_manager def _hook_extension_option_prefix(self, extension): name = uncamelcase(extension.name, sep='-').replace('_', '-') option_prefix = '--with-{0}'.format(name) dest_prefix = name.replace('-', '_') return option_prefix, dest_prefix def _namespace_to_option(self, namespace): parts = self._namespace_to_option_parts[namespace] option = '--{0}'.format('-'.join(parts)) dest = '_'.join(parts) return option, dest def _add_hook_extension_arguments(self, extension, parser): option_prefix, dest_prefix = self._hook_extension_option_prefix( extension) extension.plugin.add_parser_arguments( parser, extension.name, option_prefix, dest_prefix) def _create_hook_plugin(self, extension, args, **kwargs): option_prefix, dest_prefix = self._hook_extension_option_prefix( extension) plugin = extension.plugin.from_args( args, extension.name, dest_prefix, **kwargs) if plugin is not None and plugin.enabled: return plugin return None def _add_driver_extension_arguments(self, extension, parser, option_prefix, dest_prefix): extension.plugin.add_parser_arguments( parser, option_prefix, dest_prefix) def add_plugin_arguments(self, parser): """Add plugin arguments to argument parser. Parameters ---------- parser : argparse.ArgumentParser The main haas ArgumentParser. """ for manager in self.hook_managers.values(): if len(list(manager)) == 0: continue manager.map(self._add_hook_extension_arguments, parser) for namespace, manager in self.driver_managers.items(): choices = list(sorted(manager.names())) if len(choices) == 0: continue option, dest = self._namespace_to_option(namespace) parser.add_argument( option, help=self._help[namespace], dest=dest, choices=choices, default='default') option_prefix = '{0}-'.format(option) dest_prefix = '{0}_'.format(dest) manager.map(self._add_driver_extension_arguments, parser, option_prefix, dest_prefix) def get_driver(self, namespace, parsed_args, **kwargs): """Get mutually-exlusive plugin for plugin namespace. """ option, dest = self._namespace_to_option(namespace) dest_prefix = '{0}_'.format(dest) driver_name = getattr(parsed_args, dest, 'default') driver_extension = self.driver_managers[namespace][driver_name] return driver_extension.plugin.from_args( parsed_args, dest_prefix, **kwargs)
scalative/haas
haas/plugin_manager.py
PluginManager.get_driver
python
def get_driver(self, namespace, parsed_args, **kwargs): option, dest = self._namespace_to_option(namespace) dest_prefix = '{0}_'.format(dest) driver_name = getattr(parsed_args, dest, 'default') driver_extension = self.driver_managers[namespace][driver_name] return driver_extension.plugin.from_args( parsed_args, dest_prefix, **kwargs)
Get mutually-exlusive plugin for plugin namespace.
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugin_manager.py#L144-L153
[ "def _namespace_to_option(self, namespace):\n parts = self._namespace_to_option_parts[namespace]\n option = '--{0}'.format('-'.join(parts))\n dest = '_'.join(parts)\n return option, dest\n" ]
class PluginManager(object): ENVIRONMENT_HOOK = 'haas.hooks.environment' RESULT_HANDLERS = 'haas.result.handler' TEST_RUNNER = 'haas.runner' TEST_DISCOVERY = 'haas.discovery' _help = { TEST_DISCOVERY: 'The test discovery implementation to use.', TEST_RUNNER: 'Test runner implementation to use.', RESULT_HANDLERS: 'Test result handler implementation to use.', } _namespace_to_option_parts = { TEST_DISCOVERY: ['discovery'], TEST_RUNNER: ['runner'], RESULT_HANDLERS: ['result', 'handler'], } def __init__(self): self.hook_managers = OrderedDict() self.hook_managers[self.ENVIRONMENT_HOOK] = ExtensionManager( namespace=self.ENVIRONMENT_HOOK, ) self.hook_managers[self.RESULT_HANDLERS] = ExtensionManager( namespace=self.RESULT_HANDLERS, ) self.driver_managers = OrderedDict() self.driver_managers[self.TEST_DISCOVERY] = ExtensionManager( namespace=self.TEST_DISCOVERY, ) self.driver_managers[self.TEST_RUNNER] = ExtensionManager( namespace=self.TEST_RUNNER, ) @classmethod def testing_plugin_manager(cls, hook_managers, driver_managers): """Create a fabricated plugin manager for testing. """ plugin_manager = cls.__new__(cls) plugin_manager.hook_managers = OrderedDict(hook_managers) plugin_manager.driver_managers = OrderedDict(driver_managers) return plugin_manager def _hook_extension_option_prefix(self, extension): name = uncamelcase(extension.name, sep='-').replace('_', '-') option_prefix = '--with-{0}'.format(name) dest_prefix = name.replace('-', '_') return option_prefix, dest_prefix def _namespace_to_option(self, namespace): parts = self._namespace_to_option_parts[namespace] option = '--{0}'.format('-'.join(parts)) dest = '_'.join(parts) return option, dest def _add_hook_extension_arguments(self, extension, parser): option_prefix, dest_prefix = self._hook_extension_option_prefix( extension) extension.plugin.add_parser_arguments( parser, extension.name, option_prefix, dest_prefix) def _create_hook_plugin(self, extension, args, **kwargs): option_prefix, dest_prefix = self._hook_extension_option_prefix( extension) plugin = extension.plugin.from_args( args, extension.name, dest_prefix, **kwargs) if plugin is not None and plugin.enabled: return plugin return None def _add_driver_extension_arguments(self, extension, parser, option_prefix, dest_prefix): extension.plugin.add_parser_arguments( parser, option_prefix, dest_prefix) def add_plugin_arguments(self, parser): """Add plugin arguments to argument parser. Parameters ---------- parser : argparse.ArgumentParser The main haas ArgumentParser. """ for manager in self.hook_managers.values(): if len(list(manager)) == 0: continue manager.map(self._add_hook_extension_arguments, parser) for namespace, manager in self.driver_managers.items(): choices = list(sorted(manager.names())) if len(choices) == 0: continue option, dest = self._namespace_to_option(namespace) parser.add_argument( option, help=self._help[namespace], dest=dest, choices=choices, default='default') option_prefix = '{0}-'.format(option) dest_prefix = '{0}_'.format(dest) manager.map(self._add_driver_extension_arguments, parser, option_prefix, dest_prefix) def get_enabled_hook_plugins(self, hook, args, **kwargs): """Get enabled plugins for specified hook name. """ manager = self.hook_managers[hook] if len(list(manager)) == 0: return [] return [ plugin for plugin in manager.map( self._create_hook_plugin, args, **kwargs) if plugin is not None ]
scalative/haas
haas/plugins/discoverer.py
find_top_level_directory
python
def find_top_level_directory(start_directory): top_level = start_directory while os.path.isfile(os.path.join(top_level, '__init__.py')): top_level = os.path.dirname(top_level) if top_level == os.path.dirname(top_level): raise ValueError("Can't find top level directory") return os.path.abspath(top_level)
Finds the top-level directory of a project given a start directory inside the project. Parameters ---------- start_directory : str The directory in which test discovery will start.
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L92-L107
null
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals from fnmatch import fnmatch import logging import os import sys import traceback from haas.exceptions import DotInModuleNameError from haas.module_import_error import ModuleImportError from haas.suite import find_test_cases from haas.testing import unittest from haas.utils import get_module_by_name from .i_discoverer_plugin import IDiscovererPlugin logger = logging.getLogger(__name__) def _is_import_error_test(test): return isinstance(test, ModuleImportError) def _create_import_error_test(module_name): message = 'Unable to import module {0!r}\n{1}'.format( module_name, traceback.format_exc()) def test_error(self): raise ImportError(message) method_name = 'test_error' cls = type(ModuleImportError.__name__, (ModuleImportError, unittest.TestCase,), {method_name: test_error}) return cls(method_name) def get_relpath(top_level_directory, fullpath): normalized = os.path.normpath(fullpath) relpath = os.path.relpath(normalized, top_level_directory) if os.path.isabs(relpath) or relpath.startswith('..'): raise ValueError('Path not within project: {0}'.format(fullpath)) return relpath def match_path(filename, filepath, pattern): return fnmatch(filename, pattern) def get_module_name(top_level_directory, filepath): modulepath = os.path.splitext(os.path.normpath(filepath))[0] relpath = get_relpath(top_level_directory, modulepath) if '.' in relpath: raise DotInModuleNameError(relpath) return relpath.replace(os.path.sep, '.') def assert_start_importable(top_level_directory, start_directory): relpath = get_relpath(top_level_directory, start_directory) path = top_level_directory for component in relpath.split(os.path.sep): if component == '.': continue path = os.path.join(path, component) if path != top_level_directory and \ not os.path.isfile(os.path.join(path, '__init__.py')): raise ImportError('Start directory is not importable') def find_module_by_name(full_name): module_name = full_name module_attributes = [] while True: try: module = get_module_by_name(module_name) except ImportError: if '.' in module_name: module_name, attribute = module_name.rsplit('.', 1) module_attributes.append(attribute) else: raise else: break return module, list(reversed(module_attributes)) def filter_test_suite(suite, filter_name): """Filter test cases in a test suite by a substring in the full dotted test name. Parameters ---------- suite : haas.suite.TestSuite The test suite containing tests to be filtered. filter_name : str The substring of the full dotted name on which to filter. This should not contain a leading or trailing dot. """ filtered_cases = [] for test in find_test_cases(suite): type_ = type(test) name = '{0}.{1}.{2}'.format( type_.__module__, type_.__name__, test._testMethodName) filter_internal = '.{0}.'.format(filter_name) if _is_import_error_test(test) or \ filter_internal in name or \ name.endswith(filter_internal[:-1]): filtered_cases.append(test) return filtered_cases class Discoverer(IDiscovererPlugin): """The ``Discoverer`` is responsible for finding tests that can be loaded by a :class:`~haas.loader.Loader`. """ def __init__(self, loader, **kwargs): super(Discoverer, self).__init__(**kwargs) self._loader = loader @classmethod def from_args(cls, args, arg_prefix, loader): """Construct the discoverer from parsed command line arguments. Parameters ---------- args : argparse.Namespace The ``argparse.Namespace`` containing parsed arguments. arg_prefix : str The prefix used for arguments beloning solely to this plugin. loader : haas.loader.Loader The test loader used to construct TestCase and TestSuite instances. """ return cls(loader) @classmethod def add_parser_arguments(cls, parser, option_prefix, dest_prefix): """Add options for the plugin to the main argument parser. Parameters ---------- parser : argparse.ArgumentParser The parser to extend option_prefix : str The prefix that option strings added by this plugin should use. dest_prefix : str The prefix that ``dest`` strings for options added by this plugin should use. """ def discover(self, start, top_level_directory=None, pattern='test*.py'): """Do test case discovery. This is the top-level entry-point for test discovery. If the ``start`` argument is a drectory, then ``haas`` will discover all tests in the package contained in that directory. If the ``start`` argument is not a directory, it is assumed to be a package or module name and tests in the package or module are loaded. FIXME: This needs a better description. Parameters ---------- start : str The directory, package, module, class or test to load. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ logger.debug('Starting test discovery') if os.path.isdir(start): start_directory = start return self.discover_by_directory( start_directory, top_level_directory=top_level_directory, pattern=pattern) elif os.path.isfile(start): start_filepath = start return self.discover_by_file( start_filepath, top_level_directory=top_level_directory) else: package_or_module = start return self.discover_by_module( package_or_module, top_level_directory=top_level_directory, pattern=pattern) def discover_by_module(self, module_name, top_level_directory=None, pattern='test*.py'): """Find all tests in a package or module, or load a single test case if a class or test inside a module was specified. Parameters ---------- module_name : str The dotted package name, module name or TestCase class and test method. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ # If the top level directory is given, the module may only be # importable with that in the path. if top_level_directory is not None and \ top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) logger.debug('Discovering tests by module: module_name=%r, ' 'top_level_directory=%r, pattern=%r', module_name, top_level_directory, pattern) try: module, case_attributes = find_module_by_name(module_name) except ImportError: return self.discover_filtered_tests( module_name, top_level_directory=top_level_directory, pattern=pattern) dirname, basename = os.path.split(module.__file__) basename = os.path.splitext(basename)[0] if len(case_attributes) == 0 and basename == '__init__': # Discover in a package return self.discover_by_directory( dirname, top_level_directory, pattern=pattern) elif len(case_attributes) == 0: # Discover all in a module return self._loader.load_module(module) return self.discover_single_case(module, case_attributes) def discover_single_case(self, module, case_attributes): """Find and load a single TestCase or TestCase method from a module. Parameters ---------- module : module The imported Python module containing the TestCase to be loaded. case_attributes : list A list (length 1 or 2) of str. The first component must be the name of a TestCase subclass. The second component must be the name of a method in the TestCase. """ # Find single case case = module loader = self._loader for index, component in enumerate(case_attributes): case = getattr(case, component, None) if case is None: return loader.create_suite() elif loader.is_test_case(case): rest = case_attributes[index + 1:] if len(rest) > 1: raise ValueError('Too many components in module path') elif len(rest) == 1: return loader.create_suite( [loader.load_test(case, *rest)]) return loader.load_case(case) # No cases matched, return empty suite return loader.create_suite() def discover_by_directory(self, start_directory, top_level_directory=None, pattern='test*.py'): """Run test discovery in a directory. Parameters ---------- start_directory : str The package directory in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ start_directory = os.path.abspath(start_directory) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in directory: start_directory=%r, ' 'top_level_directory=%r, pattern=%r', start_directory, top_level_directory, pattern) assert_start_importable(top_level_directory, start_directory) if top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) tests = self._discover_tests( start_directory, top_level_directory, pattern) return self._loader.create_suite(list(tests)) def discover_by_file(self, start_filepath, top_level_directory=None): """Run test discovery on a single file. Parameters ---------- start_filepath : str The module file in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. """ start_filepath = os.path.abspath(start_filepath) start_directory = os.path.dirname(start_filepath) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in file: start_filepath=%r, ' 'top_level_directory=', start_filepath, top_level_directory) assert_start_importable(top_level_directory, start_directory) if top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) tests = self._load_from_file( start_filepath, top_level_directory) return self._loader.create_suite(list(tests)) def _load_from_file(self, filepath, top_level_directory): module_name = get_module_name(top_level_directory, filepath) logger.debug('Loading tests from %r', module_name) try: module = get_module_by_name(module_name) except Exception: test = _create_import_error_test(module_name) else: # No exceptions on module import # Load tests return self._loader.load_module(module) # Create the test suite containing handled exception on import return self._loader.create_suite((test,)) def _discover_tests(self, start_directory, top_level_directory, pattern): for curdir, dirnames, filenames in os.walk(start_directory): logger.debug('Discovering tests in %r', curdir) dirnames[:] = [ dirname for dirname in dirnames if os.path.exists(os.path.join(curdir, dirname, '__init__.py')) ] for filename in filenames: filepath = os.path.join(curdir, filename) if not match_path(filename, filepath, pattern): logger.debug('Skipping %r', filepath) continue try: yield self._load_from_file(filepath, top_level_directory) except DotInModuleNameError: logger.info( 'Unexpected dot in module or package name: %r', filepath) continue def discover_filtered_tests(self, filter_name, top_level_directory=None, pattern='test*.py'): """Find all tests whose package, module, class or method names match the ``filter_name`` string. Parameters ---------- filter_name : str A subsection of the full dotted test name. This can be simply a test method name (e.g. ``test_some_method``), the TestCase class name (e.g. ``TestMyClass``), a module name (e.g. ``test_module``), a subpackage (e.g. ``tests``). It may also be a dotted combination of the above (e.g. ``TestMyClass.test_some_method``). top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ if top_level_directory is None: top_level_directory = find_top_level_directory( os.getcwd()) logger.debug('Discovering filtered tests: filter_name=%r, ' 'top_level_directory=%r, pattern=%r', top_level_directory, top_level_directory, pattern) suite = self.discover_by_directory( top_level_directory, top_level_directory=top_level_directory, pattern=pattern) return self._loader.create_suite( filter_test_suite(suite, filter_name=filter_name))
scalative/haas
haas/plugins/discoverer.py
Discoverer.discover
python
def discover(self, start, top_level_directory=None, pattern='test*.py'): logger.debug('Starting test discovery') if os.path.isdir(start): start_directory = start return self.discover_by_directory( start_directory, top_level_directory=top_level_directory, pattern=pattern) elif os.path.isfile(start): start_filepath = start return self.discover_by_file( start_filepath, top_level_directory=top_level_directory) else: package_or_module = start return self.discover_by_module( package_or_module, top_level_directory=top_level_directory, pattern=pattern)
Do test case discovery. This is the top-level entry-point for test discovery. If the ``start`` argument is a drectory, then ``haas`` will discover all tests in the package contained in that directory. If the ``start`` argument is not a directory, it is assumed to be a package or module name and tests in the package or module are loaded. FIXME: This needs a better description. Parameters ---------- start : str The directory, package, module, class or test to load. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests.
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L178-L219
[ "def discover_by_directory(self, start_directory, top_level_directory=None,\n pattern='test*.py'):\n \"\"\"Run test discovery in a directory.\n\n Parameters\n ----------\n start_directory : str\n The package directory in which to start test discovery.\n top_level_direc...
class Discoverer(IDiscovererPlugin): """The ``Discoverer`` is responsible for finding tests that can be loaded by a :class:`~haas.loader.Loader`. """ def __init__(self, loader, **kwargs): super(Discoverer, self).__init__(**kwargs) self._loader = loader @classmethod def from_args(cls, args, arg_prefix, loader): """Construct the discoverer from parsed command line arguments. Parameters ---------- args : argparse.Namespace The ``argparse.Namespace`` containing parsed arguments. arg_prefix : str The prefix used for arguments beloning solely to this plugin. loader : haas.loader.Loader The test loader used to construct TestCase and TestSuite instances. """ return cls(loader) @classmethod def add_parser_arguments(cls, parser, option_prefix, dest_prefix): """Add options for the plugin to the main argument parser. Parameters ---------- parser : argparse.ArgumentParser The parser to extend option_prefix : str The prefix that option strings added by this plugin should use. dest_prefix : str The prefix that ``dest`` strings for options added by this plugin should use. """ def discover_by_module(self, module_name, top_level_directory=None, pattern='test*.py'): """Find all tests in a package or module, or load a single test case if a class or test inside a module was specified. Parameters ---------- module_name : str The dotted package name, module name or TestCase class and test method. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ # If the top level directory is given, the module may only be # importable with that in the path. if top_level_directory is not None and \ top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) logger.debug('Discovering tests by module: module_name=%r, ' 'top_level_directory=%r, pattern=%r', module_name, top_level_directory, pattern) try: module, case_attributes = find_module_by_name(module_name) except ImportError: return self.discover_filtered_tests( module_name, top_level_directory=top_level_directory, pattern=pattern) dirname, basename = os.path.split(module.__file__) basename = os.path.splitext(basename)[0] if len(case_attributes) == 0 and basename == '__init__': # Discover in a package return self.discover_by_directory( dirname, top_level_directory, pattern=pattern) elif len(case_attributes) == 0: # Discover all in a module return self._loader.load_module(module) return self.discover_single_case(module, case_attributes) def discover_single_case(self, module, case_attributes): """Find and load a single TestCase or TestCase method from a module. Parameters ---------- module : module The imported Python module containing the TestCase to be loaded. case_attributes : list A list (length 1 or 2) of str. The first component must be the name of a TestCase subclass. The second component must be the name of a method in the TestCase. """ # Find single case case = module loader = self._loader for index, component in enumerate(case_attributes): case = getattr(case, component, None) if case is None: return loader.create_suite() elif loader.is_test_case(case): rest = case_attributes[index + 1:] if len(rest) > 1: raise ValueError('Too many components in module path') elif len(rest) == 1: return loader.create_suite( [loader.load_test(case, *rest)]) return loader.load_case(case) # No cases matched, return empty suite return loader.create_suite() def discover_by_directory(self, start_directory, top_level_directory=None, pattern='test*.py'): """Run test discovery in a directory. Parameters ---------- start_directory : str The package directory in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ start_directory = os.path.abspath(start_directory) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in directory: start_directory=%r, ' 'top_level_directory=%r, pattern=%r', start_directory, top_level_directory, pattern) assert_start_importable(top_level_directory, start_directory) if top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) tests = self._discover_tests( start_directory, top_level_directory, pattern) return self._loader.create_suite(list(tests)) def discover_by_file(self, start_filepath, top_level_directory=None): """Run test discovery on a single file. Parameters ---------- start_filepath : str The module file in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. """ start_filepath = os.path.abspath(start_filepath) start_directory = os.path.dirname(start_filepath) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in file: start_filepath=%r, ' 'top_level_directory=', start_filepath, top_level_directory) assert_start_importable(top_level_directory, start_directory) if top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) tests = self._load_from_file( start_filepath, top_level_directory) return self._loader.create_suite(list(tests)) def _load_from_file(self, filepath, top_level_directory): module_name = get_module_name(top_level_directory, filepath) logger.debug('Loading tests from %r', module_name) try: module = get_module_by_name(module_name) except Exception: test = _create_import_error_test(module_name) else: # No exceptions on module import # Load tests return self._loader.load_module(module) # Create the test suite containing handled exception on import return self._loader.create_suite((test,)) def _discover_tests(self, start_directory, top_level_directory, pattern): for curdir, dirnames, filenames in os.walk(start_directory): logger.debug('Discovering tests in %r', curdir) dirnames[:] = [ dirname for dirname in dirnames if os.path.exists(os.path.join(curdir, dirname, '__init__.py')) ] for filename in filenames: filepath = os.path.join(curdir, filename) if not match_path(filename, filepath, pattern): logger.debug('Skipping %r', filepath) continue try: yield self._load_from_file(filepath, top_level_directory) except DotInModuleNameError: logger.info( 'Unexpected dot in module or package name: %r', filepath) continue def discover_filtered_tests(self, filter_name, top_level_directory=None, pattern='test*.py'): """Find all tests whose package, module, class or method names match the ``filter_name`` string. Parameters ---------- filter_name : str A subsection of the full dotted test name. This can be simply a test method name (e.g. ``test_some_method``), the TestCase class name (e.g. ``TestMyClass``), a module name (e.g. ``test_module``), a subpackage (e.g. ``tests``). It may also be a dotted combination of the above (e.g. ``TestMyClass.test_some_method``). top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ if top_level_directory is None: top_level_directory = find_top_level_directory( os.getcwd()) logger.debug('Discovering filtered tests: filter_name=%r, ' 'top_level_directory=%r, pattern=%r', top_level_directory, top_level_directory, pattern) suite = self.discover_by_directory( top_level_directory, top_level_directory=top_level_directory, pattern=pattern) return self._loader.create_suite( filter_test_suite(suite, filter_name=filter_name))
scalative/haas
haas/plugins/discoverer.py
Discoverer.discover_by_module
python
def discover_by_module(self, module_name, top_level_directory=None, pattern='test*.py'): # If the top level directory is given, the module may only be # importable with that in the path. if top_level_directory is not None and \ top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) logger.debug('Discovering tests by module: module_name=%r, ' 'top_level_directory=%r, pattern=%r', module_name, top_level_directory, pattern) try: module, case_attributes = find_module_by_name(module_name) except ImportError: return self.discover_filtered_tests( module_name, top_level_directory=top_level_directory, pattern=pattern) dirname, basename = os.path.split(module.__file__) basename = os.path.splitext(basename)[0] if len(case_attributes) == 0 and basename == '__init__': # Discover in a package return self.discover_by_directory( dirname, top_level_directory, pattern=pattern) elif len(case_attributes) == 0: # Discover all in a module return self._loader.load_module(module) return self.discover_single_case(module, case_attributes)
Find all tests in a package or module, or load a single test case if a class or test inside a module was specified. Parameters ---------- module_name : str The dotted package name, module name or TestCase class and test method. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests.
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L221-L266
[ "def find_module_by_name(full_name):\n module_name = full_name\n module_attributes = []\n while True:\n try:\n module = get_module_by_name(module_name)\n except ImportError:\n if '.' in module_name:\n module_name, attribute = module_name.rsplit('.', 1)\n ...
class Discoverer(IDiscovererPlugin): """The ``Discoverer`` is responsible for finding tests that can be loaded by a :class:`~haas.loader.Loader`. """ def __init__(self, loader, **kwargs): super(Discoverer, self).__init__(**kwargs) self._loader = loader @classmethod def from_args(cls, args, arg_prefix, loader): """Construct the discoverer from parsed command line arguments. Parameters ---------- args : argparse.Namespace The ``argparse.Namespace`` containing parsed arguments. arg_prefix : str The prefix used for arguments beloning solely to this plugin. loader : haas.loader.Loader The test loader used to construct TestCase and TestSuite instances. """ return cls(loader) @classmethod def add_parser_arguments(cls, parser, option_prefix, dest_prefix): """Add options for the plugin to the main argument parser. Parameters ---------- parser : argparse.ArgumentParser The parser to extend option_prefix : str The prefix that option strings added by this plugin should use. dest_prefix : str The prefix that ``dest`` strings for options added by this plugin should use. """ def discover(self, start, top_level_directory=None, pattern='test*.py'): """Do test case discovery. This is the top-level entry-point for test discovery. If the ``start`` argument is a drectory, then ``haas`` will discover all tests in the package contained in that directory. If the ``start`` argument is not a directory, it is assumed to be a package or module name and tests in the package or module are loaded. FIXME: This needs a better description. Parameters ---------- start : str The directory, package, module, class or test to load. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ logger.debug('Starting test discovery') if os.path.isdir(start): start_directory = start return self.discover_by_directory( start_directory, top_level_directory=top_level_directory, pattern=pattern) elif os.path.isfile(start): start_filepath = start return self.discover_by_file( start_filepath, top_level_directory=top_level_directory) else: package_or_module = start return self.discover_by_module( package_or_module, top_level_directory=top_level_directory, pattern=pattern) def discover_single_case(self, module, case_attributes): """Find and load a single TestCase or TestCase method from a module. Parameters ---------- module : module The imported Python module containing the TestCase to be loaded. case_attributes : list A list (length 1 or 2) of str. The first component must be the name of a TestCase subclass. The second component must be the name of a method in the TestCase. """ # Find single case case = module loader = self._loader for index, component in enumerate(case_attributes): case = getattr(case, component, None) if case is None: return loader.create_suite() elif loader.is_test_case(case): rest = case_attributes[index + 1:] if len(rest) > 1: raise ValueError('Too many components in module path') elif len(rest) == 1: return loader.create_suite( [loader.load_test(case, *rest)]) return loader.load_case(case) # No cases matched, return empty suite return loader.create_suite() def discover_by_directory(self, start_directory, top_level_directory=None, pattern='test*.py'): """Run test discovery in a directory. Parameters ---------- start_directory : str The package directory in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ start_directory = os.path.abspath(start_directory) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in directory: start_directory=%r, ' 'top_level_directory=%r, pattern=%r', start_directory, top_level_directory, pattern) assert_start_importable(top_level_directory, start_directory) if top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) tests = self._discover_tests( start_directory, top_level_directory, pattern) return self._loader.create_suite(list(tests)) def discover_by_file(self, start_filepath, top_level_directory=None): """Run test discovery on a single file. Parameters ---------- start_filepath : str The module file in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. """ start_filepath = os.path.abspath(start_filepath) start_directory = os.path.dirname(start_filepath) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in file: start_filepath=%r, ' 'top_level_directory=', start_filepath, top_level_directory) assert_start_importable(top_level_directory, start_directory) if top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) tests = self._load_from_file( start_filepath, top_level_directory) return self._loader.create_suite(list(tests)) def _load_from_file(self, filepath, top_level_directory): module_name = get_module_name(top_level_directory, filepath) logger.debug('Loading tests from %r', module_name) try: module = get_module_by_name(module_name) except Exception: test = _create_import_error_test(module_name) else: # No exceptions on module import # Load tests return self._loader.load_module(module) # Create the test suite containing handled exception on import return self._loader.create_suite((test,)) def _discover_tests(self, start_directory, top_level_directory, pattern): for curdir, dirnames, filenames in os.walk(start_directory): logger.debug('Discovering tests in %r', curdir) dirnames[:] = [ dirname for dirname in dirnames if os.path.exists(os.path.join(curdir, dirname, '__init__.py')) ] for filename in filenames: filepath = os.path.join(curdir, filename) if not match_path(filename, filepath, pattern): logger.debug('Skipping %r', filepath) continue try: yield self._load_from_file(filepath, top_level_directory) except DotInModuleNameError: logger.info( 'Unexpected dot in module or package name: %r', filepath) continue def discover_filtered_tests(self, filter_name, top_level_directory=None, pattern='test*.py'): """Find all tests whose package, module, class or method names match the ``filter_name`` string. Parameters ---------- filter_name : str A subsection of the full dotted test name. This can be simply a test method name (e.g. ``test_some_method``), the TestCase class name (e.g. ``TestMyClass``), a module name (e.g. ``test_module``), a subpackage (e.g. ``tests``). It may also be a dotted combination of the above (e.g. ``TestMyClass.test_some_method``). top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ if top_level_directory is None: top_level_directory = find_top_level_directory( os.getcwd()) logger.debug('Discovering filtered tests: filter_name=%r, ' 'top_level_directory=%r, pattern=%r', top_level_directory, top_level_directory, pattern) suite = self.discover_by_directory( top_level_directory, top_level_directory=top_level_directory, pattern=pattern) return self._loader.create_suite( filter_test_suite(suite, filter_name=filter_name))
scalative/haas
haas/plugins/discoverer.py
Discoverer.discover_single_case
python
def discover_single_case(self, module, case_attributes): # Find single case case = module loader = self._loader for index, component in enumerate(case_attributes): case = getattr(case, component, None) if case is None: return loader.create_suite() elif loader.is_test_case(case): rest = case_attributes[index + 1:] if len(rest) > 1: raise ValueError('Too many components in module path') elif len(rest) == 1: return loader.create_suite( [loader.load_test(case, *rest)]) return loader.load_case(case) # No cases matched, return empty suite return loader.create_suite()
Find and load a single TestCase or TestCase method from a module. Parameters ---------- module : module The imported Python module containing the TestCase to be loaded. case_attributes : list A list (length 1 or 2) of str. The first component must be the name of a TestCase subclass. The second component must be the name of a method in the TestCase.
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L268-L299
null
class Discoverer(IDiscovererPlugin): """The ``Discoverer`` is responsible for finding tests that can be loaded by a :class:`~haas.loader.Loader`. """ def __init__(self, loader, **kwargs): super(Discoverer, self).__init__(**kwargs) self._loader = loader @classmethod def from_args(cls, args, arg_prefix, loader): """Construct the discoverer from parsed command line arguments. Parameters ---------- args : argparse.Namespace The ``argparse.Namespace`` containing parsed arguments. arg_prefix : str The prefix used for arguments beloning solely to this plugin. loader : haas.loader.Loader The test loader used to construct TestCase and TestSuite instances. """ return cls(loader) @classmethod def add_parser_arguments(cls, parser, option_prefix, dest_prefix): """Add options for the plugin to the main argument parser. Parameters ---------- parser : argparse.ArgumentParser The parser to extend option_prefix : str The prefix that option strings added by this plugin should use. dest_prefix : str The prefix that ``dest`` strings for options added by this plugin should use. """ def discover(self, start, top_level_directory=None, pattern='test*.py'): """Do test case discovery. This is the top-level entry-point for test discovery. If the ``start`` argument is a drectory, then ``haas`` will discover all tests in the package contained in that directory. If the ``start`` argument is not a directory, it is assumed to be a package or module name and tests in the package or module are loaded. FIXME: This needs a better description. Parameters ---------- start : str The directory, package, module, class or test to load. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ logger.debug('Starting test discovery') if os.path.isdir(start): start_directory = start return self.discover_by_directory( start_directory, top_level_directory=top_level_directory, pattern=pattern) elif os.path.isfile(start): start_filepath = start return self.discover_by_file( start_filepath, top_level_directory=top_level_directory) else: package_or_module = start return self.discover_by_module( package_or_module, top_level_directory=top_level_directory, pattern=pattern) def discover_by_module(self, module_name, top_level_directory=None, pattern='test*.py'): """Find all tests in a package or module, or load a single test case if a class or test inside a module was specified. Parameters ---------- module_name : str The dotted package name, module name or TestCase class and test method. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ # If the top level directory is given, the module may only be # importable with that in the path. if top_level_directory is not None and \ top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) logger.debug('Discovering tests by module: module_name=%r, ' 'top_level_directory=%r, pattern=%r', module_name, top_level_directory, pattern) try: module, case_attributes = find_module_by_name(module_name) except ImportError: return self.discover_filtered_tests( module_name, top_level_directory=top_level_directory, pattern=pattern) dirname, basename = os.path.split(module.__file__) basename = os.path.splitext(basename)[0] if len(case_attributes) == 0 and basename == '__init__': # Discover in a package return self.discover_by_directory( dirname, top_level_directory, pattern=pattern) elif len(case_attributes) == 0: # Discover all in a module return self._loader.load_module(module) return self.discover_single_case(module, case_attributes) def discover_by_directory(self, start_directory, top_level_directory=None, pattern='test*.py'): """Run test discovery in a directory. Parameters ---------- start_directory : str The package directory in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ start_directory = os.path.abspath(start_directory) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in directory: start_directory=%r, ' 'top_level_directory=%r, pattern=%r', start_directory, top_level_directory, pattern) assert_start_importable(top_level_directory, start_directory) if top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) tests = self._discover_tests( start_directory, top_level_directory, pattern) return self._loader.create_suite(list(tests)) def discover_by_file(self, start_filepath, top_level_directory=None): """Run test discovery on a single file. Parameters ---------- start_filepath : str The module file in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. """ start_filepath = os.path.abspath(start_filepath) start_directory = os.path.dirname(start_filepath) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in file: start_filepath=%r, ' 'top_level_directory=', start_filepath, top_level_directory) assert_start_importable(top_level_directory, start_directory) if top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) tests = self._load_from_file( start_filepath, top_level_directory) return self._loader.create_suite(list(tests)) def _load_from_file(self, filepath, top_level_directory): module_name = get_module_name(top_level_directory, filepath) logger.debug('Loading tests from %r', module_name) try: module = get_module_by_name(module_name) except Exception: test = _create_import_error_test(module_name) else: # No exceptions on module import # Load tests return self._loader.load_module(module) # Create the test suite containing handled exception on import return self._loader.create_suite((test,)) def _discover_tests(self, start_directory, top_level_directory, pattern): for curdir, dirnames, filenames in os.walk(start_directory): logger.debug('Discovering tests in %r', curdir) dirnames[:] = [ dirname for dirname in dirnames if os.path.exists(os.path.join(curdir, dirname, '__init__.py')) ] for filename in filenames: filepath = os.path.join(curdir, filename) if not match_path(filename, filepath, pattern): logger.debug('Skipping %r', filepath) continue try: yield self._load_from_file(filepath, top_level_directory) except DotInModuleNameError: logger.info( 'Unexpected dot in module or package name: %r', filepath) continue def discover_filtered_tests(self, filter_name, top_level_directory=None, pattern='test*.py'): """Find all tests whose package, module, class or method names match the ``filter_name`` string. Parameters ---------- filter_name : str A subsection of the full dotted test name. This can be simply a test method name (e.g. ``test_some_method``), the TestCase class name (e.g. ``TestMyClass``), a module name (e.g. ``test_module``), a subpackage (e.g. ``tests``). It may also be a dotted combination of the above (e.g. ``TestMyClass.test_some_method``). top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ if top_level_directory is None: top_level_directory = find_top_level_directory( os.getcwd()) logger.debug('Discovering filtered tests: filter_name=%r, ' 'top_level_directory=%r, pattern=%r', top_level_directory, top_level_directory, pattern) suite = self.discover_by_directory( top_level_directory, top_level_directory=top_level_directory, pattern=pattern) return self._loader.create_suite( filter_test_suite(suite, filter_name=filter_name))
scalative/haas
haas/plugins/discoverer.py
Discoverer.discover_by_directory
python
def discover_by_directory(self, start_directory, top_level_directory=None, pattern='test*.py'): start_directory = os.path.abspath(start_directory) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in directory: start_directory=%r, ' 'top_level_directory=%r, pattern=%r', start_directory, top_level_directory, pattern) assert_start_importable(top_level_directory, start_directory) if top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) tests = self._discover_tests( start_directory, top_level_directory, pattern) return self._loader.create_suite(list(tests))
Run test discovery in a directory. Parameters ---------- start_directory : str The package directory in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests.
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L301-L332
[ "def assert_start_importable(top_level_directory, start_directory):\n relpath = get_relpath(top_level_directory, start_directory)\n path = top_level_directory\n for component in relpath.split(os.path.sep):\n if component == '.':\n continue\n path = os.path.join(path, component)\n ...
class Discoverer(IDiscovererPlugin): """The ``Discoverer`` is responsible for finding tests that can be loaded by a :class:`~haas.loader.Loader`. """ def __init__(self, loader, **kwargs): super(Discoverer, self).__init__(**kwargs) self._loader = loader @classmethod def from_args(cls, args, arg_prefix, loader): """Construct the discoverer from parsed command line arguments. Parameters ---------- args : argparse.Namespace The ``argparse.Namespace`` containing parsed arguments. arg_prefix : str The prefix used for arguments beloning solely to this plugin. loader : haas.loader.Loader The test loader used to construct TestCase and TestSuite instances. """ return cls(loader) @classmethod def add_parser_arguments(cls, parser, option_prefix, dest_prefix): """Add options for the plugin to the main argument parser. Parameters ---------- parser : argparse.ArgumentParser The parser to extend option_prefix : str The prefix that option strings added by this plugin should use. dest_prefix : str The prefix that ``dest`` strings for options added by this plugin should use. """ def discover(self, start, top_level_directory=None, pattern='test*.py'): """Do test case discovery. This is the top-level entry-point for test discovery. If the ``start`` argument is a drectory, then ``haas`` will discover all tests in the package contained in that directory. If the ``start`` argument is not a directory, it is assumed to be a package or module name and tests in the package or module are loaded. FIXME: This needs a better description. Parameters ---------- start : str The directory, package, module, class or test to load. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ logger.debug('Starting test discovery') if os.path.isdir(start): start_directory = start return self.discover_by_directory( start_directory, top_level_directory=top_level_directory, pattern=pattern) elif os.path.isfile(start): start_filepath = start return self.discover_by_file( start_filepath, top_level_directory=top_level_directory) else: package_or_module = start return self.discover_by_module( package_or_module, top_level_directory=top_level_directory, pattern=pattern) def discover_by_module(self, module_name, top_level_directory=None, pattern='test*.py'): """Find all tests in a package or module, or load a single test case if a class or test inside a module was specified. Parameters ---------- module_name : str The dotted package name, module name or TestCase class and test method. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ # If the top level directory is given, the module may only be # importable with that in the path. if top_level_directory is not None and \ top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) logger.debug('Discovering tests by module: module_name=%r, ' 'top_level_directory=%r, pattern=%r', module_name, top_level_directory, pattern) try: module, case_attributes = find_module_by_name(module_name) except ImportError: return self.discover_filtered_tests( module_name, top_level_directory=top_level_directory, pattern=pattern) dirname, basename = os.path.split(module.__file__) basename = os.path.splitext(basename)[0] if len(case_attributes) == 0 and basename == '__init__': # Discover in a package return self.discover_by_directory( dirname, top_level_directory, pattern=pattern) elif len(case_attributes) == 0: # Discover all in a module return self._loader.load_module(module) return self.discover_single_case(module, case_attributes) def discover_single_case(self, module, case_attributes): """Find and load a single TestCase or TestCase method from a module. Parameters ---------- module : module The imported Python module containing the TestCase to be loaded. case_attributes : list A list (length 1 or 2) of str. The first component must be the name of a TestCase subclass. The second component must be the name of a method in the TestCase. """ # Find single case case = module loader = self._loader for index, component in enumerate(case_attributes): case = getattr(case, component, None) if case is None: return loader.create_suite() elif loader.is_test_case(case): rest = case_attributes[index + 1:] if len(rest) > 1: raise ValueError('Too many components in module path') elif len(rest) == 1: return loader.create_suite( [loader.load_test(case, *rest)]) return loader.load_case(case) # No cases matched, return empty suite return loader.create_suite() def discover_by_file(self, start_filepath, top_level_directory=None): """Run test discovery on a single file. Parameters ---------- start_filepath : str The module file in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. """ start_filepath = os.path.abspath(start_filepath) start_directory = os.path.dirname(start_filepath) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in file: start_filepath=%r, ' 'top_level_directory=', start_filepath, top_level_directory) assert_start_importable(top_level_directory, start_directory) if top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) tests = self._load_from_file( start_filepath, top_level_directory) return self._loader.create_suite(list(tests)) def _load_from_file(self, filepath, top_level_directory): module_name = get_module_name(top_level_directory, filepath) logger.debug('Loading tests from %r', module_name) try: module = get_module_by_name(module_name) except Exception: test = _create_import_error_test(module_name) else: # No exceptions on module import # Load tests return self._loader.load_module(module) # Create the test suite containing handled exception on import return self._loader.create_suite((test,)) def _discover_tests(self, start_directory, top_level_directory, pattern): for curdir, dirnames, filenames in os.walk(start_directory): logger.debug('Discovering tests in %r', curdir) dirnames[:] = [ dirname for dirname in dirnames if os.path.exists(os.path.join(curdir, dirname, '__init__.py')) ] for filename in filenames: filepath = os.path.join(curdir, filename) if not match_path(filename, filepath, pattern): logger.debug('Skipping %r', filepath) continue try: yield self._load_from_file(filepath, top_level_directory) except DotInModuleNameError: logger.info( 'Unexpected dot in module or package name: %r', filepath) continue def discover_filtered_tests(self, filter_name, top_level_directory=None, pattern='test*.py'): """Find all tests whose package, module, class or method names match the ``filter_name`` string. Parameters ---------- filter_name : str A subsection of the full dotted test name. This can be simply a test method name (e.g. ``test_some_method``), the TestCase class name (e.g. ``TestMyClass``), a module name (e.g. ``test_module``), a subpackage (e.g. ``tests``). It may also be a dotted combination of the above (e.g. ``TestMyClass.test_some_method``). top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ if top_level_directory is None: top_level_directory = find_top_level_directory( os.getcwd()) logger.debug('Discovering filtered tests: filter_name=%r, ' 'top_level_directory=%r, pattern=%r', top_level_directory, top_level_directory, pattern) suite = self.discover_by_directory( top_level_directory, top_level_directory=top_level_directory, pattern=pattern) return self._loader.create_suite( filter_test_suite(suite, filter_name=filter_name))
scalative/haas
haas/plugins/discoverer.py
Discoverer.discover_by_file
python
def discover_by_file(self, start_filepath, top_level_directory=None): start_filepath = os.path.abspath(start_filepath) start_directory = os.path.dirname(start_filepath) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in file: start_filepath=%r, ' 'top_level_directory=', start_filepath, top_level_directory) assert_start_importable(top_level_directory, start_directory) if top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) tests = self._load_from_file( start_filepath, top_level_directory) return self._loader.create_suite(list(tests))
Run test discovery on a single file. Parameters ---------- start_filepath : str The module file in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package.
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L334-L362
[ "def assert_start_importable(top_level_directory, start_directory):\n relpath = get_relpath(top_level_directory, start_directory)\n path = top_level_directory\n for component in relpath.split(os.path.sep):\n if component == '.':\n continue\n path = os.path.join(path, component)\n ...
class Discoverer(IDiscovererPlugin): """The ``Discoverer`` is responsible for finding tests that can be loaded by a :class:`~haas.loader.Loader`. """ def __init__(self, loader, **kwargs): super(Discoverer, self).__init__(**kwargs) self._loader = loader @classmethod def from_args(cls, args, arg_prefix, loader): """Construct the discoverer from parsed command line arguments. Parameters ---------- args : argparse.Namespace The ``argparse.Namespace`` containing parsed arguments. arg_prefix : str The prefix used for arguments beloning solely to this plugin. loader : haas.loader.Loader The test loader used to construct TestCase and TestSuite instances. """ return cls(loader) @classmethod def add_parser_arguments(cls, parser, option_prefix, dest_prefix): """Add options for the plugin to the main argument parser. Parameters ---------- parser : argparse.ArgumentParser The parser to extend option_prefix : str The prefix that option strings added by this plugin should use. dest_prefix : str The prefix that ``dest`` strings for options added by this plugin should use. """ def discover(self, start, top_level_directory=None, pattern='test*.py'): """Do test case discovery. This is the top-level entry-point for test discovery. If the ``start`` argument is a drectory, then ``haas`` will discover all tests in the package contained in that directory. If the ``start`` argument is not a directory, it is assumed to be a package or module name and tests in the package or module are loaded. FIXME: This needs a better description. Parameters ---------- start : str The directory, package, module, class or test to load. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ logger.debug('Starting test discovery') if os.path.isdir(start): start_directory = start return self.discover_by_directory( start_directory, top_level_directory=top_level_directory, pattern=pattern) elif os.path.isfile(start): start_filepath = start return self.discover_by_file( start_filepath, top_level_directory=top_level_directory) else: package_or_module = start return self.discover_by_module( package_or_module, top_level_directory=top_level_directory, pattern=pattern) def discover_by_module(self, module_name, top_level_directory=None, pattern='test*.py'): """Find all tests in a package or module, or load a single test case if a class or test inside a module was specified. Parameters ---------- module_name : str The dotted package name, module name or TestCase class and test method. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ # If the top level directory is given, the module may only be # importable with that in the path. if top_level_directory is not None and \ top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) logger.debug('Discovering tests by module: module_name=%r, ' 'top_level_directory=%r, pattern=%r', module_name, top_level_directory, pattern) try: module, case_attributes = find_module_by_name(module_name) except ImportError: return self.discover_filtered_tests( module_name, top_level_directory=top_level_directory, pattern=pattern) dirname, basename = os.path.split(module.__file__) basename = os.path.splitext(basename)[0] if len(case_attributes) == 0 and basename == '__init__': # Discover in a package return self.discover_by_directory( dirname, top_level_directory, pattern=pattern) elif len(case_attributes) == 0: # Discover all in a module return self._loader.load_module(module) return self.discover_single_case(module, case_attributes) def discover_single_case(self, module, case_attributes): """Find and load a single TestCase or TestCase method from a module. Parameters ---------- module : module The imported Python module containing the TestCase to be loaded. case_attributes : list A list (length 1 or 2) of str. The first component must be the name of a TestCase subclass. The second component must be the name of a method in the TestCase. """ # Find single case case = module loader = self._loader for index, component in enumerate(case_attributes): case = getattr(case, component, None) if case is None: return loader.create_suite() elif loader.is_test_case(case): rest = case_attributes[index + 1:] if len(rest) > 1: raise ValueError('Too many components in module path') elif len(rest) == 1: return loader.create_suite( [loader.load_test(case, *rest)]) return loader.load_case(case) # No cases matched, return empty suite return loader.create_suite() def discover_by_directory(self, start_directory, top_level_directory=None, pattern='test*.py'): """Run test discovery in a directory. Parameters ---------- start_directory : str The package directory in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ start_directory = os.path.abspath(start_directory) if top_level_directory is None: top_level_directory = find_top_level_directory( start_directory) logger.debug('Discovering tests in directory: start_directory=%r, ' 'top_level_directory=%r, pattern=%r', start_directory, top_level_directory, pattern) assert_start_importable(top_level_directory, start_directory) if top_level_directory not in sys.path: sys.path.insert(0, top_level_directory) tests = self._discover_tests( start_directory, top_level_directory, pattern) return self._loader.create_suite(list(tests)) def _load_from_file(self, filepath, top_level_directory): module_name = get_module_name(top_level_directory, filepath) logger.debug('Loading tests from %r', module_name) try: module = get_module_by_name(module_name) except Exception: test = _create_import_error_test(module_name) else: # No exceptions on module import # Load tests return self._loader.load_module(module) # Create the test suite containing handled exception on import return self._loader.create_suite((test,)) def _discover_tests(self, start_directory, top_level_directory, pattern): for curdir, dirnames, filenames in os.walk(start_directory): logger.debug('Discovering tests in %r', curdir) dirnames[:] = [ dirname for dirname in dirnames if os.path.exists(os.path.join(curdir, dirname, '__init__.py')) ] for filename in filenames: filepath = os.path.join(curdir, filename) if not match_path(filename, filepath, pattern): logger.debug('Skipping %r', filepath) continue try: yield self._load_from_file(filepath, top_level_directory) except DotInModuleNameError: logger.info( 'Unexpected dot in module or package name: %r', filepath) continue def discover_filtered_tests(self, filter_name, top_level_directory=None, pattern='test*.py'): """Find all tests whose package, module, class or method names match the ``filter_name`` string. Parameters ---------- filter_name : str A subsection of the full dotted test name. This can be simply a test method name (e.g. ``test_some_method``), the TestCase class name (e.g. ``TestMyClass``), a module name (e.g. ``test_module``), a subpackage (e.g. ``tests``). It may also be a dotted combination of the above (e.g. ``TestMyClass.test_some_method``). top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project'stop-level Python package. pattern : str The glob pattern to match the filenames of modules to search for tests. """ if top_level_directory is None: top_level_directory = find_top_level_directory( os.getcwd()) logger.debug('Discovering filtered tests: filter_name=%r, ' 'top_level_directory=%r, pattern=%r', top_level_directory, top_level_directory, pattern) suite = self.discover_by_directory( top_level_directory, top_level_directory=top_level_directory, pattern=pattern) return self._loader.create_suite( filter_test_suite(suite, filter_name=filter_name))
scalative/haas
haas/loader.py
Loader.load_case
python
def load_case(self, testcase): tests = [self.load_test(testcase, name) for name in self.find_test_method_names(testcase)] return self.create_suite(tests)
Load a TestSuite containing all TestCase instances for all tests in a TestCase subclass. Parameters ---------- testcase : type A subclass of :class:`unittest.TestCase`
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/loader.py#L83-L95
[ "def create_suite(self, tests=()):\n \"\"\"Create a test suite using the confugured test suite class.\n\n Parameters\n ----------\n tests : sequence\n Sequence of TestCase instances.\n\n \"\"\"\n return self._test_suite_class(tests)\n", "def find_test_method_names(self, testcase):\n \"...
class Loader(object): """Load individual test cases from modules and wrap them in the :class:`~haas.suite.Suite` container. """ def __init__(self, test_suite_class=None, test_case_class=None, test_method_prefix='test', **kwargs): super(Loader, self).__init__(**kwargs) self._test_method_prefix = test_method_prefix if test_suite_class is None: test_suite_class = TestSuite self._test_suite_class = test_suite_class if test_case_class is None: test_case_class = unittest.TestCase self._test_case_class = test_case_class def create_suite(self, tests=()): """Create a test suite using the confugured test suite class. Parameters ---------- tests : sequence Sequence of TestCase instances. """ return self._test_suite_class(tests) def is_test_case(self, klass): """Check if a class is a TestCase. """ return issubclass(klass, self._test_case_class) def find_test_method_names(self, testcase): """Return a list of test method names in the provided ``TestCase`` subclass. Parameters ---------- testcase : type Subclass of :class:`unittest.TestCase` """ prefix = self._test_method_prefix names = [name for name in dir(testcase) if name.startswith(prefix) and hasattr(getattr(testcase, name), '__call__')] return names def load_test(self, testcase, method_name): """Create and return an instance of :class:`unittest.TestCase` for the specified unbound test method. Parameters ---------- unbound_test : unbound method An unbound method of a :class:`unittest.TestCase` """ if not self.is_test_case(testcase): raise TypeError( 'Test case must be a subclass of ' '{0.__module__}.{0.__name__}'.format(self._test_case_class)) return testcase(method_name) def get_test_cases_from_module(self, module): """Return a list of TestCase subclasses contained in the provided module object. Parameters ---------- module : module A module object containing ``TestCases`` """ module_items = (getattr(module, name) for name in dir(module)) return [item for item in module_items if isinstance(item, type) and self.is_test_case(item)] def load_module(self, module): """Create and return a test suite containing all cases loaded from the provided module. Parameters ---------- module : module A module object containing ``TestCases`` """ cases = self.get_test_cases_from_module(module) suites = [self.load_case(case) for case in cases] return self.create_suite(suites)
scalative/haas
haas/loader.py
Loader.load_module
python
def load_module(self, module): cases = self.get_test_cases_from_module(module) suites = [self.load_case(case) for case in cases] return self.create_suite(suites)
Create and return a test suite containing all cases loaded from the provided module. Parameters ---------- module : module A module object containing ``TestCases``
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/loader.py#L112-L124
[ "def create_suite(self, tests=()):\n \"\"\"Create a test suite using the confugured test suite class.\n\n Parameters\n ----------\n tests : sequence\n Sequence of TestCase instances.\n\n \"\"\"\n return self._test_suite_class(tests)\n", "def get_test_cases_from_module(self, module):\n ...
class Loader(object): """Load individual test cases from modules and wrap them in the :class:`~haas.suite.Suite` container. """ def __init__(self, test_suite_class=None, test_case_class=None, test_method_prefix='test', **kwargs): super(Loader, self).__init__(**kwargs) self._test_method_prefix = test_method_prefix if test_suite_class is None: test_suite_class = TestSuite self._test_suite_class = test_suite_class if test_case_class is None: test_case_class = unittest.TestCase self._test_case_class = test_case_class def create_suite(self, tests=()): """Create a test suite using the confugured test suite class. Parameters ---------- tests : sequence Sequence of TestCase instances. """ return self._test_suite_class(tests) def is_test_case(self, klass): """Check if a class is a TestCase. """ return issubclass(klass, self._test_case_class) def find_test_method_names(self, testcase): """Return a list of test method names in the provided ``TestCase`` subclass. Parameters ---------- testcase : type Subclass of :class:`unittest.TestCase` """ prefix = self._test_method_prefix names = [name for name in dir(testcase) if name.startswith(prefix) and hasattr(getattr(testcase, name), '__call__')] return names def load_test(self, testcase, method_name): """Create and return an instance of :class:`unittest.TestCase` for the specified unbound test method. Parameters ---------- unbound_test : unbound method An unbound method of a :class:`unittest.TestCase` """ if not self.is_test_case(testcase): raise TypeError( 'Test case must be a subclass of ' '{0.__module__}.{0.__name__}'.format(self._test_case_class)) return testcase(method_name) def load_case(self, testcase): """Load a TestSuite containing all TestCase instances for all tests in a TestCase subclass. Parameters ---------- testcase : type A subclass of :class:`unittest.TestCase` """ tests = [self.load_test(testcase, name) for name in self.find_test_method_names(testcase)] return self.create_suite(tests) def get_test_cases_from_module(self, module): """Return a list of TestCase subclasses contained in the provided module object. Parameters ---------- module : module A module object containing ``TestCases`` """ module_items = (getattr(module, name) for name in dir(module)) return [item for item in module_items if isinstance(item, type) and self.is_test_case(item)]
Genida/django-meerkat
src/meerkat/utils/geolocation.py
ip_geoloc
python
def ip_geoloc(ip, hit_api=True): from ..logs.models import IPInfoCheck try: obj = IPInfoCheck.objects.get(ip_address=ip).ip_info except IPInfoCheck.DoesNotExist: if hit_api: try: obj = IPInfoCheck.check_ip(ip) except RateExceededError: return None else: return None return obj.latitude, obj.longitude
Get IP geolocation. Args: ip (str): IP address to use if no data provided. hit_api (bool): whether to hit api if info not found. Returns: str: latitude and longitude, comma-separated.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/geolocation.py#L8-L30
[ "def check_ip(ip):\n ip_info, _ = IPInfo.get_or_create_from_ip(ip)\n if ip_info:\n IPInfoCheck.objects.create(ip_address=ip, ip_info=ip_info)\n return ip_info\n return None\n" ]
# -*- coding: utf-8 -*- """Geolocation utils.""" from ..exceptions import RateExceededError def google_maps_geoloc_link(data): """ Get a link to google maps pointing on this IP's geolocation. Args: data (str/tuple): IP address or (latitude, longitude). Returns: str: a link to google maps pointing on this IP's geolocation. """ if isinstance(data, str): lat_lon = ip_geoloc(data) if lat_lon is None: return '' lat, lon = lat_lon else: lat, lon = data loc = '%s,%s' % (lat, lon) return 'https://www.google.com/maps/place/@%s,17z/' \ 'data=!3m1!4b1!4m5!3m4!1s0x0:0x0!8m2!3d%s!4d%s' % ( loc, lat, lon) def open_street_map_geoloc_link(data): """ Get a link to open street map pointing on this IP's geolocation. Args: data (str/tuple): IP address or (latitude, longitude). Returns: str: a link to open street map pointing on this IP's geolocation. """ if isinstance(data, str): lat_lon = ip_geoloc(data) if lat_lon is None: return '' lat, lon = lat_lon else: lat, lon = data return 'https://www.openstreetmap.org/search' \ '?query=%s%%2C%s#map=7/%s/%s' % (lat, lon, lat, lon)
Genida/django-meerkat
src/meerkat/utils/geolocation.py
google_maps_geoloc_link
python
def google_maps_geoloc_link(data): if isinstance(data, str): lat_lon = ip_geoloc(data) if lat_lon is None: return '' lat, lon = lat_lon else: lat, lon = data loc = '%s,%s' % (lat, lon) return 'https://www.google.com/maps/place/@%s,17z/' \ 'data=!3m1!4b1!4m5!3m4!1s0x0:0x0!8m2!3d%s!4d%s' % ( loc, lat, lon)
Get a link to google maps pointing on this IP's geolocation. Args: data (str/tuple): IP address or (latitude, longitude). Returns: str: a link to google maps pointing on this IP's geolocation.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/geolocation.py#L33-L53
[ "def ip_geoloc(ip, hit_api=True):\n \"\"\"\n Get IP geolocation.\n\n Args:\n ip (str): IP address to use if no data provided.\n hit_api (bool): whether to hit api if info not found.\n\n Returns:\n str: latitude and longitude, comma-separated.\n \"\"\"\n from ..logs.models impo...
# -*- coding: utf-8 -*- """Geolocation utils.""" from ..exceptions import RateExceededError def ip_geoloc(ip, hit_api=True): """ Get IP geolocation. Args: ip (str): IP address to use if no data provided. hit_api (bool): whether to hit api if info not found. Returns: str: latitude and longitude, comma-separated. """ from ..logs.models import IPInfoCheck try: obj = IPInfoCheck.objects.get(ip_address=ip).ip_info except IPInfoCheck.DoesNotExist: if hit_api: try: obj = IPInfoCheck.check_ip(ip) except RateExceededError: return None else: return None return obj.latitude, obj.longitude def open_street_map_geoloc_link(data): """ Get a link to open street map pointing on this IP's geolocation. Args: data (str/tuple): IP address or (latitude, longitude). Returns: str: a link to open street map pointing on this IP's geolocation. """ if isinstance(data, str): lat_lon = ip_geoloc(data) if lat_lon is None: return '' lat, lon = lat_lon else: lat, lon = data return 'https://www.openstreetmap.org/search' \ '?query=%s%%2C%s#map=7/%s/%s' % (lat, lon, lat, lon)
Genida/django-meerkat
src/meerkat/utils/geolocation.py
open_street_map_geoloc_link
python
def open_street_map_geoloc_link(data): if isinstance(data, str): lat_lon = ip_geoloc(data) if lat_lon is None: return '' lat, lon = lat_lon else: lat, lon = data return 'https://www.openstreetmap.org/search' \ '?query=%s%%2C%s#map=7/%s/%s' % (lat, lon, lat, lon)
Get a link to open street map pointing on this IP's geolocation. Args: data (str/tuple): IP address or (latitude, longitude). Returns: str: a link to open street map pointing on this IP's geolocation.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/geolocation.py#L56-L74
[ "def ip_geoloc(ip, hit_api=True):\n \"\"\"\n Get IP geolocation.\n\n Args:\n ip (str): IP address to use if no data provided.\n hit_api (bool): whether to hit api if info not found.\n\n Returns:\n str: latitude and longitude, comma-separated.\n \"\"\"\n from ..logs.models impo...
# -*- coding: utf-8 -*- """Geolocation utils.""" from ..exceptions import RateExceededError def ip_geoloc(ip, hit_api=True): """ Get IP geolocation. Args: ip (str): IP address to use if no data provided. hit_api (bool): whether to hit api if info not found. Returns: str: latitude and longitude, comma-separated. """ from ..logs.models import IPInfoCheck try: obj = IPInfoCheck.objects.get(ip_address=ip).ip_info except IPInfoCheck.DoesNotExist: if hit_api: try: obj = IPInfoCheck.check_ip(ip) except RateExceededError: return None else: return None return obj.latitude, obj.longitude def google_maps_geoloc_link(data): """ Get a link to google maps pointing on this IP's geolocation. Args: data (str/tuple): IP address or (latitude, longitude). Returns: str: a link to google maps pointing on this IP's geolocation. """ if isinstance(data, str): lat_lon = ip_geoloc(data) if lat_lon is None: return '' lat, lon = lat_lon else: lat, lon = data loc = '%s,%s' % (lat, lon) return 'https://www.google.com/maps/place/@%s,17z/' \ 'data=!3m1!4b1!4m5!3m4!1s0x0:0x0!8m2!3d%s!4d%s' % ( loc, lat, lon)
Genida/django-meerkat
src/meerkat/logs/charts.py
status_codes_chart
python
def status_codes_chart(): stats = status_codes_stats() chart_options = { 'chart': { 'type': 'pie' }, 'title': { 'text': '' }, 'subtitle': { 'text': '' }, 'tooltip': { 'formatter': "return this.y + '/' + this.total + ' (' + " "Highcharts.numberFormat(this.percentage, 1) + '%)';" }, 'legend': { 'enabled': True, }, 'plotOptions': { 'pie': { 'allowPointSelect': True, 'cursor': 'pointer', 'dataLabels': { 'enabled': True, 'format': '<b>{point.name}</b>: {point.y}/{point.total} ' '({point.percentage:.1f}%)' }, 'showInLegend': True } }, 'series': [{ 'name': _('Status Codes'), 'colorByPoint': True, 'data': sorted( [{'name': '%s %s' % (k, STATUS_CODES[int(k)]['name']), 'y': v} for k, v in stats.items()], key=lambda x: x['y'], reverse=True) }] } return chart_options
Chart for status codes.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/charts.py#L19-L63
[ "def status_codes_stats():\n \"\"\"\n Get stats for status codes.\n\n Args:\n logs (list): logs data to use.\n\n Returns:\n dict: status code as key, number of apparition as value.\n \"\"\"\n return dict(Counter(list(RequestLog.objects.values_list(\n 'status_code', flat=True))...
# -*- coding: utf-8 -*- """ Chart methods. This module contains the methods that will build the chart dictionaries from data. """ from django.utils.translation import ugettext as _ from ..utils.url import ( ASSET, COMMON_ASSET, FALSE_NEGATIVE, OLD_ASSET, OLD_PROJECT, PROJECT, SUSPICIOUS) from .data import STATUS_CODES from .stats import most_visited_pages_stats, status_codes_stats def status_codes_by_date_chart(): """Chart for status codes by date.""" return { 'chart': { 'type': 'area', 'zoomType': 'x' }, 'title': {'text': None}, 'xAxis': {'type': 'datetime'}, 'yAxis': {'title': {'text': None}}, 'legend': {'enabled': True}, 'tooltip': {'shared': True}, 'plotOptions': { 'area': { 'lineWidth': 1, 'marker': { 'lineWidth': 1, } } } } URL_TYPE_COLOR = { PROJECT: '#AFE4FD', ASSET: '#DBDBDB', COMMON_ASSET: '#F1F2B6', OLD_ASSET: '#808080', OLD_PROJECT: '#B6B6F2', FALSE_NEGATIVE: '#9CD8AC', SUSPICIOUS: '#FFB31A' } def most_visited_pages_legend_chart(): """Chart for most visited pages legend.""" return { 'chart': { 'type': 'bar', 'height': 200, }, 'title': { 'text': _('Legend') }, 'xAxis': { 'categories': [ _('Project URL'), _('Old project URL'), _('Asset URL'), _('Old asset URL'), _('Common asset URL'), _('False-negative project URL'), _('Suspicious URL (potential attack)') ], 'title': { 'text': None } }, 'yAxis': { 'title': { 'text': None, 'align': 'high' }, 'labels': { 'overflow': 'justify' } }, 'tooltip': { 'enabled': False }, 'legend': { 'enabled': False }, 'credits': { 'enabled': False }, 'series': [{ 'name': _('Legend'), 'data': [ {'color': URL_TYPE_COLOR[PROJECT], 'y': 1}, {'color': URL_TYPE_COLOR[OLD_PROJECT], 'y': 1}, {'color': URL_TYPE_COLOR[ASSET], 'y': 1}, {'color': URL_TYPE_COLOR[OLD_ASSET], 'y': 1}, {'color': URL_TYPE_COLOR[COMMON_ASSET], 'y': 1}, {'color': URL_TYPE_COLOR[FALSE_NEGATIVE], 'y': 1}, {'color': URL_TYPE_COLOR[SUSPICIOUS], 'y': 1}, ] }] } def most_visited_pages_charts(): """Chart for most visited pages.""" stats = most_visited_pages_stats() charts = [] for i, stat in enumerate(stats['more_than_10']): bound = stat['bound'] subset = stat['subset'] chart_options = { 'chart': { 'type': 'bar', 'height': 15 * len(subset) + 100 }, 'title': { 'text': {0: _('More than %d times') % bound}.get( i, _('Between %d and %d times') % ( bound, stats['more_than_10'][i - 1]['bound'])) }, 'xAxis': { 'categories': [u for (u, c, t) in subset], 'title': { 'text': None } }, 'yAxis': { 'title': { 'text': None } }, 'plotOptions': { 'bar': { 'dataLabels': { 'enabled': True } }, }, 'tooltip': { 'enabled': False }, 'legend': { 'enabled': False }, 'credits': { 'enabled': False }, } series_data = [] for index, (url, count, url_type) in enumerate(subset): data = { 'x': index, 'y': count } color = URL_TYPE_COLOR[url_type] data['color'] = color series_data.append(data) chart_options['series'] = [{ 'name': _('Requests'), 'data': series_data }] charts.append(chart_options) point_formatter_code = """ return '<br>%s: <strong>' + this.dis + '</strong>(' + Highcharts.numberFormat(this.dis / this.total_dis * 100, 1) + '%%)' + '<br>%s: <strong>' + this.occ + '</strong> (' + Highcharts.numberFormat(this.occ / this.total_occ * 100, 1) + '%%)'; """ % (_('Distinct URLs'), _('Occurrences')) occurrences = stats['less_than_10'] total_distinct = sum([v['distinct'] for k, v in occurrences.items()]) total_occurrences = sum([v['total'] for k, v in occurrences.items()]) charts.append({ 'chart': { 'plotBackgroundColor': None, 'plotBorderWidth': None, 'plotShadow': False, 'type': 'pie' }, 'title': { 'text': _('Less than 10 (type repartition)') }, 'plotOptions': { 'pie': { 'allowPointSelect': True, 'cursor': 'pointer', 'dataLabels': { 'enabled': False }, 'showInLegend': True, 'tooltip': { 'pointFormatter': point_formatter_code }, } }, 'series': [{ 'name': '', 'colorByPoint': True, 'data': [{ 'name': _('Valid project URL'), 'dis': occurrences[PROJECT]['distinct'], 'y': occurrences[PROJECT]['total'], 'occ': occurrences[PROJECT]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[PROJECT] }, { 'name': _('Old project URL'), 'dis': occurrences[OLD_PROJECT]['distinct'], 'y': occurrences[OLD_PROJECT]['total'], 'occ': occurrences[OLD_PROJECT]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[OLD_PROJECT] }, { 'name': _('Valid asset URL'), 'dis': occurrences[ASSET]['distinct'], 'y': occurrences[ASSET]['total'], 'occ': occurrences[ASSET]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[ASSET] }, { 'name': _('Old asset URL'), 'dis': occurrences[OLD_ASSET]['distinct'], 'y': occurrences[OLD_ASSET]['total'], 'occ': occurrences[OLD_ASSET]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[OLD_ASSET] }, { 'name': _('Common asset URL'), 'dis': occurrences[COMMON_ASSET]['distinct'], 'y': occurrences[COMMON_ASSET]['total'], 'occ': occurrences[COMMON_ASSET]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[COMMON_ASSET] }, { 'name': _('False-negative project URL'), 'dis': occurrences[FALSE_NEGATIVE]['distinct'], 'y': occurrences[FALSE_NEGATIVE]['total'], 'occ': occurrences[FALSE_NEGATIVE]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[FALSE_NEGATIVE] }, { 'name': _('Suspicious URL (potential attack)'), 'dis': occurrences[SUSPICIOUS]['distinct'], 'y': occurrences[SUSPICIOUS]['total'], 'occ': occurrences[SUSPICIOUS]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[SUSPICIOUS] }] }] }) return charts
Genida/django-meerkat
src/meerkat/logs/charts.py
most_visited_pages_legend_chart
python
def most_visited_pages_legend_chart(): return { 'chart': { 'type': 'bar', 'height': 200, }, 'title': { 'text': _('Legend') }, 'xAxis': { 'categories': [ _('Project URL'), _('Old project URL'), _('Asset URL'), _('Old asset URL'), _('Common asset URL'), _('False-negative project URL'), _('Suspicious URL (potential attack)') ], 'title': { 'text': None } }, 'yAxis': { 'title': { 'text': None, 'align': 'high' }, 'labels': { 'overflow': 'justify' } }, 'tooltip': { 'enabled': False }, 'legend': { 'enabled': False }, 'credits': { 'enabled': False }, 'series': [{ 'name': _('Legend'), 'data': [ {'color': URL_TYPE_COLOR[PROJECT], 'y': 1}, {'color': URL_TYPE_COLOR[OLD_PROJECT], 'y': 1}, {'color': URL_TYPE_COLOR[ASSET], 'y': 1}, {'color': URL_TYPE_COLOR[OLD_ASSET], 'y': 1}, {'color': URL_TYPE_COLOR[COMMON_ASSET], 'y': 1}, {'color': URL_TYPE_COLOR[FALSE_NEGATIVE], 'y': 1}, {'color': URL_TYPE_COLOR[SUSPICIOUS], 'y': 1}, ] }] }
Chart for most visited pages legend.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/charts.py#L100-L154
null
# -*- coding: utf-8 -*- """ Chart methods. This module contains the methods that will build the chart dictionaries from data. """ from django.utils.translation import ugettext as _ from ..utils.url import ( ASSET, COMMON_ASSET, FALSE_NEGATIVE, OLD_ASSET, OLD_PROJECT, PROJECT, SUSPICIOUS) from .data import STATUS_CODES from .stats import most_visited_pages_stats, status_codes_stats def status_codes_chart(): """Chart for status codes.""" stats = status_codes_stats() chart_options = { 'chart': { 'type': 'pie' }, 'title': { 'text': '' }, 'subtitle': { 'text': '' }, 'tooltip': { 'formatter': "return this.y + '/' + this.total + ' (' + " "Highcharts.numberFormat(this.percentage, 1) + '%)';" }, 'legend': { 'enabled': True, }, 'plotOptions': { 'pie': { 'allowPointSelect': True, 'cursor': 'pointer', 'dataLabels': { 'enabled': True, 'format': '<b>{point.name}</b>: {point.y}/{point.total} ' '({point.percentage:.1f}%)' }, 'showInLegend': True } }, 'series': [{ 'name': _('Status Codes'), 'colorByPoint': True, 'data': sorted( [{'name': '%s %s' % (k, STATUS_CODES[int(k)]['name']), 'y': v} for k, v in stats.items()], key=lambda x: x['y'], reverse=True) }] } return chart_options def status_codes_by_date_chart(): """Chart for status codes by date.""" return { 'chart': { 'type': 'area', 'zoomType': 'x' }, 'title': {'text': None}, 'xAxis': {'type': 'datetime'}, 'yAxis': {'title': {'text': None}}, 'legend': {'enabled': True}, 'tooltip': {'shared': True}, 'plotOptions': { 'area': { 'lineWidth': 1, 'marker': { 'lineWidth': 1, } } } } URL_TYPE_COLOR = { PROJECT: '#AFE4FD', ASSET: '#DBDBDB', COMMON_ASSET: '#F1F2B6', OLD_ASSET: '#808080', OLD_PROJECT: '#B6B6F2', FALSE_NEGATIVE: '#9CD8AC', SUSPICIOUS: '#FFB31A' } def most_visited_pages_charts(): """Chart for most visited pages.""" stats = most_visited_pages_stats() charts = [] for i, stat in enumerate(stats['more_than_10']): bound = stat['bound'] subset = stat['subset'] chart_options = { 'chart': { 'type': 'bar', 'height': 15 * len(subset) + 100 }, 'title': { 'text': {0: _('More than %d times') % bound}.get( i, _('Between %d and %d times') % ( bound, stats['more_than_10'][i - 1]['bound'])) }, 'xAxis': { 'categories': [u for (u, c, t) in subset], 'title': { 'text': None } }, 'yAxis': { 'title': { 'text': None } }, 'plotOptions': { 'bar': { 'dataLabels': { 'enabled': True } }, }, 'tooltip': { 'enabled': False }, 'legend': { 'enabled': False }, 'credits': { 'enabled': False }, } series_data = [] for index, (url, count, url_type) in enumerate(subset): data = { 'x': index, 'y': count } color = URL_TYPE_COLOR[url_type] data['color'] = color series_data.append(data) chart_options['series'] = [{ 'name': _('Requests'), 'data': series_data }] charts.append(chart_options) point_formatter_code = """ return '<br>%s: <strong>' + this.dis + '</strong>(' + Highcharts.numberFormat(this.dis / this.total_dis * 100, 1) + '%%)' + '<br>%s: <strong>' + this.occ + '</strong> (' + Highcharts.numberFormat(this.occ / this.total_occ * 100, 1) + '%%)'; """ % (_('Distinct URLs'), _('Occurrences')) occurrences = stats['less_than_10'] total_distinct = sum([v['distinct'] for k, v in occurrences.items()]) total_occurrences = sum([v['total'] for k, v in occurrences.items()]) charts.append({ 'chart': { 'plotBackgroundColor': None, 'plotBorderWidth': None, 'plotShadow': False, 'type': 'pie' }, 'title': { 'text': _('Less than 10 (type repartition)') }, 'plotOptions': { 'pie': { 'allowPointSelect': True, 'cursor': 'pointer', 'dataLabels': { 'enabled': False }, 'showInLegend': True, 'tooltip': { 'pointFormatter': point_formatter_code }, } }, 'series': [{ 'name': '', 'colorByPoint': True, 'data': [{ 'name': _('Valid project URL'), 'dis': occurrences[PROJECT]['distinct'], 'y': occurrences[PROJECT]['total'], 'occ': occurrences[PROJECT]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[PROJECT] }, { 'name': _('Old project URL'), 'dis': occurrences[OLD_PROJECT]['distinct'], 'y': occurrences[OLD_PROJECT]['total'], 'occ': occurrences[OLD_PROJECT]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[OLD_PROJECT] }, { 'name': _('Valid asset URL'), 'dis': occurrences[ASSET]['distinct'], 'y': occurrences[ASSET]['total'], 'occ': occurrences[ASSET]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[ASSET] }, { 'name': _('Old asset URL'), 'dis': occurrences[OLD_ASSET]['distinct'], 'y': occurrences[OLD_ASSET]['total'], 'occ': occurrences[OLD_ASSET]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[OLD_ASSET] }, { 'name': _('Common asset URL'), 'dis': occurrences[COMMON_ASSET]['distinct'], 'y': occurrences[COMMON_ASSET]['total'], 'occ': occurrences[COMMON_ASSET]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[COMMON_ASSET] }, { 'name': _('False-negative project URL'), 'dis': occurrences[FALSE_NEGATIVE]['distinct'], 'y': occurrences[FALSE_NEGATIVE]['total'], 'occ': occurrences[FALSE_NEGATIVE]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[FALSE_NEGATIVE] }, { 'name': _('Suspicious URL (potential attack)'), 'dis': occurrences[SUSPICIOUS]['distinct'], 'y': occurrences[SUSPICIOUS]['total'], 'occ': occurrences[SUSPICIOUS]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[SUSPICIOUS] }] }] }) return charts
Genida/django-meerkat
src/meerkat/logs/charts.py
most_visited_pages_charts
python
def most_visited_pages_charts(): stats = most_visited_pages_stats() charts = [] for i, stat in enumerate(stats['more_than_10']): bound = stat['bound'] subset = stat['subset'] chart_options = { 'chart': { 'type': 'bar', 'height': 15 * len(subset) + 100 }, 'title': { 'text': {0: _('More than %d times') % bound}.get( i, _('Between %d and %d times') % ( bound, stats['more_than_10'][i - 1]['bound'])) }, 'xAxis': { 'categories': [u for (u, c, t) in subset], 'title': { 'text': None } }, 'yAxis': { 'title': { 'text': None } }, 'plotOptions': { 'bar': { 'dataLabels': { 'enabled': True } }, }, 'tooltip': { 'enabled': False }, 'legend': { 'enabled': False }, 'credits': { 'enabled': False }, } series_data = [] for index, (url, count, url_type) in enumerate(subset): data = { 'x': index, 'y': count } color = URL_TYPE_COLOR[url_type] data['color'] = color series_data.append(data) chart_options['series'] = [{ 'name': _('Requests'), 'data': series_data }] charts.append(chart_options) point_formatter_code = """ return '<br>%s: <strong>' + this.dis + '</strong>(' + Highcharts.numberFormat(this.dis / this.total_dis * 100, 1) + '%%)' + '<br>%s: <strong>' + this.occ + '</strong> (' + Highcharts.numberFormat(this.occ / this.total_occ * 100, 1) + '%%)'; """ % (_('Distinct URLs'), _('Occurrences')) occurrences = stats['less_than_10'] total_distinct = sum([v['distinct'] for k, v in occurrences.items()]) total_occurrences = sum([v['total'] for k, v in occurrences.items()]) charts.append({ 'chart': { 'plotBackgroundColor': None, 'plotBorderWidth': None, 'plotShadow': False, 'type': 'pie' }, 'title': { 'text': _('Less than 10 (type repartition)') }, 'plotOptions': { 'pie': { 'allowPointSelect': True, 'cursor': 'pointer', 'dataLabels': { 'enabled': False }, 'showInLegend': True, 'tooltip': { 'pointFormatter': point_formatter_code }, } }, 'series': [{ 'name': '', 'colorByPoint': True, 'data': [{ 'name': _('Valid project URL'), 'dis': occurrences[PROJECT]['distinct'], 'y': occurrences[PROJECT]['total'], 'occ': occurrences[PROJECT]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[PROJECT] }, { 'name': _('Old project URL'), 'dis': occurrences[OLD_PROJECT]['distinct'], 'y': occurrences[OLD_PROJECT]['total'], 'occ': occurrences[OLD_PROJECT]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[OLD_PROJECT] }, { 'name': _('Valid asset URL'), 'dis': occurrences[ASSET]['distinct'], 'y': occurrences[ASSET]['total'], 'occ': occurrences[ASSET]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[ASSET] }, { 'name': _('Old asset URL'), 'dis': occurrences[OLD_ASSET]['distinct'], 'y': occurrences[OLD_ASSET]['total'], 'occ': occurrences[OLD_ASSET]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[OLD_ASSET] }, { 'name': _('Common asset URL'), 'dis': occurrences[COMMON_ASSET]['distinct'], 'y': occurrences[COMMON_ASSET]['total'], 'occ': occurrences[COMMON_ASSET]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[COMMON_ASSET] }, { 'name': _('False-negative project URL'), 'dis': occurrences[FALSE_NEGATIVE]['distinct'], 'y': occurrences[FALSE_NEGATIVE]['total'], 'occ': occurrences[FALSE_NEGATIVE]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[FALSE_NEGATIVE] }, { 'name': _('Suspicious URL (potential attack)'), 'dis': occurrences[SUSPICIOUS]['distinct'], 'y': occurrences[SUSPICIOUS]['total'], 'occ': occurrences[SUSPICIOUS]['total'], 'total_dis': total_distinct, 'total_occ': total_occurrences, 'color': URL_TYPE_COLOR[SUSPICIOUS] }] }] }) return charts
Chart for most visited pages.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/charts.py#L157-L318
[ "def most_visited_pages_stats():\n \"\"\"\n Get stats for most visited pages.\n\n Args:\n logs (list): logs data to use.\n\n Returns:\n dict: more_than_10 and less_than_10: list of dict (bound + url list).\n \"\"\"\n stats = {'more_than_10': [], 'less_than_10': {}}\n\n counter = C...
# -*- coding: utf-8 -*- """ Chart methods. This module contains the methods that will build the chart dictionaries from data. """ from django.utils.translation import ugettext as _ from ..utils.url import ( ASSET, COMMON_ASSET, FALSE_NEGATIVE, OLD_ASSET, OLD_PROJECT, PROJECT, SUSPICIOUS) from .data import STATUS_CODES from .stats import most_visited_pages_stats, status_codes_stats def status_codes_chart(): """Chart for status codes.""" stats = status_codes_stats() chart_options = { 'chart': { 'type': 'pie' }, 'title': { 'text': '' }, 'subtitle': { 'text': '' }, 'tooltip': { 'formatter': "return this.y + '/' + this.total + ' (' + " "Highcharts.numberFormat(this.percentage, 1) + '%)';" }, 'legend': { 'enabled': True, }, 'plotOptions': { 'pie': { 'allowPointSelect': True, 'cursor': 'pointer', 'dataLabels': { 'enabled': True, 'format': '<b>{point.name}</b>: {point.y}/{point.total} ' '({point.percentage:.1f}%)' }, 'showInLegend': True } }, 'series': [{ 'name': _('Status Codes'), 'colorByPoint': True, 'data': sorted( [{'name': '%s %s' % (k, STATUS_CODES[int(k)]['name']), 'y': v} for k, v in stats.items()], key=lambda x: x['y'], reverse=True) }] } return chart_options def status_codes_by_date_chart(): """Chart for status codes by date.""" return { 'chart': { 'type': 'area', 'zoomType': 'x' }, 'title': {'text': None}, 'xAxis': {'type': 'datetime'}, 'yAxis': {'title': {'text': None}}, 'legend': {'enabled': True}, 'tooltip': {'shared': True}, 'plotOptions': { 'area': { 'lineWidth': 1, 'marker': { 'lineWidth': 1, } } } } URL_TYPE_COLOR = { PROJECT: '#AFE4FD', ASSET: '#DBDBDB', COMMON_ASSET: '#F1F2B6', OLD_ASSET: '#808080', OLD_PROJECT: '#B6B6F2', FALSE_NEGATIVE: '#9CD8AC', SUSPICIOUS: '#FFB31A' } def most_visited_pages_legend_chart(): """Chart for most visited pages legend.""" return { 'chart': { 'type': 'bar', 'height': 200, }, 'title': { 'text': _('Legend') }, 'xAxis': { 'categories': [ _('Project URL'), _('Old project URL'), _('Asset URL'), _('Old asset URL'), _('Common asset URL'), _('False-negative project URL'), _('Suspicious URL (potential attack)') ], 'title': { 'text': None } }, 'yAxis': { 'title': { 'text': None, 'align': 'high' }, 'labels': { 'overflow': 'justify' } }, 'tooltip': { 'enabled': False }, 'legend': { 'enabled': False }, 'credits': { 'enabled': False }, 'series': [{ 'name': _('Legend'), 'data': [ {'color': URL_TYPE_COLOR[PROJECT], 'y': 1}, {'color': URL_TYPE_COLOR[OLD_PROJECT], 'y': 1}, {'color': URL_TYPE_COLOR[ASSET], 'y': 1}, {'color': URL_TYPE_COLOR[OLD_ASSET], 'y': 1}, {'color': URL_TYPE_COLOR[COMMON_ASSET], 'y': 1}, {'color': URL_TYPE_COLOR[FALSE_NEGATIVE], 'y': 1}, {'color': URL_TYPE_COLOR[SUSPICIOUS], 'y': 1}, ] }] }
Genida/django-meerkat
src/meerkat/sites.py
DashboardSite.get_urls
python
def get_urls(self): urls = super(DashboardSite, self).get_urls() custom_urls = [ url(r'^$', self.admin_view(HomeView.as_view()), name='index'), url(r'^logs/', include(logs_urlpatterns(self.admin_view))), ] custom_urls += get_realtime_urls(self.admin_view) del urls[0] return custom_urls + urls
Get urls method. Returns: list: the list of url objects.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/sites.py#L23-L41
[ "def logs_urlpatterns(admin_view=lambda x: x):\n \"\"\"\n Return the URL patterns for the logs views.\n\n Args:\n admin_view (callable): admin_view method from an AdminSite instance.\n\n Returns:\n list: the URL patterns for the logs views.\n \"\"\"\n return [\n url(r'^$',\n ...
class DashboardSite(AdminSite): """A Django AdminSite to allow registering custom dashboard views."""
Genida/django-meerkat
src/meerkat/logs/urls.py
logs_urlpatterns
python
def logs_urlpatterns(admin_view=lambda x: x): return [ url(r'^$', admin_view(LogsMenu.as_view()), name='logs'), url(r'^status_codes$', admin_view(LogsStatusCodes.as_view()), name='logs_status_codes'), url(r'^status_codes_by_date$', admin_view(LogsStatusCodesByDate.as_view()), name='logs_status_codes_by_date'), url(r'^most_visited_pages$', admin_view(LogsMostVisitedPages.as_view()), name='logs_most_visited_pages') ]
Return the URL patterns for the logs views. Args: admin_view (callable): admin_view method from an AdminSite instance. Returns: list: the URL patterns for the logs views.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/urls.py#L11-L34
[ "def logs_urlpatterns(admin_view=lambda x: x):\n" ]
# -*- coding: utf-8 -*- """URLs for log submodule.""" from django.conf.urls import url from .views import ( LogsMenu, LogsMostVisitedPages, LogsStatusCodes, LogsStatusCodesByDate) urlpatterns = logs_urlpatterns()
Genida/django-meerkat
src/meerkat/utils/ip_info.py
IpInfoHandler._get
python
def _get(self, ip): # Geoloc updated up to once a week: # http://ipinfo.io/developers/data#geolocation-data retries = 10 for retry in range(retries): try: response = requests.get('http://ipinfo.io/%s/json' % ip, verify=False, timeout=1) # nosec if response.status_code == 429: raise RateExceededError return response.json() except (requests.ReadTimeout, requests.ConnectTimeout): pass return {}
Get information about an IP. Args: ip (str): an IP (xxx.xxx.xxx.xxx). Returns: dict: see http://ipinfo.io/developers/getting-started
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/ip_info.py#L100-L122
null
class IpInfoHandler(BaseRequestRateHandler): rate = 1000 per = 3600 * 24 def format(self, data): loc = data.get('loc', None) lat = lon = '' if loc and ',' in loc: lat, lon = loc.split(',') return dict( latitude=lat, longitude=lon, hostname=data.get('hostname', ''), city=data.get('city', ''), region=data.get('region', ''), country=data.get('country', ''), org=data.get('org', '')) def _batch(self, ips): pass
Genida/django-meerkat
src/meerkat/utils/url.py
url_is_project
python
def url_is_project(url, default='not_a_func'): try: u = resolve(url) if u and u.func != default: return True except Resolver404: static_url = settings.STATIC_URL static_url_wd = static_url.lstrip('/') if url.startswith(static_url): url = url[len(static_url):] elif url.startswith(static_url_wd): url = url[len(static_url_wd):] else: return False if finders.find(url): return True return False
Check if URL is part of the current project's URLs. Args: url (str): URL to check. default (callable): used to filter out some URLs attached to function. Returns:
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/url.py#L14-L40
null
# -*- coding: utf-8 -*- """URL utils.""" from django.conf import settings from django.contrib.staticfiles import finders from django.core.urlresolvers import Resolver404, resolve from ..apps import AppSettings app_settings = AppSettings() def url_is(white_list): """ Function generator. Args: white_list (dict): dict with PREFIXES and CONSTANTS keys (list values). Returns: func: a function to check if a URL is... """ def func(url): prefixes = white_list.get('PREFIXES', ()) for prefix in prefixes: if url.startswith(prefix): return True constants = white_list.get('CONSTANTS', ()) for exact_url in constants: if url == exact_url: return True return False return func ASSET = 1 PROJECT = 2 OLD_ASSET = 3 COMMON_ASSET = 4 OLD_PROJECT = 5 FALSE_NEGATIVE = 6 SUSPICIOUS = 7 IGNORED = 8 URL_TYPE = { ASSET: 'ASSET', PROJECT: 'PROJECT', OLD_ASSET: 'OLD_ASSET', COMMON_ASSET: 'COMMON_ASSET', OLD_PROJECT: 'OLD_PROJECT', FALSE_NEGATIVE: 'FALSE_NEGATIVE', SUSPICIOUS: 'SUSPICIOUS', IGNORED: 'IGNORED' } URL_TYPE_REVERSE = {v: k for k, v in URL_TYPE.items()} URL_WHITELIST = app_settings.logs_url_whitelist url_is_asset = url_is(URL_WHITELIST[URL_TYPE[ASSET]]) url_is_old_asset = url_is(URL_WHITELIST[URL_TYPE[OLD_ASSET]]) url_is_common_asset = url_is(URL_WHITELIST[URL_TYPE[COMMON_ASSET]]) url_is_old_project = url_is(URL_WHITELIST[URL_TYPE[OLD_PROJECT]]) url_is_false_negative = url_is(URL_WHITELIST[URL_TYPE[FALSE_NEGATIVE]]) url_is_ignored = url_is(URL_WHITELIST[URL_TYPE[IGNORED]])
Genida/django-meerkat
src/meerkat/utils/url.py
url_is
python
def url_is(white_list): def func(url): prefixes = white_list.get('PREFIXES', ()) for prefix in prefixes: if url.startswith(prefix): return True constants = white_list.get('CONSTANTS', ()) for exact_url in constants: if url == exact_url: return True return False return func
Function generator. Args: white_list (dict): dict with PREFIXES and CONSTANTS keys (list values). Returns: func: a function to check if a URL is...
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/url.py#L43-L63
null
# -*- coding: utf-8 -*- """URL utils.""" from django.conf import settings from django.contrib.staticfiles import finders from django.core.urlresolvers import Resolver404, resolve from ..apps import AppSettings app_settings = AppSettings() def url_is_project(url, default='not_a_func'): """ Check if URL is part of the current project's URLs. Args: url (str): URL to check. default (callable): used to filter out some URLs attached to function. Returns: """ try: u = resolve(url) if u and u.func != default: return True except Resolver404: static_url = settings.STATIC_URL static_url_wd = static_url.lstrip('/') if url.startswith(static_url): url = url[len(static_url):] elif url.startswith(static_url_wd): url = url[len(static_url_wd):] else: return False if finders.find(url): return True return False ASSET = 1 PROJECT = 2 OLD_ASSET = 3 COMMON_ASSET = 4 OLD_PROJECT = 5 FALSE_NEGATIVE = 6 SUSPICIOUS = 7 IGNORED = 8 URL_TYPE = { ASSET: 'ASSET', PROJECT: 'PROJECT', OLD_ASSET: 'OLD_ASSET', COMMON_ASSET: 'COMMON_ASSET', OLD_PROJECT: 'OLD_PROJECT', FALSE_NEGATIVE: 'FALSE_NEGATIVE', SUSPICIOUS: 'SUSPICIOUS', IGNORED: 'IGNORED' } URL_TYPE_REVERSE = {v: k for k, v in URL_TYPE.items()} URL_WHITELIST = app_settings.logs_url_whitelist url_is_asset = url_is(URL_WHITELIST[URL_TYPE[ASSET]]) url_is_old_asset = url_is(URL_WHITELIST[URL_TYPE[OLD_ASSET]]) url_is_common_asset = url_is(URL_WHITELIST[URL_TYPE[COMMON_ASSET]]) url_is_old_project = url_is(URL_WHITELIST[URL_TYPE[OLD_PROJECT]]) url_is_false_negative = url_is(URL_WHITELIST[URL_TYPE[FALSE_NEGATIVE]]) url_is_ignored = url_is(URL_WHITELIST[URL_TYPE[IGNORED]])
Genida/django-meerkat
src/meerkat/utils/time.py
daterange
python
def daterange(start_date, end_date): for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n)
Yield one date per day from starting date to ending date. Args: start_date (date): starting date. end_date (date): ending date. Yields: date: a date for each day within the range.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/time.py#L21-L33
null
# -*- coding: utf-8 -*- """Time utils.""" from datetime import datetime, timedelta def ms_since_epoch(dt): """ Get the milliseconds since epoch until specific a date and time. Args: dt (datetime): date and time limit. Returns: int: number of milliseconds. """ return (dt - datetime(1970, 1, 1)).total_seconds() * 1000 def log_date_to_python_date(s): """ Convert a log date (string) to a Python date object. Args: s (str): string representing the date ('%d/%b/%Y'). Returns: date: Python date object. """ return datetime.strptime(s, '%d/%b/%Y').date() def log_datetime_to_python_datetime(s): """ Convert a log datetime (string) to a Python datetime object. Args: s (str): string representing the datetime ('%d/%b/%Y:%H:%M:%S +%z'). Returns: datetime: Python datetime object. """ return datetime.strptime(s, '%d/%b/%Y:%H:%M:%S +%z') def log_datetime_to_python_date(s): """ Convert a log datetime (string) to a Python date object. Args: s (str): string representing the datetime ('%d/%b/%Y:%H:%M:%S +%z'). Returns: date: Python date object. """ return log_datetime_to_python_datetime(s).date() def month_name_to_number(month, to_int=False): """ Convert a month name (MMM) to its number (01-12). Args: month (str): 3-letters string describing month. to_int (bool): cast number to int or not. Returns: str/int: the month's number (between 01 and 12). """ number = { 'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12', }.get(month) return int(number) if to_int else number
Genida/django-meerkat
src/meerkat/utils/time.py
month_name_to_number
python
def month_name_to_number(month, to_int=False): number = { 'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12', }.get(month) return int(number) if to_int else number
Convert a month name (MMM) to its number (01-12). Args: month (str): 3-letters string describing month. to_int (bool): cast number to int or not. Returns: str/int: the month's number (between 01 and 12).
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/time.py#L75-L91
null
# -*- coding: utf-8 -*- """Time utils.""" from datetime import datetime, timedelta def ms_since_epoch(dt): """ Get the milliseconds since epoch until specific a date and time. Args: dt (datetime): date and time limit. Returns: int: number of milliseconds. """ return (dt - datetime(1970, 1, 1)).total_seconds() * 1000 def daterange(start_date, end_date): """ Yield one date per day from starting date to ending date. Args: start_date (date): starting date. end_date (date): ending date. Yields: date: a date for each day within the range. """ for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n) def log_date_to_python_date(s): """ Convert a log date (string) to a Python date object. Args: s (str): string representing the date ('%d/%b/%Y'). Returns: date: Python date object. """ return datetime.strptime(s, '%d/%b/%Y').date() def log_datetime_to_python_datetime(s): """ Convert a log datetime (string) to a Python datetime object. Args: s (str): string representing the datetime ('%d/%b/%Y:%H:%M:%S +%z'). Returns: datetime: Python datetime object. """ return datetime.strptime(s, '%d/%b/%Y:%H:%M:%S +%z') def log_datetime_to_python_date(s): """ Convert a log datetime (string) to a Python date object. Args: s (str): string representing the datetime ('%d/%b/%Y:%H:%M:%S +%z'). Returns: date: Python date object. """ return log_datetime_to_python_datetime(s).date()
Genida/django-meerkat
src/meerkat/logs/models.py
IPInfo.get_or_create_from_ip
python
def get_or_create_from_ip(ip): data = ip_api_handler.get(ip) if data and any(v for v in data.values()): if data.get('ip_address', None) is None or not data['ip_address']: data['ip_address'] = ip return IPInfo.objects.get_or_create(**data) return None, False
Get or create an entry using obtained information from an IP. Args: ip (str): IP address xxx.xxx.xxx.xxx. Returns: ip_info: an instance of IPInfo.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/models.py#L128-L143
[ "def get(self, ip, wait=True):\n if self.can_hit():\n response = self._get(ip)\n self.hit()\n return self.format(response)\n elif wait:\n time.sleep(self.time_to_wait())\n return self.get(ip, wait)\n return None\n" ]
class IPInfo(models.Model): """A model to store IP address information.""" # Even if we have a paid account on some ip info service, # an IP address had unique information at the time of the # request. Therefore, this information must be stored in the DB # if we want to compute statistical data about it. We cannot query # web-services each time we want to do this (data changed over time). ip_address = models.GenericIPAddressField( verbose_name=_('IP address')) org = models.CharField( verbose_name=_('Organization'), max_length=255, blank=True) asn = models.CharField( verbose_name=_('Autonomous System'), max_length=255, blank=True) isp = models.CharField( verbose_name=_('Internet Service Provider'), max_length=255, blank=True) proxy = models.NullBooleanField( verbose_name=_('Proxy')) hostname = models.CharField( verbose_name=_('Hostname'), max_length=255, blank=True) continent = models.CharField( verbose_name=_('Continent'), max_length=255, blank=True) continent_code = models.CharField( verbose_name=_('Continent code'), max_length=255, blank=True) country = models.CharField( verbose_name=_('Country'), max_length=255, blank=True) country_code = models.CharField( verbose_name=_('Country code'), max_length=255, blank=True) region = models.CharField( verbose_name=_('Region'), max_length=255, blank=True) region_code = models.CharField( verbose_name=_('Region code'), max_length=255, blank=True) city = models.CharField( verbose_name=_('City'), max_length=255, blank=True) city_code = models.CharField( verbose_name=_('City code'), max_length=255, blank=True) # TODO: maybe store latitude and longitude as Float? latitude = models.CharField( verbose_name=_('Latitude'), max_length=255, blank=True) longitude = models.CharField( verbose_name=_('Longitude'), max_length=255, blank=True) class Meta: """Meta class for Django.""" unique_together = ( 'ip_address', 'continent', 'continent_code', 'country', 'country_code', 'region', 'region_code', 'city', 'city_code', 'latitude', 'longitude', 'org', 'asn', 'isp', 'proxy', 'hostname') verbose_name = _('IP address information') verbose_name_plural = _('IP address information') def __str__(self): for attr in (self.org, self.hostname, self.asn, self.isp, self.city, self.city_code, self.region, self.region_code, self.country, self.country_code): if attr: return attr if self.latitude and self.longitude: return '%s,%s' % (self.latitude, self.longitude) return repr(self) @staticmethod def ip_addresses(self): return list(IPInfoCheck.objects.filter( ip_info=self).values_list('ip_address', flat=True))
Genida/django-meerkat
src/meerkat/logs/models.py
RequestLog.update_ip_info
python
def update_ip_info(self, since_days=10, save=False, force=False): # If ip already checked try: last_check = IPInfoCheck.objects.get( ip_address=self.client_ip_address) # If checked less than since_days ago, don't check again since_last = datetime.date.today() - last_check.date if since_last <= datetime.timedelta(days=since_days): if not self.ip_info or ( self.ip_info != last_check.ip_info and force): self.ip_info = last_check.ip_info self.save() return True elif save: self.save() return False # Get or create ip_info object ip_info, created = IPInfo.get_or_create_from_ip( self.client_ip_address) # Update check time last_check.date = datetime.date.today() last_check.save() # Maybe data changed if created: last_check.ip_info = ip_info self.ip_info = ip_info self.save() return True elif save: self.save() return False except IPInfoCheck.DoesNotExist: # Else if ip never checked, check it and set ip_info self.ip_info = IPInfoCheck.check_ip(self.client_ip_address) self.save() return True
Update the IP info. Args: since_days (int): if checked less than this number of days ago, don't check again (default to 10 days). save (bool): whether to save anyway or not. force (bool): whether to update ip_info to last checked one. Returns: bool: check was run. IPInfo might not have been updated.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/models.py#L333-L387
[ "def check_ip(ip):\n ip_info, _ = IPInfo.get_or_create_from_ip(ip)\n if ip_info:\n IPInfoCheck.objects.create(ip_address=ip, ip_info=ip_info)\n return ip_info\n return None\n" ]
class RequestLog(models.Model): """A model to store the request logs.""" VERBS = ['CONNECT', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT' 'TRACE', 'DELETE', 'PATCH'] PROTOCOLS = ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2.0', 'RTSP/1.0', 'SIP/2.0'] REQUEST_REGEX = re.compile( r'(?P<verb>%s) (?P<url>[^\s]+?) (?P<protocol>%s)' % ( '|'.join(VERBS), '|'.join(PROTOCOLS))) url_validator = URLValidator() daemon = None # General info client_ip_address = models.GenericIPAddressField( verbose_name=_('Client IP address'), blank=True, null=True) datetime = models.DateTimeField( verbose_name=_('Datetime'), blank=True) timezone = models.CharField( verbose_name=_('Timezone'), max_length=10, blank=True) url = models.URLField( verbose_name=_('URL'), max_length=2047, blank=True) status_code = models.SmallIntegerField( verbose_name=_('Status code'), blank=True) user_agent = models.TextField( verbose_name=_('User agent'), blank=True) referrer = models.TextField( verbose_name=_('Referrer'), blank=True) upstream = models.TextField( verbose_name=_('Upstream'), blank=True) host = models.TextField( verbose_name=_('Host'), blank=True) server = models.TextField( verbose_name=_('Server'), blank=True) verb = models.CharField( verbose_name=_('Verb'), max_length=30, blank=True) protocol = models.CharField( verbose_name=_('Protocol'), max_length=30, blank=True) port = models.PositiveIntegerField( verbose_name=_('Port'), blank=True, null=True) file_type = models.CharField( verbose_name=_('File type'), max_length=30, blank=True) https = models.NullBooleanField( verbose_name=_('HTTPS')) bytes_sent = models.IntegerField( verbose_name=_('Bytes sent'), blank=True) request = models.TextField( verbose_name=_('Request'), blank=True) request_body = models.TextField( verbose_name=_('Request body'), blank=True) # Error logs error = models.BooleanField( verbose_name=_('Error'), default=False) level = models.CharField( verbose_name=_('Level'), max_length=255, blank=True) message = models.TextField( verbose_name=_('Message'), blank=True) # IPInfo ip_info = models.ForeignKey( IPInfo, verbose_name=_('IP Info'), null=True) # Other suspicious = models.NullBooleanField( verbose_name=_('Suspicious')) # Not really useful for now # response_time = models.TimeField() # response_header = models.TextField() # response_body = models.TextField() # # proxy_host = models.CharField(max_length=255) # proxy_port = models.PositiveIntegerField() # proxy_protocol_address = models.CharField(max_length=255) # proxy_protocol_port = models.PositiveIntegerField() # # ssl_cipher = models.CharField(max_length=255) # ssl_client_cert = models.CharField(max_length=255) # ssl_client_fingerprint = models.CharField(max_length=255) # ssl_client_i_dn = models.CharField(max_length=255) # ssl_client_raw_cert = models.CharField(max_length=255) # ssl_client_s_dn = models.CharField(max_length=255) # ssl_client_serial = models.CharField(max_length=255) # ssl_client_verify = models.CharField(max_length=255) # ssl_protocol = models.CharField(max_length=255) # ssl_server_name = models.CharField(max_length=255) # ssl_session_id = models.CharField(max_length=255) # ssl_session_reused = models.CharField(max_length=255) # # tcp_info_rtt = models.CharField(max_length=255) # tcp_info_rtt_var = models.CharField(max_length=255) # tcp_info_snd_cwnd = models.CharField(max_length=255) # tcp_info_rcv_space = models.CharField(max_length=255) # # upstream_address = models.CharField(max_length=255) # upstream_cache_status = models.CharField(max_length=255) # upstream_connect_time = models.CharField(max_length=255) # upstream_cookie = models.CharField(max_length=255) # upstream_header_time = models.CharField(max_length=255) # upstream_http = models.CharField(max_length=255) # upstream_response_length = models.CharField(max_length=255) # upstream_response_time = models.CharField(max_length=255) # upstream_status = models.CharField(max_length=255) class Meta: """Meta class for Django.""" verbose_name = _('Request log') verbose_name_plural = _('Request logs') class ParseToDBThread(StoppableThread): def __init__(self, parser, *args, **kwargs): super(RequestLog.ParseToDBThread, self).__init__(*args, **kwargs) self.parser = parser def run(self): matching_files = self.parser.matching_files() if len(matching_files) > 1: print('Meerkat logs: more than 1 matching log file, ' 'cannot follow') return elif not matching_files: print('Meerkat logs: no matching log files, cannot follow') return file_name = matching_files[0] seek_end = True while True: for line in follow(file_name, seek_end, 1, self.stopped): try: data = self.parser.parse_string(line) except AttributeError: # TODO: log the line print("Meerkat: can't parse log line: %s" % line) continue log_object = RequestLog(**self.parser.format_data(data)) log_object.complete() log_object.update_ip_info(save=True) if self.stopped(): break if self.stopped(): break seek_end = False def __str__(self): return str(self.datetime) def validate_url(self, url=None): if url is None: url = self.url for u in (url, 'http://localhost/%s' % url): try: self.url_validator(u) return True except ValidationError: pass return False def _request_to_verb_url_protocol(self): try: return re.match(self.REQUEST_REGEX, self.request).groupdict() except AttributeError: return {} def complete_verb_url_protocol(self, rewrite_verb=True, rewrite_protocol=True, rewrite_url=True, strict_url=False, save=True): data = self._request_to_verb_url_protocol() if not data: return False modified_verb = self.complete_verb( data=data, rewrite=rewrite_verb, save=False) modified_url = self.complete_url( data=data, strict=strict_url, rewrite=rewrite_url, save=False) modified_protocol = self.complete_protocol( data=data, rewrite=rewrite_protocol, save=False) modified = modified_verb | modified_url | modified_protocol if modified and save: self.save() return modified def complete_verb(self, data=None, rewrite=True, save=True): modified = False if not data: data = self._request_to_verb_url_protocol() if not data: return False if not self.verb or (rewrite and self.verb != data['verb']): self.verb = data['verb'] modified = True if modified and save: self.save() return modified def complete_url(self, data=None, strict=False, rewrite=True, save=True): modified = False if not data: data = self._request_to_verb_url_protocol() if not data: return False if not self.url or (rewrite and self.url != data['url']): if strict: if self.validate_url(data['url']): self.url = data['url'] modified = True else: self.url = data['url'] modified = True if modified and save: self.save() return modified def complete_protocol(self, data=None, rewrite=True, save=True): modified = False if not data: data = self._request_to_verb_url_protocol() if not data: return False if not self.protocol or ( rewrite and self.protocol != data['protocol']): self.protocol = data['protocol'] modified = True if modified and save: self.save() return modified def complete_https(self, rewrite=True, save=True): modified = False https = None # TODO: implement complete_https if not self.https or (rewrite and self.https != https): self.https = https modified = True if modified and save: self.save() return modified # FIXME: use urllib parse_url? def _url_end(self, contains=''): url = self.url if not url: url = self._request_to_verb_url_protocol().get('url', None) if url and contains in url: end = url if '?' in url: end = end.split('?')[0] elif '%3F' in url: end = end.split('%3F')[0] return end.split('/')[-1] return '' def complete_file_type(self, rewrite=True, save=True): modified = False file_type = '' end = self._url_end(contains='.') if '.' in end: file_type = end.split('.')[-1].upper() file_type = file_type.split(':')[0] if not self.file_type or (rewrite and self.file_type != file_type): self.file_type = file_type modified = True if modified and save: self.save() return modified def complete_port(self, rewrite=True, save=True): modified = False port = None end = self._url_end(contains=':') if ':' in end: port = end.split(':')[-1].upper() try: port = int(port) except ValueError: port = None if not self.port or (rewrite and self.port != port): self.port = port modified = True if modified and save: self.save() return modified def complete_suspicious(self, rewrite=True, save=True): modified = False suspicious = None # TODO: implement complete_suspicious if not self.suspicious or (rewrite and self.suspicious != suspicious): self.suspicious = suspicious modified = True if modified and save: self.save() return modified def complete(self, rewrite=True, save=True, **kwargs): rewrite_verb = kwargs.pop('rewrite_verb', rewrite) rewrite_url = kwargs.pop('rewrite_url', rewrite) rewrite_protocol = kwargs.pop('rewrite_protocol', rewrite) rewrite_https = kwargs.pop('rewrite_https', rewrite) rewrite_file_type = kwargs.pop('rewrite_file_type', rewrite) rewrite_suspicious = kwargs.pop('rewrite_suspicious', rewrite) strict_url = kwargs.pop('strict_url', False) modified_vup = self.complete_verb_url_protocol( rewrite_verb=rewrite_verb, rewrite_url=rewrite_url, rewrite_protocol=rewrite_protocol, strict_url=strict_url, save=False) modified_https = self.complete_https( rewrite=rewrite_https, save=False) modified_file_type = self.complete_file_type( rewrite=rewrite_file_type, save=False) modified_port = self.complete_port( rewrite=rewrite_file_type, save=False) modified_suspicious = self.complete_suspicious( rewrite=rewrite_suspicious, save=False) modified = any(( modified_vup, modified_https, modified_file_type, modified_port, modified_suspicious)) if modified and save: self.save() return modified @staticmethod def autocomplete(queryset, batch_size=512, rewrite=True, progress=True, **kwargs): # noqa # perf improvement: avoid QuerySet.__getitem__ when doing qs[i] # FIXME: though we may need to buffer because the queryset can be huge total = queryset.count() progress_bar = ProgressBar(sys.stdout if progress else None, total) print('Completing information for %s request logs' % total) count = 0 start = datetime.datetime.now() while count < total: buffer = queryset[count:count+batch_size] with transaction.atomic(): # is this a real improvement? for obj in buffer: obj.complete(rewrite=rewrite, **kwargs) count += 1 progress_bar.update(count) # end transaction end = datetime.datetime.now() print('Elapsed time: %s' % (end - start)) @staticmethod def parse_all(buffer_size=512, progress=True): parser = get_nginx_parser() buffer = [] start = datetime.datetime.now() for log_file in parser.matching_files(): n_lines = count_lines(log_file) progress_bar = ProgressBar(sys.stdout if progress else None, n_lines) # noqa print('Reading log file %s: %s lines' % (log_file, n_lines)) with open(log_file) as f: for count, line in enumerate(f, 1): try: data = parser.parse_string(line) except AttributeError: # TODO: log the line print('Error while parsing log line: %s' % line) continue log_object = RequestLog(**parser.format_data(data)) log_object.complete(save=False) buffer.append(log_object) if len(buffer) >= buffer_size: RequestLog.objects.bulk_create(buffer) buffer.clear() progress_bar.update(count) if len(buffer) > 0: RequestLog.objects.bulk_create(buffer) buffer.clear() end = datetime.datetime.now() print('Elapsed time: %s' % (end - start)) @staticmethod def get_ip_info(only_update=False): param = 'client_ip_address' if not only_update: unique_ips = set(RequestLog.objects.distinct(param).values_list(param, flat=True)) # noqa checked_ips = set(IPInfoCheck.objects.values_list('ip_address', flat=True)) # noqa not_checked_ips = unique_ips - checked_ips print('Checking IP addresses information (%s)' % len(not_checked_ips)) check_progress_bar = ProgressBar(sys.stdout, len(not_checked_ips)) for count, ip in enumerate(not_checked_ips, 1): try: IPInfoCheck.check_ip(ip) except RateExceededError: print(' Rate exceeded') break check_progress_bar.update(count) no_ip_info = RequestLog.objects.filter(ip_info=None) no_ip_info_ip = set(no_ip_info.distinct(param).values_list(param, flat=True)) # noqa checks = IPInfoCheck.objects.filter(ip_address__in=no_ip_info_ip) print('Updating request logs\' IP info (%s)' % no_ip_info.count()) print('%s related checks' % checks.count()) logs_progress_bar = ProgressBar(sys.stdout, checks.count()) for count, check in enumerate(checks, 1): no_ip_info.filter( client_ip_address=check.ip_address ).update(ip_info=check.ip_info) logs_progress_bar.update(count) @staticmethod def start_daemon(): """ Start a thread to continuously read log files and append lines in DB. Work in progress. Currently the thread doesn't append anything, it only print the information parsed from each line read. Returns: thread: the started thread. """ if RequestLog.daemon is None: parser = get_nginx_parser() RequestLog.daemon = RequestLog.ParseToDBThread(parser, daemon=True) RequestLog.daemon.start() return RequestLog.daemon @staticmethod def stop_daemon(): if hasattr(RequestLog, 'daemon'): RequestLog.daemon.stop() RequestLog.daemon.join()
Genida/django-meerkat
src/meerkat/logs/models.py
RequestLog.start_daemon
python
def start_daemon(): if RequestLog.daemon is None: parser = get_nginx_parser() RequestLog.daemon = RequestLog.ParseToDBThread(parser, daemon=True) RequestLog.daemon.start() return RequestLog.daemon
Start a thread to continuously read log files and append lines in DB. Work in progress. Currently the thread doesn't append anything, it only print the information parsed from each line read. Returns: thread: the started thread.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/models.py#L648-L662
[ "def get_nginx_parser():\n file_path_regex = app_settings.logs_file_path_regex\n log_format_regex = app_settings.logs_format_regex\n top_dir = app_settings.logs_top_dir\n\n return NginXAccessLogParser(\n file_path_regex=file_path_regex if file_path_regex else None,\n log_format_regex=log_f...
class RequestLog(models.Model): """A model to store the request logs.""" VERBS = ['CONNECT', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT' 'TRACE', 'DELETE', 'PATCH'] PROTOCOLS = ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2.0', 'RTSP/1.0', 'SIP/2.0'] REQUEST_REGEX = re.compile( r'(?P<verb>%s) (?P<url>[^\s]+?) (?P<protocol>%s)' % ( '|'.join(VERBS), '|'.join(PROTOCOLS))) url_validator = URLValidator() daemon = None # General info client_ip_address = models.GenericIPAddressField( verbose_name=_('Client IP address'), blank=True, null=True) datetime = models.DateTimeField( verbose_name=_('Datetime'), blank=True) timezone = models.CharField( verbose_name=_('Timezone'), max_length=10, blank=True) url = models.URLField( verbose_name=_('URL'), max_length=2047, blank=True) status_code = models.SmallIntegerField( verbose_name=_('Status code'), blank=True) user_agent = models.TextField( verbose_name=_('User agent'), blank=True) referrer = models.TextField( verbose_name=_('Referrer'), blank=True) upstream = models.TextField( verbose_name=_('Upstream'), blank=True) host = models.TextField( verbose_name=_('Host'), blank=True) server = models.TextField( verbose_name=_('Server'), blank=True) verb = models.CharField( verbose_name=_('Verb'), max_length=30, blank=True) protocol = models.CharField( verbose_name=_('Protocol'), max_length=30, blank=True) port = models.PositiveIntegerField( verbose_name=_('Port'), blank=True, null=True) file_type = models.CharField( verbose_name=_('File type'), max_length=30, blank=True) https = models.NullBooleanField( verbose_name=_('HTTPS')) bytes_sent = models.IntegerField( verbose_name=_('Bytes sent'), blank=True) request = models.TextField( verbose_name=_('Request'), blank=True) request_body = models.TextField( verbose_name=_('Request body'), blank=True) # Error logs error = models.BooleanField( verbose_name=_('Error'), default=False) level = models.CharField( verbose_name=_('Level'), max_length=255, blank=True) message = models.TextField( verbose_name=_('Message'), blank=True) # IPInfo ip_info = models.ForeignKey( IPInfo, verbose_name=_('IP Info'), null=True) # Other suspicious = models.NullBooleanField( verbose_name=_('Suspicious')) # Not really useful for now # response_time = models.TimeField() # response_header = models.TextField() # response_body = models.TextField() # # proxy_host = models.CharField(max_length=255) # proxy_port = models.PositiveIntegerField() # proxy_protocol_address = models.CharField(max_length=255) # proxy_protocol_port = models.PositiveIntegerField() # # ssl_cipher = models.CharField(max_length=255) # ssl_client_cert = models.CharField(max_length=255) # ssl_client_fingerprint = models.CharField(max_length=255) # ssl_client_i_dn = models.CharField(max_length=255) # ssl_client_raw_cert = models.CharField(max_length=255) # ssl_client_s_dn = models.CharField(max_length=255) # ssl_client_serial = models.CharField(max_length=255) # ssl_client_verify = models.CharField(max_length=255) # ssl_protocol = models.CharField(max_length=255) # ssl_server_name = models.CharField(max_length=255) # ssl_session_id = models.CharField(max_length=255) # ssl_session_reused = models.CharField(max_length=255) # # tcp_info_rtt = models.CharField(max_length=255) # tcp_info_rtt_var = models.CharField(max_length=255) # tcp_info_snd_cwnd = models.CharField(max_length=255) # tcp_info_rcv_space = models.CharField(max_length=255) # # upstream_address = models.CharField(max_length=255) # upstream_cache_status = models.CharField(max_length=255) # upstream_connect_time = models.CharField(max_length=255) # upstream_cookie = models.CharField(max_length=255) # upstream_header_time = models.CharField(max_length=255) # upstream_http = models.CharField(max_length=255) # upstream_response_length = models.CharField(max_length=255) # upstream_response_time = models.CharField(max_length=255) # upstream_status = models.CharField(max_length=255) class Meta: """Meta class for Django.""" verbose_name = _('Request log') verbose_name_plural = _('Request logs') class ParseToDBThread(StoppableThread): def __init__(self, parser, *args, **kwargs): super(RequestLog.ParseToDBThread, self).__init__(*args, **kwargs) self.parser = parser def run(self): matching_files = self.parser.matching_files() if len(matching_files) > 1: print('Meerkat logs: more than 1 matching log file, ' 'cannot follow') return elif not matching_files: print('Meerkat logs: no matching log files, cannot follow') return file_name = matching_files[0] seek_end = True while True: for line in follow(file_name, seek_end, 1, self.stopped): try: data = self.parser.parse_string(line) except AttributeError: # TODO: log the line print("Meerkat: can't parse log line: %s" % line) continue log_object = RequestLog(**self.parser.format_data(data)) log_object.complete() log_object.update_ip_info(save=True) if self.stopped(): break if self.stopped(): break seek_end = False def __str__(self): return str(self.datetime) def update_ip_info(self, since_days=10, save=False, force=False): """ Update the IP info. Args: since_days (int): if checked less than this number of days ago, don't check again (default to 10 days). save (bool): whether to save anyway or not. force (bool): whether to update ip_info to last checked one. Returns: bool: check was run. IPInfo might not have been updated. """ # If ip already checked try: last_check = IPInfoCheck.objects.get( ip_address=self.client_ip_address) # If checked less than since_days ago, don't check again since_last = datetime.date.today() - last_check.date if since_last <= datetime.timedelta(days=since_days): if not self.ip_info or ( self.ip_info != last_check.ip_info and force): self.ip_info = last_check.ip_info self.save() return True elif save: self.save() return False # Get or create ip_info object ip_info, created = IPInfo.get_or_create_from_ip( self.client_ip_address) # Update check time last_check.date = datetime.date.today() last_check.save() # Maybe data changed if created: last_check.ip_info = ip_info self.ip_info = ip_info self.save() return True elif save: self.save() return False except IPInfoCheck.DoesNotExist: # Else if ip never checked, check it and set ip_info self.ip_info = IPInfoCheck.check_ip(self.client_ip_address) self.save() return True def validate_url(self, url=None): if url is None: url = self.url for u in (url, 'http://localhost/%s' % url): try: self.url_validator(u) return True except ValidationError: pass return False def _request_to_verb_url_protocol(self): try: return re.match(self.REQUEST_REGEX, self.request).groupdict() except AttributeError: return {} def complete_verb_url_protocol(self, rewrite_verb=True, rewrite_protocol=True, rewrite_url=True, strict_url=False, save=True): data = self._request_to_verb_url_protocol() if not data: return False modified_verb = self.complete_verb( data=data, rewrite=rewrite_verb, save=False) modified_url = self.complete_url( data=data, strict=strict_url, rewrite=rewrite_url, save=False) modified_protocol = self.complete_protocol( data=data, rewrite=rewrite_protocol, save=False) modified = modified_verb | modified_url | modified_protocol if modified and save: self.save() return modified def complete_verb(self, data=None, rewrite=True, save=True): modified = False if not data: data = self._request_to_verb_url_protocol() if not data: return False if not self.verb or (rewrite and self.verb != data['verb']): self.verb = data['verb'] modified = True if modified and save: self.save() return modified def complete_url(self, data=None, strict=False, rewrite=True, save=True): modified = False if not data: data = self._request_to_verb_url_protocol() if not data: return False if not self.url or (rewrite and self.url != data['url']): if strict: if self.validate_url(data['url']): self.url = data['url'] modified = True else: self.url = data['url'] modified = True if modified and save: self.save() return modified def complete_protocol(self, data=None, rewrite=True, save=True): modified = False if not data: data = self._request_to_verb_url_protocol() if not data: return False if not self.protocol or ( rewrite and self.protocol != data['protocol']): self.protocol = data['protocol'] modified = True if modified and save: self.save() return modified def complete_https(self, rewrite=True, save=True): modified = False https = None # TODO: implement complete_https if not self.https or (rewrite and self.https != https): self.https = https modified = True if modified and save: self.save() return modified # FIXME: use urllib parse_url? def _url_end(self, contains=''): url = self.url if not url: url = self._request_to_verb_url_protocol().get('url', None) if url and contains in url: end = url if '?' in url: end = end.split('?')[0] elif '%3F' in url: end = end.split('%3F')[0] return end.split('/')[-1] return '' def complete_file_type(self, rewrite=True, save=True): modified = False file_type = '' end = self._url_end(contains='.') if '.' in end: file_type = end.split('.')[-1].upper() file_type = file_type.split(':')[0] if not self.file_type or (rewrite and self.file_type != file_type): self.file_type = file_type modified = True if modified and save: self.save() return modified def complete_port(self, rewrite=True, save=True): modified = False port = None end = self._url_end(contains=':') if ':' in end: port = end.split(':')[-1].upper() try: port = int(port) except ValueError: port = None if not self.port or (rewrite and self.port != port): self.port = port modified = True if modified and save: self.save() return modified def complete_suspicious(self, rewrite=True, save=True): modified = False suspicious = None # TODO: implement complete_suspicious if not self.suspicious or (rewrite and self.suspicious != suspicious): self.suspicious = suspicious modified = True if modified and save: self.save() return modified def complete(self, rewrite=True, save=True, **kwargs): rewrite_verb = kwargs.pop('rewrite_verb', rewrite) rewrite_url = kwargs.pop('rewrite_url', rewrite) rewrite_protocol = kwargs.pop('rewrite_protocol', rewrite) rewrite_https = kwargs.pop('rewrite_https', rewrite) rewrite_file_type = kwargs.pop('rewrite_file_type', rewrite) rewrite_suspicious = kwargs.pop('rewrite_suspicious', rewrite) strict_url = kwargs.pop('strict_url', False) modified_vup = self.complete_verb_url_protocol( rewrite_verb=rewrite_verb, rewrite_url=rewrite_url, rewrite_protocol=rewrite_protocol, strict_url=strict_url, save=False) modified_https = self.complete_https( rewrite=rewrite_https, save=False) modified_file_type = self.complete_file_type( rewrite=rewrite_file_type, save=False) modified_port = self.complete_port( rewrite=rewrite_file_type, save=False) modified_suspicious = self.complete_suspicious( rewrite=rewrite_suspicious, save=False) modified = any(( modified_vup, modified_https, modified_file_type, modified_port, modified_suspicious)) if modified and save: self.save() return modified @staticmethod def autocomplete(queryset, batch_size=512, rewrite=True, progress=True, **kwargs): # noqa # perf improvement: avoid QuerySet.__getitem__ when doing qs[i] # FIXME: though we may need to buffer because the queryset can be huge total = queryset.count() progress_bar = ProgressBar(sys.stdout if progress else None, total) print('Completing information for %s request logs' % total) count = 0 start = datetime.datetime.now() while count < total: buffer = queryset[count:count+batch_size] with transaction.atomic(): # is this a real improvement? for obj in buffer: obj.complete(rewrite=rewrite, **kwargs) count += 1 progress_bar.update(count) # end transaction end = datetime.datetime.now() print('Elapsed time: %s' % (end - start)) @staticmethod def parse_all(buffer_size=512, progress=True): parser = get_nginx_parser() buffer = [] start = datetime.datetime.now() for log_file in parser.matching_files(): n_lines = count_lines(log_file) progress_bar = ProgressBar(sys.stdout if progress else None, n_lines) # noqa print('Reading log file %s: %s lines' % (log_file, n_lines)) with open(log_file) as f: for count, line in enumerate(f, 1): try: data = parser.parse_string(line) except AttributeError: # TODO: log the line print('Error while parsing log line: %s' % line) continue log_object = RequestLog(**parser.format_data(data)) log_object.complete(save=False) buffer.append(log_object) if len(buffer) >= buffer_size: RequestLog.objects.bulk_create(buffer) buffer.clear() progress_bar.update(count) if len(buffer) > 0: RequestLog.objects.bulk_create(buffer) buffer.clear() end = datetime.datetime.now() print('Elapsed time: %s' % (end - start)) @staticmethod def get_ip_info(only_update=False): param = 'client_ip_address' if not only_update: unique_ips = set(RequestLog.objects.distinct(param).values_list(param, flat=True)) # noqa checked_ips = set(IPInfoCheck.objects.values_list('ip_address', flat=True)) # noqa not_checked_ips = unique_ips - checked_ips print('Checking IP addresses information (%s)' % len(not_checked_ips)) check_progress_bar = ProgressBar(sys.stdout, len(not_checked_ips)) for count, ip in enumerate(not_checked_ips, 1): try: IPInfoCheck.check_ip(ip) except RateExceededError: print(' Rate exceeded') break check_progress_bar.update(count) no_ip_info = RequestLog.objects.filter(ip_info=None) no_ip_info_ip = set(no_ip_info.distinct(param).values_list(param, flat=True)) # noqa checks = IPInfoCheck.objects.filter(ip_address__in=no_ip_info_ip) print('Updating request logs\' IP info (%s)' % no_ip_info.count()) print('%s related checks' % checks.count()) logs_progress_bar = ProgressBar(sys.stdout, checks.count()) for count, check in enumerate(checks, 1): no_ip_info.filter( client_ip_address=check.ip_address ).update(ip_info=check.ip_info) logs_progress_bar.update(count) @staticmethod @staticmethod def stop_daemon(): if hasattr(RequestLog, 'daemon'): RequestLog.daemon.stop() RequestLog.daemon.join()
Genida/django-meerkat
src/meerkat/utils/list.py
distinct
python
def distinct(l): seen = set() seen_add = seen.add return (_ for _ in l if not (_ in seen or seen_add(_)))
Return a list where the duplicates have been removed. Args: l (list): the list to filter. Returns: list: the same list without duplicates.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/utils/list.py#L6-L18
null
# -*- coding: utf-8 -*- """List utils."""
Genida/django-meerkat
src/meerkat/logs/boxes.py
BoxLogsStatusCodesByDate.context
python
def context(self): stats = status_codes_by_date_stats() attacks_data = [{ 'type': 'line', 'zIndex': 9, 'name': _('Attacks'), 'data': [(v[0], v[1]['attacks']) for v in stats] }] codes_data = [{ 'zIndex': 4, 'name': '2xx', 'data': [(v[0], v[1][200]) for v in stats] }, { 'zIndex': 5, 'name': '3xx', 'data': [(v[0], v[1][300]) for v in stats] }, { 'zIndex': 6, 'name': '4xx', 'data': [(v[0], v[1][400]) for v in stats] }, { 'zIndex': 8, 'name': '5xx', 'data': [(v[0], v[1][500]) for v in stats] }] return {'generic_chart': json.dumps(status_codes_by_date_chart()), 'attacks_data': json.dumps(attacks_data), 'codes_data': json.dumps(codes_data)}
Get the context.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/boxes.py#L68-L100
[ "def status_codes_by_date_chart():\n \"\"\"Chart for status codes by date.\"\"\"\n return {\n 'chart': {\n 'type': 'area',\n 'zoomType': 'x'\n },\n 'title': {'text': None},\n 'xAxis': {'type': 'datetime'},\n 'yAxis': {'title': {'text': None}},\n ...
class BoxLogsStatusCodesByDate(Box): """The status codes by date widget.""" title = _('Status codes by date') template = 'meerkat/logs/status_codes_by_date.html' @property
Genida/django-meerkat
src/meerkat/logs/boxes.py
BoxLogsMostVisitedPages.widgets
python
def widgets(self): widgets = [] for i, chart in enumerate(most_visited_pages_charts()): widgets.append(Widget(html_id='most_visited_chart_%d' % i, content=json.dumps(chart), template='meerkat/widgets/highcharts.html', js_code=['plotOptions.tooltip.pointFormatter'])) return widgets
Get the items.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/boxes.py#L118-L127
[ "def most_visited_pages_charts():\n \"\"\"Chart for most visited pages.\"\"\"\n stats = most_visited_pages_stats()\n\n charts = []\n\n for i, stat in enumerate(stats['more_than_10']):\n bound = stat['bound']\n subset = stat['subset']\n\n chart_options = {\n 'chart': {\n ...
class BoxLogsMostVisitedPages(Box): """The most visited pages legend.""" title = _('Most visited pages') @property
Genida/django-meerkat
src/meerkat/logs/parsers.py
GenericParser.content
python
def content(self): if self._content is None: self._content = self.parse_files() return self._content
Return parsed data. Parse it if not already parsed. Returns: list: list of dictionaries (one for each parsed line).
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/parsers.py#L48-L57
[ "def parse_files(self):\n \"\"\"\n Find the files and parse them.\n\n Returns:\n list: list of dictionaries (one for each parsed line).\n \"\"\"\n log_re = self.log_format_regex\n log_lines = []\n for log_file in self.matching_files():\n with open(log_file) as f:\n matc...
class GenericParser(object): """Generic parser. Customize it with regular expressions.""" file_path_regex = re.compile(r'^.*$') log_format_regex = re.compile(r'^.*$') top_dir = '' def __init__(self, file_path_regex=None, log_format_regex=None, top_dir=None): """ Init method. Args: file_path_regex (regex): the regex to find the log files. log_format_regex (regex): the regex to parse the log files. top_dir (str): the path to the root directory containing the logs. """ if file_path_regex is not None: self.file_path_regex = file_path_regex if log_format_regex is not None: self.log_format_regex = log_format_regex if top_dir is not None: self.top_dir = top_dir self._content = None @property # http://stackoverflow.com/questions/6798097#answer-6799409 def matching_files(self): """ Find files. Returns: list: the list of matching files. """ matching = [] matcher = self.file_path_regex pieces = self.file_path_regex.pattern.split(sep) partial_matchers = list(map(re.compile, ( sep.join(pieces[:i + 1]) for i in range(len(pieces))))) for root, dirs, files in walk(self.top_dir, topdown=True): for i in reversed(range(len(dirs))): dirname = relpath(join(root, dirs[i]), self.top_dir) dirlevel = dirname.count(sep) if not partial_matchers[dirlevel].match(dirname): del dirs[i] for filename in files: if matcher.match(filename): matching.append(abspath(join(root, filename))) return matching def parse_files(self): """ Find the files and parse them. Returns: list: list of dictionaries (one for each parsed line). """ log_re = self.log_format_regex log_lines = [] for log_file in self.matching_files(): with open(log_file) as f: matches = re.finditer(log_re, f.read()) for match in matches: log_lines.append(match.groupdict()) return log_lines def parse_string(self, string): """ Parse just a string. Args: string (str): the log line to parse. Returns: dict: parsed information with regex groups as keys. """ return re.match(self.log_format_regex, string).groupdict() def format_data(self, data): raise NotImplementedError
Genida/django-meerkat
src/meerkat/logs/parsers.py
GenericParser.matching_files
python
def matching_files(self): matching = [] matcher = self.file_path_regex pieces = self.file_path_regex.pattern.split(sep) partial_matchers = list(map(re.compile, ( sep.join(pieces[:i + 1]) for i in range(len(pieces))))) for root, dirs, files in walk(self.top_dir, topdown=True): for i in reversed(range(len(dirs))): dirname = relpath(join(root, dirs[i]), self.top_dir) dirlevel = dirname.count(sep) if not partial_matchers[dirlevel].match(dirname): del dirs[i] for filename in files: if matcher.match(filename): matching.append(abspath(join(root, filename))) return matching
Find files. Returns: list: the list of matching files.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/parsers.py#L60-L84
null
class GenericParser(object): """Generic parser. Customize it with regular expressions.""" file_path_regex = re.compile(r'^.*$') log_format_regex = re.compile(r'^.*$') top_dir = '' def __init__(self, file_path_regex=None, log_format_regex=None, top_dir=None): """ Init method. Args: file_path_regex (regex): the regex to find the log files. log_format_regex (regex): the regex to parse the log files. top_dir (str): the path to the root directory containing the logs. """ if file_path_regex is not None: self.file_path_regex = file_path_regex if log_format_regex is not None: self.log_format_regex = log_format_regex if top_dir is not None: self.top_dir = top_dir self._content = None @property def content(self): """ Return parsed data. Parse it if not already parsed. Returns: list: list of dictionaries (one for each parsed line). """ if self._content is None: self._content = self.parse_files() return self._content # http://stackoverflow.com/questions/6798097#answer-6799409 def parse_files(self): """ Find the files and parse them. Returns: list: list of dictionaries (one for each parsed line). """ log_re = self.log_format_regex log_lines = [] for log_file in self.matching_files(): with open(log_file) as f: matches = re.finditer(log_re, f.read()) for match in matches: log_lines.append(match.groupdict()) return log_lines def parse_string(self, string): """ Parse just a string. Args: string (str): the log line to parse. Returns: dict: parsed information with regex groups as keys. """ return re.match(self.log_format_regex, string).groupdict() def format_data(self, data): raise NotImplementedError
Genida/django-meerkat
src/meerkat/logs/parsers.py
GenericParser.parse_files
python
def parse_files(self): log_re = self.log_format_regex log_lines = [] for log_file in self.matching_files(): with open(log_file) as f: matches = re.finditer(log_re, f.read()) for match in matches: log_lines.append(match.groupdict()) return log_lines
Find the files and parse them. Returns: list: list of dictionaries (one for each parsed line).
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/parsers.py#L86-L100
[ "def matching_files(self):\n \"\"\"\n Find files.\n\n Returns:\n list: the list of matching files.\n \"\"\"\n matching = []\n matcher = self.file_path_regex\n pieces = self.file_path_regex.pattern.split(sep)\n partial_matchers = list(map(re.compile, (\n sep.join(pieces[:i + 1])...
class GenericParser(object): """Generic parser. Customize it with regular expressions.""" file_path_regex = re.compile(r'^.*$') log_format_regex = re.compile(r'^.*$') top_dir = '' def __init__(self, file_path_regex=None, log_format_regex=None, top_dir=None): """ Init method. Args: file_path_regex (regex): the regex to find the log files. log_format_regex (regex): the regex to parse the log files. top_dir (str): the path to the root directory containing the logs. """ if file_path_regex is not None: self.file_path_regex = file_path_regex if log_format_regex is not None: self.log_format_regex = log_format_regex if top_dir is not None: self.top_dir = top_dir self._content = None @property def content(self): """ Return parsed data. Parse it if not already parsed. Returns: list: list of dictionaries (one for each parsed line). """ if self._content is None: self._content = self.parse_files() return self._content # http://stackoverflow.com/questions/6798097#answer-6799409 def matching_files(self): """ Find files. Returns: list: the list of matching files. """ matching = [] matcher = self.file_path_regex pieces = self.file_path_regex.pattern.split(sep) partial_matchers = list(map(re.compile, ( sep.join(pieces[:i + 1]) for i in range(len(pieces))))) for root, dirs, files in walk(self.top_dir, topdown=True): for i in reversed(range(len(dirs))): dirname = relpath(join(root, dirs[i]), self.top_dir) dirlevel = dirname.count(sep) if not partial_matchers[dirlevel].match(dirname): del dirs[i] for filename in files: if matcher.match(filename): matching.append(abspath(join(root, filename))) return matching def parse_string(self, string): """ Parse just a string. Args: string (str): the log line to parse. Returns: dict: parsed information with regex groups as keys. """ return re.match(self.log_format_regex, string).groupdict() def format_data(self, data): raise NotImplementedError
Genida/django-meerkat
src/meerkat/logs/stats.py
status_codes_by_date_stats
python
def status_codes_by_date_stats(): def date_counter(queryset): return dict(Counter(map( lambda dt: ms_since_epoch(datetime.combine( make_naive(dt), datetime.min.time())), list(queryset.values_list('datetime', flat=True))))) codes = {low: date_counter( RequestLog.objects.filter(status_code__gte=low, status_code__lt=high)) for low, high in ((200, 300), (300, 400), (400, 500))} codes[500] = date_counter(RequestLog.objects.filter(status_code__gte=500)) codes['attacks'] = date_counter(RequestLog.objects.filter( status_code__in=(400, 444, 502))) stats = {} for code in (200, 300, 400, 500, 'attacks'): for date, count in codes[code].items(): if stats.get(date, None) is None: stats[date] = {200: 0, 300: 0, 400: 0, 500: 0, 'attacks': 0} stats[date][code] += count stats = sorted([(k, v) for k, v in stats.items()], key=lambda x: x[0]) return stats
Get stats for status codes by date. Returns: list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks.
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/stats.py#L38-L67
[ "def date_counter(queryset):\n return dict(Counter(map(\n lambda dt: ms_since_epoch(datetime.combine(\n make_naive(dt), datetime.min.time())),\n list(queryset.values_list('datetime', flat=True)))))\n" ]
# -*- coding: utf-8 -*- """ Statistics methods. This modules stores the functions to compute statistics used by charts. Typically, these data will be used in series for Highcharts charts. """ from collections import Counter from datetime import datetime from django.utils.timezone import make_naive from ..utils.time import ms_since_epoch from ..utils.url import ( ASSET, COMMON_ASSET, FALSE_NEGATIVE, IGNORED, OLD_ASSET, OLD_PROJECT, PROJECT, SUSPICIOUS, URL_TYPE, URL_TYPE_REVERSE, url_is_asset, url_is_common_asset, url_is_false_negative, url_is_ignored, url_is_old_project, url_is_project) from .models import RequestLog def status_codes_stats(): """ Get stats for status codes. Args: logs (list): logs data to use. Returns: dict: status code as key, number of apparition as value. """ return dict(Counter(list(RequestLog.objects.values_list( 'status_code', flat=True)))) # noqa def most_visited_pages_stats(): """ Get stats for most visited pages. Args: logs (list): logs data to use. Returns: dict: more_than_10 and less_than_10: list of dict (bound + url list). """ stats = {'more_than_10': [], 'less_than_10': {}} counter = Counter(list(RequestLog.objects.values_list('url', flat=True))) most_visited_pages = counter.most_common() bounds = (10000, 1000, 100, 10) subsets = [[] for _ in bounds] for u, c in most_visited_pages: if url_is_ignored(u): continue if c >= bounds[0]: subsets[0].append([u, c]) elif c < bounds[-1]: subsets[-1].append([u, c]) else: for i, bound in enumerate(bounds[:-1]): if bound > c >= bounds[i+1]: subsets[i+1].append([u, c]) break stats['more_than_10'] = [ {'bound': bound, 'subset': subset} for bound, subset in zip(bounds[:-1], subsets[:-1])] for subset in subsets[:-1]: for uc in subset: if url_is_project(uc[0]): if url_is_asset(uc[0]): uc.append(ASSET) else: uc.append(PROJECT) else: if url_is_asset(uc[0]): uc.append(OLD_ASSET) elif url_is_common_asset(uc[0]): uc.append(COMMON_ASSET) elif url_is_old_project(uc[0]): uc.append(OLD_PROJECT) elif url_is_false_negative(uc[0]): uc.append(FALSE_NEGATIVE) else: uc.append(SUSPICIOUS) occurrences = {name: {'distinct': 0, 'total': 0} for name in set(URL_TYPE.keys()) - {IGNORED}} for u, c in subsets[-1]: if url_is_project(u): if url_is_asset(u): occurrences[ASSET]['distinct'] += 1 occurrences[ASSET]['total'] += c else: occurrences[PROJECT]['distinct'] += 1 occurrences[PROJECT]['total'] += c else: if url_is_asset(u): occurrences[OLD_ASSET]['distinct'] += 1 occurrences[OLD_ASSET]['total'] += c elif url_is_common_asset(u): occurrences[COMMON_ASSET]['distinct'] += 1 occurrences[COMMON_ASSET]['total'] += c elif url_is_old_project(u): occurrences[OLD_PROJECT]['distinct'] += 1 occurrences[OLD_PROJECT]['total'] += c elif url_is_false_negative(u): occurrences[FALSE_NEGATIVE]['distinct'] += 1 occurrences[FALSE_NEGATIVE]['total'] += c else: occurrences[SUSPICIOUS]['distinct'] += 1 occurrences[SUSPICIOUS]['total'] += c stats['less_than_10'] = occurrences return stats
Genida/django-meerkat
src/meerkat/logs/stats.py
most_visited_pages_stats
python
def most_visited_pages_stats(): stats = {'more_than_10': [], 'less_than_10': {}} counter = Counter(list(RequestLog.objects.values_list('url', flat=True))) most_visited_pages = counter.most_common() bounds = (10000, 1000, 100, 10) subsets = [[] for _ in bounds] for u, c in most_visited_pages: if url_is_ignored(u): continue if c >= bounds[0]: subsets[0].append([u, c]) elif c < bounds[-1]: subsets[-1].append([u, c]) else: for i, bound in enumerate(bounds[:-1]): if bound > c >= bounds[i+1]: subsets[i+1].append([u, c]) break stats['more_than_10'] = [ {'bound': bound, 'subset': subset} for bound, subset in zip(bounds[:-1], subsets[:-1])] for subset in subsets[:-1]: for uc in subset: if url_is_project(uc[0]): if url_is_asset(uc[0]): uc.append(ASSET) else: uc.append(PROJECT) else: if url_is_asset(uc[0]): uc.append(OLD_ASSET) elif url_is_common_asset(uc[0]): uc.append(COMMON_ASSET) elif url_is_old_project(uc[0]): uc.append(OLD_PROJECT) elif url_is_false_negative(uc[0]): uc.append(FALSE_NEGATIVE) else: uc.append(SUSPICIOUS) occurrences = {name: {'distinct': 0, 'total': 0} for name in set(URL_TYPE.keys()) - {IGNORED}} for u, c in subsets[-1]: if url_is_project(u): if url_is_asset(u): occurrences[ASSET]['distinct'] += 1 occurrences[ASSET]['total'] += c else: occurrences[PROJECT]['distinct'] += 1 occurrences[PROJECT]['total'] += c else: if url_is_asset(u): occurrences[OLD_ASSET]['distinct'] += 1 occurrences[OLD_ASSET]['total'] += c elif url_is_common_asset(u): occurrences[COMMON_ASSET]['distinct'] += 1 occurrences[COMMON_ASSET]['total'] += c elif url_is_old_project(u): occurrences[OLD_PROJECT]['distinct'] += 1 occurrences[OLD_PROJECT]['total'] += c elif url_is_false_negative(u): occurrences[FALSE_NEGATIVE]['distinct'] += 1 occurrences[FALSE_NEGATIVE]['total'] += c else: occurrences[SUSPICIOUS]['distinct'] += 1 occurrences[SUSPICIOUS]['total'] += c stats['less_than_10'] = occurrences return stats
Get stats for most visited pages. Args: logs (list): logs data to use. Returns: dict: more_than_10 and less_than_10: list of dict (bound + url list).
train
https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/stats.py#L70-L153
[ "def url_is_project(url, default='not_a_func'):\n \"\"\"\n Check if URL is part of the current project's URLs.\n\n Args:\n url (str): URL to check.\n default (callable): used to filter out some URLs attached to function.\n\n Returns:\n\n \"\"\"\n try:\n u = resolve(url)\n ...
# -*- coding: utf-8 -*- """ Statistics methods. This modules stores the functions to compute statistics used by charts. Typically, these data will be used in series for Highcharts charts. """ from collections import Counter from datetime import datetime from django.utils.timezone import make_naive from ..utils.time import ms_since_epoch from ..utils.url import ( ASSET, COMMON_ASSET, FALSE_NEGATIVE, IGNORED, OLD_ASSET, OLD_PROJECT, PROJECT, SUSPICIOUS, URL_TYPE, URL_TYPE_REVERSE, url_is_asset, url_is_common_asset, url_is_false_negative, url_is_ignored, url_is_old_project, url_is_project) from .models import RequestLog def status_codes_stats(): """ Get stats for status codes. Args: logs (list): logs data to use. Returns: dict: status code as key, number of apparition as value. """ return dict(Counter(list(RequestLog.objects.values_list( 'status_code', flat=True)))) # noqa def status_codes_by_date_stats(): """ Get stats for status codes by date. Returns: list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks. """ def date_counter(queryset): return dict(Counter(map( lambda dt: ms_since_epoch(datetime.combine( make_naive(dt), datetime.min.time())), list(queryset.values_list('datetime', flat=True))))) codes = {low: date_counter( RequestLog.objects.filter(status_code__gte=low, status_code__lt=high)) for low, high in ((200, 300), (300, 400), (400, 500))} codes[500] = date_counter(RequestLog.objects.filter(status_code__gte=500)) codes['attacks'] = date_counter(RequestLog.objects.filter( status_code__in=(400, 444, 502))) stats = {} for code in (200, 300, 400, 500, 'attacks'): for date, count in codes[code].items(): if stats.get(date, None) is None: stats[date] = {200: 0, 300: 0, 400: 0, 500: 0, 'attacks': 0} stats[date][code] += count stats = sorted([(k, v) for k, v in stats.items()], key=lambda x: x[0]) return stats
ets-labs/python-domain-models
domain_models/fields.py
Field.bind_name
python
def bind_name(self, name): if self.name: raise errors.Error('Already bound "{0}" with name "{1}" could not ' 'be rebound'.format(self, self.name)) self.name = name self.storage_name = ''.join(('_', self.name)) return self
Bind field to its name in model class.
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L24-L31
null
class Field(property): """Base field.""" def __init__(self, default=None, required=False): """Initializer.""" super(Field, self).__init__(self.get_value, self.set_value) self.name = None self.storage_name = None self.model_cls = None self.default = default self.required = required def bind_model_cls(self, model_cls): """Bind field to model class.""" if self.model_cls: raise errors.Error('"{0}" has been already bound to "{1}" and ' 'could not be rebound to "{2}"'.format( self, self.model_cls, model_cls)) self.model_cls = model_cls return self def init_model(self, model, value): """Init model with field. :param DomainModel model: :param object value: """ if value is None and self.default is not None: value = self.default() if callable(self.default) else self.default self.set_value(model, value) def get_value(self, model, default=None): """Return field's value. :param DomainModel model: :param object default: :rtype object: """ if default is not None: default = self._converter(default) value = getattr(model, self.storage_name) return value if value is not None else default def set_value(self, model, value): """Set field's value. :param DomainModel model: :param object value: """ if value is None and self.required: raise AttributeError("This field is required.") if value is not None: value = self._converter(value) setattr(model, self.storage_name, value) def get_builtin_type(self, model): """Return built-in type representation of Field. :param DomainModel model: :rtype object: """ return self.get_value(model) def _converter(self, value): """Convert raw input value of the field. :param object value: :rtype object: """ return value @staticmethod def _get_model_instance(model_cls, data): """Convert dict into object of class of passed model. :param class model_cls: :param object data: :rtype DomainModel: """ if not isinstance(data, (model_cls, dict)): raise TypeError('{0} is not valid type, instance of ' '{1} or dict required'.format(data, model_cls)) return model_cls(**data) if isinstance(data, dict) else data
ets-labs/python-domain-models
domain_models/fields.py
Field.bind_model_cls
python
def bind_model_cls(self, model_cls): if self.model_cls: raise errors.Error('"{0}" has been already bound to "{1}" and ' 'could not be rebound to "{2}"'.format( self, self.model_cls, model_cls)) self.model_cls = model_cls return self
Bind field to model class.
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L33-L40
null
class Field(property): """Base field.""" def __init__(self, default=None, required=False): """Initializer.""" super(Field, self).__init__(self.get_value, self.set_value) self.name = None self.storage_name = None self.model_cls = None self.default = default self.required = required def bind_name(self, name): """Bind field to its name in model class.""" if self.name: raise errors.Error('Already bound "{0}" with name "{1}" could not ' 'be rebound'.format(self, self.name)) self.name = name self.storage_name = ''.join(('_', self.name)) return self def init_model(self, model, value): """Init model with field. :param DomainModel model: :param object value: """ if value is None and self.default is not None: value = self.default() if callable(self.default) else self.default self.set_value(model, value) def get_value(self, model, default=None): """Return field's value. :param DomainModel model: :param object default: :rtype object: """ if default is not None: default = self._converter(default) value = getattr(model, self.storage_name) return value if value is not None else default def set_value(self, model, value): """Set field's value. :param DomainModel model: :param object value: """ if value is None and self.required: raise AttributeError("This field is required.") if value is not None: value = self._converter(value) setattr(model, self.storage_name, value) def get_builtin_type(self, model): """Return built-in type representation of Field. :param DomainModel model: :rtype object: """ return self.get_value(model) def _converter(self, value): """Convert raw input value of the field. :param object value: :rtype object: """ return value @staticmethod def _get_model_instance(model_cls, data): """Convert dict into object of class of passed model. :param class model_cls: :param object data: :rtype DomainModel: """ if not isinstance(data, (model_cls, dict)): raise TypeError('{0} is not valid type, instance of ' '{1} or dict required'.format(data, model_cls)) return model_cls(**data) if isinstance(data, dict) else data
ets-labs/python-domain-models
domain_models/fields.py
Field.init_model
python
def init_model(self, model, value): if value is None and self.default is not None: value = self.default() if callable(self.default) else self.default self.set_value(model, value)
Init model with field. :param DomainModel model: :param object value:
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L42-L51
[ "def set_value(self, model, value):\n \"\"\"Set field's value.\n\n :param DomainModel model:\n :param object value:\n \"\"\"\n if value is None and self.required:\n raise AttributeError(\"This field is required.\")\n\n if value is not None:\n value = self._converter(value)\n\n set...
class Field(property): """Base field.""" def __init__(self, default=None, required=False): """Initializer.""" super(Field, self).__init__(self.get_value, self.set_value) self.name = None self.storage_name = None self.model_cls = None self.default = default self.required = required def bind_name(self, name): """Bind field to its name in model class.""" if self.name: raise errors.Error('Already bound "{0}" with name "{1}" could not ' 'be rebound'.format(self, self.name)) self.name = name self.storage_name = ''.join(('_', self.name)) return self def bind_model_cls(self, model_cls): """Bind field to model class.""" if self.model_cls: raise errors.Error('"{0}" has been already bound to "{1}" and ' 'could not be rebound to "{2}"'.format( self, self.model_cls, model_cls)) self.model_cls = model_cls return self def get_value(self, model, default=None): """Return field's value. :param DomainModel model: :param object default: :rtype object: """ if default is not None: default = self._converter(default) value = getattr(model, self.storage_name) return value if value is not None else default def set_value(self, model, value): """Set field's value. :param DomainModel model: :param object value: """ if value is None and self.required: raise AttributeError("This field is required.") if value is not None: value = self._converter(value) setattr(model, self.storage_name, value) def get_builtin_type(self, model): """Return built-in type representation of Field. :param DomainModel model: :rtype object: """ return self.get_value(model) def _converter(self, value): """Convert raw input value of the field. :param object value: :rtype object: """ return value @staticmethod def _get_model_instance(model_cls, data): """Convert dict into object of class of passed model. :param class model_cls: :param object data: :rtype DomainModel: """ if not isinstance(data, (model_cls, dict)): raise TypeError('{0} is not valid type, instance of ' '{1} or dict required'.format(data, model_cls)) return model_cls(**data) if isinstance(data, dict) else data
ets-labs/python-domain-models
domain_models/fields.py
Field.get_value
python
def get_value(self, model, default=None): if default is not None: default = self._converter(default) value = getattr(model, self.storage_name) return value if value is not None else default
Return field's value. :param DomainModel model: :param object default: :rtype object:
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L53-L64
[ "def _converter(self, value):\n \"\"\"Convert raw input value of the field.\n\n :param object value:\n :rtype object:\n \"\"\"\n return value\n" ]
class Field(property): """Base field.""" def __init__(self, default=None, required=False): """Initializer.""" super(Field, self).__init__(self.get_value, self.set_value) self.name = None self.storage_name = None self.model_cls = None self.default = default self.required = required def bind_name(self, name): """Bind field to its name in model class.""" if self.name: raise errors.Error('Already bound "{0}" with name "{1}" could not ' 'be rebound'.format(self, self.name)) self.name = name self.storage_name = ''.join(('_', self.name)) return self def bind_model_cls(self, model_cls): """Bind field to model class.""" if self.model_cls: raise errors.Error('"{0}" has been already bound to "{1}" and ' 'could not be rebound to "{2}"'.format( self, self.model_cls, model_cls)) self.model_cls = model_cls return self def init_model(self, model, value): """Init model with field. :param DomainModel model: :param object value: """ if value is None and self.default is not None: value = self.default() if callable(self.default) else self.default self.set_value(model, value) def set_value(self, model, value): """Set field's value. :param DomainModel model: :param object value: """ if value is None and self.required: raise AttributeError("This field is required.") if value is not None: value = self._converter(value) setattr(model, self.storage_name, value) def get_builtin_type(self, model): """Return built-in type representation of Field. :param DomainModel model: :rtype object: """ return self.get_value(model) def _converter(self, value): """Convert raw input value of the field. :param object value: :rtype object: """ return value @staticmethod def _get_model_instance(model_cls, data): """Convert dict into object of class of passed model. :param class model_cls: :param object data: :rtype DomainModel: """ if not isinstance(data, (model_cls, dict)): raise TypeError('{0} is not valid type, instance of ' '{1} or dict required'.format(data, model_cls)) return model_cls(**data) if isinstance(data, dict) else data
ets-labs/python-domain-models
domain_models/fields.py
Field.set_value
python
def set_value(self, model, value): if value is None and self.required: raise AttributeError("This field is required.") if value is not None: value = self._converter(value) setattr(model, self.storage_name, value)
Set field's value. :param DomainModel model: :param object value:
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L66-L78
[ "def _converter(self, value):\n \"\"\"Convert raw input value of the field.\n\n :param object value:\n :rtype object:\n \"\"\"\n return value\n" ]
class Field(property): """Base field.""" def __init__(self, default=None, required=False): """Initializer.""" super(Field, self).__init__(self.get_value, self.set_value) self.name = None self.storage_name = None self.model_cls = None self.default = default self.required = required def bind_name(self, name): """Bind field to its name in model class.""" if self.name: raise errors.Error('Already bound "{0}" with name "{1}" could not ' 'be rebound'.format(self, self.name)) self.name = name self.storage_name = ''.join(('_', self.name)) return self def bind_model_cls(self, model_cls): """Bind field to model class.""" if self.model_cls: raise errors.Error('"{0}" has been already bound to "{1}" and ' 'could not be rebound to "{2}"'.format( self, self.model_cls, model_cls)) self.model_cls = model_cls return self def init_model(self, model, value): """Init model with field. :param DomainModel model: :param object value: """ if value is None and self.default is not None: value = self.default() if callable(self.default) else self.default self.set_value(model, value) def get_value(self, model, default=None): """Return field's value. :param DomainModel model: :param object default: :rtype object: """ if default is not None: default = self._converter(default) value = getattr(model, self.storage_name) return value if value is not None else default def get_builtin_type(self, model): """Return built-in type representation of Field. :param DomainModel model: :rtype object: """ return self.get_value(model) def _converter(self, value): """Convert raw input value of the field. :param object value: :rtype object: """ return value @staticmethod def _get_model_instance(model_cls, data): """Convert dict into object of class of passed model. :param class model_cls: :param object data: :rtype DomainModel: """ if not isinstance(data, (model_cls, dict)): raise TypeError('{0} is not valid type, instance of ' '{1} or dict required'.format(data, model_cls)) return model_cls(**data) if isinstance(data, dict) else data
ets-labs/python-domain-models
domain_models/fields.py
Field._get_model_instance
python
def _get_model_instance(model_cls, data): if not isinstance(data, (model_cls, dict)): raise TypeError('{0} is not valid type, instance of ' '{1} or dict required'.format(data, model_cls)) return model_cls(**data) if isinstance(data, dict) else data
Convert dict into object of class of passed model. :param class model_cls: :param object data: :rtype DomainModel:
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L97-L107
null
class Field(property): """Base field.""" def __init__(self, default=None, required=False): """Initializer.""" super(Field, self).__init__(self.get_value, self.set_value) self.name = None self.storage_name = None self.model_cls = None self.default = default self.required = required def bind_name(self, name): """Bind field to its name in model class.""" if self.name: raise errors.Error('Already bound "{0}" with name "{1}" could not ' 'be rebound'.format(self, self.name)) self.name = name self.storage_name = ''.join(('_', self.name)) return self def bind_model_cls(self, model_cls): """Bind field to model class.""" if self.model_cls: raise errors.Error('"{0}" has been already bound to "{1}" and ' 'could not be rebound to "{2}"'.format( self, self.model_cls, model_cls)) self.model_cls = model_cls return self def init_model(self, model, value): """Init model with field. :param DomainModel model: :param object value: """ if value is None and self.default is not None: value = self.default() if callable(self.default) else self.default self.set_value(model, value) def get_value(self, model, default=None): """Return field's value. :param DomainModel model: :param object default: :rtype object: """ if default is not None: default = self._converter(default) value = getattr(model, self.storage_name) return value if value is not None else default def set_value(self, model, value): """Set field's value. :param DomainModel model: :param object value: """ if value is None and self.required: raise AttributeError("This field is required.") if value is not None: value = self._converter(value) setattr(model, self.storage_name, value) def get_builtin_type(self, model): """Return built-in type representation of Field. :param DomainModel model: :rtype object: """ return self.get_value(model) def _converter(self, value): """Convert raw input value of the field. :param object value: :rtype object: """ return value @staticmethod
ets-labs/python-domain-models
domain_models/fields.py
Date._converter
python
def _converter(self, value): if not isinstance(value, datetime.date): raise TypeError('{0} is not valid date'.format(value)) return value
Convert raw input value of the field.
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L153-L157
null
class Date(Field): """Date field."""
ets-labs/python-domain-models
domain_models/fields.py
Collection._converter
python
def _converter(self, value): if type(value) is not self.related_model_cls.Collection: value = self.related_model_cls.Collection([ self._get_model_instance(self.related_model_cls, item) for item in value]) return value
Convert raw input value of the field. :param object value: :rtype object:
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L203-L213
null
class Collection(Field): """Models collection relation field.""" def __init__(self, related_model_cls, default=None, required=False): """Initializer.""" super(Collection, self).__init__(default=default, required=required) self.related_model_cls = related_model_cls def get_builtin_type(self, model): """Return built-in type representation of Collection. :param DomainModel model: :rtype list: """ return [item.get_data() if isinstance(item, self.related_model_cls) else item for item in self.get_value(model)]
ets-labs/python-domain-models
domain_models/fields.py
Collection.get_builtin_type
python
def get_builtin_type(self, model): return [item.get_data() if isinstance(item, self.related_model_cls) else item for item in self.get_value(model)]
Return built-in type representation of Collection. :param DomainModel model: :rtype list:
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L215-L222
[ "def get_value(self, model, default=None):\n \"\"\"Return field's value.\n\n :param DomainModel model:\n :param object default:\n :rtype object:\n \"\"\"\n if default is not None:\n default = self._converter(default)\n\n value = getattr(model, self.storage_name)\n return value if valu...
class Collection(Field): """Models collection relation field.""" def __init__(self, related_model_cls, default=None, required=False): """Initializer.""" super(Collection, self).__init__(default=default, required=required) self.related_model_cls = related_model_cls def _converter(self, value): """Convert raw input value of the field. :param object value: :rtype object: """ if type(value) is not self.related_model_cls.Collection: value = self.related_model_cls.Collection([ self._get_model_instance(self.related_model_cls, item) for item in value]) return value
ets-labs/python-domain-models
domain_models/views.py
ContextViewMetaClass.validate
python
def validate(mcs, bases, attributes): if bases[0] is object: return None mcs.check_model_cls(attributes) mcs.check_include_exclude(attributes) mcs.check_properties(attributes)
Check attributes.
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/views.py#L18-L24
[ "def check_model_cls(attributes):\n \"\"\"Check __model_cls__ attribute.\n\n :type attributes: dict\n \"\"\"\n model_cls = attributes.get('__model_cls__')\n if model_cls is None:\n raise AttributeError(\"Attribute __model_cls__ is required.\")\n\n if not issubclass(model_cls, models.DomainM...
class ContextViewMetaClass(type): """Context view meta class.""" def __new__(mcs, class_name, bases, attributes): """Context view class factory.""" mcs.validate(bases, attributes) cls = type.__new__(mcs, class_name, bases, attributes) cls.__fields__ = mcs.get_properties(attributes) return cls @classmethod @staticmethod def check_model_cls(attributes): """Check __model_cls__ attribute. :type attributes: dict """ model_cls = attributes.get('__model_cls__') if model_cls is None: raise AttributeError("Attribute __model_cls__ is required.") if not issubclass(model_cls, models.DomainModel): raise TypeError("Attribute __model_cls__ must be subclass of " "DomainModel.") @staticmethod def get_prepared_include_exclude(attributes): """Return tuple with prepared __include__ and __exclude__ attributes. :type attributes: dict :rtype: tuple """ attrs = dict() for attr in ('__include__', '__exclude__'): attrs[attr] = tuple([item.name for item in attributes.get(attr, tuple())]) return attrs['__include__'], attrs['__exclude__'] @staticmethod def check_include_exclude(attributes): """Check __include__ and __exclude__ attributes. :type attributes: dict """ include = attributes.get('__include__', tuple()) exclude = attributes.get('__exclude__', tuple()) if not isinstance(include, tuple): raise TypeError("Attribute __include__ must be a tuple.") if not isinstance(exclude, tuple): raise TypeError("Attribute __exclude__ must be a tuple.") if all((not include, not exclude)): return None if all((include, exclude)): raise AttributeError("Usage of __include__ and __exclude__ " "at the same time is prohibited.") @staticmethod def get_properties(attributes): """Return tuple of names of defined properties. :type attributes: dict :rtype: list """ return [key for key, value in six.iteritems(attributes) if isinstance(value, property)] @classmethod def check_properties(mcs, attributes): """Check whether intersections exist. :type attributes: dict """ include, exclude = mcs.get_prepared_include_exclude(attributes) properties = mcs.get_properties(attributes) intersections = list( set(properties).intersection(include if include else exclude)) if not intersections: return None attr_name = '__include__' if include else '__exclude__' raise AttributeError( "It is not allowed to mention already defined properties: " "{0} in {1} attributes.".format(", ".join(intersections), attr_name))
ets-labs/python-domain-models
domain_models/views.py
ContextViewMetaClass.check_model_cls
python
def check_model_cls(attributes): model_cls = attributes.get('__model_cls__') if model_cls is None: raise AttributeError("Attribute __model_cls__ is required.") if not issubclass(model_cls, models.DomainModel): raise TypeError("Attribute __model_cls__ must be subclass of " "DomainModel.")
Check __model_cls__ attribute. :type attributes: dict
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/views.py#L27-L38
null
class ContextViewMetaClass(type): """Context view meta class.""" def __new__(mcs, class_name, bases, attributes): """Context view class factory.""" mcs.validate(bases, attributes) cls = type.__new__(mcs, class_name, bases, attributes) cls.__fields__ = mcs.get_properties(attributes) return cls @classmethod def validate(mcs, bases, attributes): """Check attributes.""" if bases[0] is object: return None mcs.check_model_cls(attributes) mcs.check_include_exclude(attributes) mcs.check_properties(attributes) @staticmethod @staticmethod def get_prepared_include_exclude(attributes): """Return tuple with prepared __include__ and __exclude__ attributes. :type attributes: dict :rtype: tuple """ attrs = dict() for attr in ('__include__', '__exclude__'): attrs[attr] = tuple([item.name for item in attributes.get(attr, tuple())]) return attrs['__include__'], attrs['__exclude__'] @staticmethod def check_include_exclude(attributes): """Check __include__ and __exclude__ attributes. :type attributes: dict """ include = attributes.get('__include__', tuple()) exclude = attributes.get('__exclude__', tuple()) if not isinstance(include, tuple): raise TypeError("Attribute __include__ must be a tuple.") if not isinstance(exclude, tuple): raise TypeError("Attribute __exclude__ must be a tuple.") if all((not include, not exclude)): return None if all((include, exclude)): raise AttributeError("Usage of __include__ and __exclude__ " "at the same time is prohibited.") @staticmethod def get_properties(attributes): """Return tuple of names of defined properties. :type attributes: dict :rtype: list """ return [key for key, value in six.iteritems(attributes) if isinstance(value, property)] @classmethod def check_properties(mcs, attributes): """Check whether intersections exist. :type attributes: dict """ include, exclude = mcs.get_prepared_include_exclude(attributes) properties = mcs.get_properties(attributes) intersections = list( set(properties).intersection(include if include else exclude)) if not intersections: return None attr_name = '__include__' if include else '__exclude__' raise AttributeError( "It is not allowed to mention already defined properties: " "{0} in {1} attributes.".format(", ".join(intersections), attr_name))
ets-labs/python-domain-models
domain_models/views.py
ContextViewMetaClass.get_prepared_include_exclude
python
def get_prepared_include_exclude(attributes): attrs = dict() for attr in ('__include__', '__exclude__'): attrs[attr] = tuple([item.name for item in attributes.get(attr, tuple())]) return attrs['__include__'], attrs['__exclude__']
Return tuple with prepared __include__ and __exclude__ attributes. :type attributes: dict :rtype: tuple
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/views.py#L41-L51
null
class ContextViewMetaClass(type): """Context view meta class.""" def __new__(mcs, class_name, bases, attributes): """Context view class factory.""" mcs.validate(bases, attributes) cls = type.__new__(mcs, class_name, bases, attributes) cls.__fields__ = mcs.get_properties(attributes) return cls @classmethod def validate(mcs, bases, attributes): """Check attributes.""" if bases[0] is object: return None mcs.check_model_cls(attributes) mcs.check_include_exclude(attributes) mcs.check_properties(attributes) @staticmethod def check_model_cls(attributes): """Check __model_cls__ attribute. :type attributes: dict """ model_cls = attributes.get('__model_cls__') if model_cls is None: raise AttributeError("Attribute __model_cls__ is required.") if not issubclass(model_cls, models.DomainModel): raise TypeError("Attribute __model_cls__ must be subclass of " "DomainModel.") @staticmethod @staticmethod def check_include_exclude(attributes): """Check __include__ and __exclude__ attributes. :type attributes: dict """ include = attributes.get('__include__', tuple()) exclude = attributes.get('__exclude__', tuple()) if not isinstance(include, tuple): raise TypeError("Attribute __include__ must be a tuple.") if not isinstance(exclude, tuple): raise TypeError("Attribute __exclude__ must be a tuple.") if all((not include, not exclude)): return None if all((include, exclude)): raise AttributeError("Usage of __include__ and __exclude__ " "at the same time is prohibited.") @staticmethod def get_properties(attributes): """Return tuple of names of defined properties. :type attributes: dict :rtype: list """ return [key for key, value in six.iteritems(attributes) if isinstance(value, property)] @classmethod def check_properties(mcs, attributes): """Check whether intersections exist. :type attributes: dict """ include, exclude = mcs.get_prepared_include_exclude(attributes) properties = mcs.get_properties(attributes) intersections = list( set(properties).intersection(include if include else exclude)) if not intersections: return None attr_name = '__include__' if include else '__exclude__' raise AttributeError( "It is not allowed to mention already defined properties: " "{0} in {1} attributes.".format(", ".join(intersections), attr_name))
ets-labs/python-domain-models
domain_models/views.py
ContextViewMetaClass.check_include_exclude
python
def check_include_exclude(attributes): include = attributes.get('__include__', tuple()) exclude = attributes.get('__exclude__', tuple()) if not isinstance(include, tuple): raise TypeError("Attribute __include__ must be a tuple.") if not isinstance(exclude, tuple): raise TypeError("Attribute __exclude__ must be a tuple.") if all((not include, not exclude)): return None if all((include, exclude)): raise AttributeError("Usage of __include__ and __exclude__ " "at the same time is prohibited.")
Check __include__ and __exclude__ attributes. :type attributes: dict
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/views.py#L54-L73
null
class ContextViewMetaClass(type): """Context view meta class.""" def __new__(mcs, class_name, bases, attributes): """Context view class factory.""" mcs.validate(bases, attributes) cls = type.__new__(mcs, class_name, bases, attributes) cls.__fields__ = mcs.get_properties(attributes) return cls @classmethod def validate(mcs, bases, attributes): """Check attributes.""" if bases[0] is object: return None mcs.check_model_cls(attributes) mcs.check_include_exclude(attributes) mcs.check_properties(attributes) @staticmethod def check_model_cls(attributes): """Check __model_cls__ attribute. :type attributes: dict """ model_cls = attributes.get('__model_cls__') if model_cls is None: raise AttributeError("Attribute __model_cls__ is required.") if not issubclass(model_cls, models.DomainModel): raise TypeError("Attribute __model_cls__ must be subclass of " "DomainModel.") @staticmethod def get_prepared_include_exclude(attributes): """Return tuple with prepared __include__ and __exclude__ attributes. :type attributes: dict :rtype: tuple """ attrs = dict() for attr in ('__include__', '__exclude__'): attrs[attr] = tuple([item.name for item in attributes.get(attr, tuple())]) return attrs['__include__'], attrs['__exclude__'] @staticmethod @staticmethod def get_properties(attributes): """Return tuple of names of defined properties. :type attributes: dict :rtype: list """ return [key for key, value in six.iteritems(attributes) if isinstance(value, property)] @classmethod def check_properties(mcs, attributes): """Check whether intersections exist. :type attributes: dict """ include, exclude = mcs.get_prepared_include_exclude(attributes) properties = mcs.get_properties(attributes) intersections = list( set(properties).intersection(include if include else exclude)) if not intersections: return None attr_name = '__include__' if include else '__exclude__' raise AttributeError( "It is not allowed to mention already defined properties: " "{0} in {1} attributes.".format(", ".join(intersections), attr_name))
ets-labs/python-domain-models
domain_models/views.py
ContextViewMetaClass.get_properties
python
def get_properties(attributes): return [key for key, value in six.iteritems(attributes) if isinstance(value, property)]
Return tuple of names of defined properties. :type attributes: dict :rtype: list
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/views.py#L76-L83
null
class ContextViewMetaClass(type): """Context view meta class.""" def __new__(mcs, class_name, bases, attributes): """Context view class factory.""" mcs.validate(bases, attributes) cls = type.__new__(mcs, class_name, bases, attributes) cls.__fields__ = mcs.get_properties(attributes) return cls @classmethod def validate(mcs, bases, attributes): """Check attributes.""" if bases[0] is object: return None mcs.check_model_cls(attributes) mcs.check_include_exclude(attributes) mcs.check_properties(attributes) @staticmethod def check_model_cls(attributes): """Check __model_cls__ attribute. :type attributes: dict """ model_cls = attributes.get('__model_cls__') if model_cls is None: raise AttributeError("Attribute __model_cls__ is required.") if not issubclass(model_cls, models.DomainModel): raise TypeError("Attribute __model_cls__ must be subclass of " "DomainModel.") @staticmethod def get_prepared_include_exclude(attributes): """Return tuple with prepared __include__ and __exclude__ attributes. :type attributes: dict :rtype: tuple """ attrs = dict() for attr in ('__include__', '__exclude__'): attrs[attr] = tuple([item.name for item in attributes.get(attr, tuple())]) return attrs['__include__'], attrs['__exclude__'] @staticmethod def check_include_exclude(attributes): """Check __include__ and __exclude__ attributes. :type attributes: dict """ include = attributes.get('__include__', tuple()) exclude = attributes.get('__exclude__', tuple()) if not isinstance(include, tuple): raise TypeError("Attribute __include__ must be a tuple.") if not isinstance(exclude, tuple): raise TypeError("Attribute __exclude__ must be a tuple.") if all((not include, not exclude)): return None if all((include, exclude)): raise AttributeError("Usage of __include__ and __exclude__ " "at the same time is prohibited.") @staticmethod @classmethod def check_properties(mcs, attributes): """Check whether intersections exist. :type attributes: dict """ include, exclude = mcs.get_prepared_include_exclude(attributes) properties = mcs.get_properties(attributes) intersections = list( set(properties).intersection(include if include else exclude)) if not intersections: return None attr_name = '__include__' if include else '__exclude__' raise AttributeError( "It is not allowed to mention already defined properties: " "{0} in {1} attributes.".format(", ".join(intersections), attr_name))
ets-labs/python-domain-models
domain_models/views.py
ContextViewMetaClass.check_properties
python
def check_properties(mcs, attributes): include, exclude = mcs.get_prepared_include_exclude(attributes) properties = mcs.get_properties(attributes) intersections = list( set(properties).intersection(include if include else exclude)) if not intersections: return None attr_name = '__include__' if include else '__exclude__' raise AttributeError( "It is not allowed to mention already defined properties: " "{0} in {1} attributes.".format(", ".join(intersections), attr_name))
Check whether intersections exist. :type attributes: dict
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/views.py#L86-L103
null
class ContextViewMetaClass(type): """Context view meta class.""" def __new__(mcs, class_name, bases, attributes): """Context view class factory.""" mcs.validate(bases, attributes) cls = type.__new__(mcs, class_name, bases, attributes) cls.__fields__ = mcs.get_properties(attributes) return cls @classmethod def validate(mcs, bases, attributes): """Check attributes.""" if bases[0] is object: return None mcs.check_model_cls(attributes) mcs.check_include_exclude(attributes) mcs.check_properties(attributes) @staticmethod def check_model_cls(attributes): """Check __model_cls__ attribute. :type attributes: dict """ model_cls = attributes.get('__model_cls__') if model_cls is None: raise AttributeError("Attribute __model_cls__ is required.") if not issubclass(model_cls, models.DomainModel): raise TypeError("Attribute __model_cls__ must be subclass of " "DomainModel.") @staticmethod def get_prepared_include_exclude(attributes): """Return tuple with prepared __include__ and __exclude__ attributes. :type attributes: dict :rtype: tuple """ attrs = dict() for attr in ('__include__', '__exclude__'): attrs[attr] = tuple([item.name for item in attributes.get(attr, tuple())]) return attrs['__include__'], attrs['__exclude__'] @staticmethod def check_include_exclude(attributes): """Check __include__ and __exclude__ attributes. :type attributes: dict """ include = attributes.get('__include__', tuple()) exclude = attributes.get('__exclude__', tuple()) if not isinstance(include, tuple): raise TypeError("Attribute __include__ must be a tuple.") if not isinstance(exclude, tuple): raise TypeError("Attribute __exclude__ must be a tuple.") if all((not include, not exclude)): return None if all((include, exclude)): raise AttributeError("Usage of __include__ and __exclude__ " "at the same time is prohibited.") @staticmethod def get_properties(attributes): """Return tuple of names of defined properties. :type attributes: dict :rtype: list """ return [key for key, value in six.iteritems(attributes) if isinstance(value, property)] @classmethod
ets-labs/python-domain-models
setup.py
PublishCommand.run
python
def run(self): self.run_command('sdist') self.run_command('upload') os.system('git tag -a {0} -m \'version {0}\''.format(version)) os.system('git push --tags')
Command execution.
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/setup.py#L35-L40
null
class PublishCommand(Command): """Setuptools `publish` command.""" description = "Publish current distribution to PyPi and create tag" user_options = [] def initialize_options(self): """Init options.""" def finalize_options(self): """Finalize options."""
ets-labs/python-domain-models
domain_models/models.py
DomainModelMetaClass.parse_fields
python
def parse_fields(attributes): return tuple(field.bind_name(name) for name, field in six.iteritems(attributes) if isinstance(field, fields.Field))
Parse model fields.
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/models.py#L38-L42
null
class DomainModelMetaClass(type): """Domain model meta class.""" def __new__(mcs, class_name, bases, attributes): """Domain model class factory.""" model_fields = mcs.parse_fields(attributes) if attributes.get('__slots_optimization__', True): attributes['__slots__'] = mcs.prepare_model_slots(model_fields) cls = type.__new__(mcs, class_name, bases, attributes) cls.__fields__ = mcs.bind_fields_to_model_cls(cls, model_fields) cls.__unique_key__ = mcs.prepare_fields_attribute( attribute_name='__unique_key__', attributes=attributes, class_name=class_name) cls.__view_key__ = mcs.prepare_fields_attribute( attribute_name='__view_key__', attributes=attributes, class_name=class_name) mcs.bind_collection_to_model_cls(cls) return cls @staticmethod @staticmethod def prepare_model_slots(model_fields): """Return tuple of model field slots.""" return tuple(field.storage_name for field in model_fields) @staticmethod def prepare_fields_attribute(attribute_name, attributes, class_name): """Prepare model fields attribute.""" attribute = attributes.get(attribute_name) if not attribute: attribute = tuple() elif isinstance(attribute, std_collections.Iterable): attribute = tuple(attribute) else: raise errors.Error('{0}.{1} is supposed to be a list of {2}, ' 'instead {3} given', class_name, attribute_name, fields.Field, attribute) return attribute @staticmethod def bind_fields_to_model_cls(cls, model_fields): """Bind fields to model class.""" return dict( (field.name, field.bind_model_cls(cls)) for field in model_fields) @staticmethod def bind_collection_to_model_cls(cls): """Bind collection to model's class. If collection was not specialized in process of model's declaration, subclass of collection will be created. """ cls.Collection = type('{0}.Collection'.format(cls.__name__), (cls.Collection,), {'value_type': cls}) cls.Collection.__module__ = cls.__module__
ets-labs/python-domain-models
domain_models/models.py
DomainModelMetaClass.prepare_fields_attribute
python
def prepare_fields_attribute(attribute_name, attributes, class_name): attribute = attributes.get(attribute_name) if not attribute: attribute = tuple() elif isinstance(attribute, std_collections.Iterable): attribute = tuple(attribute) else: raise errors.Error('{0}.{1} is supposed to be a list of {2}, ' 'instead {3} given', class_name, attribute_name, fields.Field, attribute) return attribute
Prepare model fields attribute.
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/models.py#L50-L61
null
class DomainModelMetaClass(type): """Domain model meta class.""" def __new__(mcs, class_name, bases, attributes): """Domain model class factory.""" model_fields = mcs.parse_fields(attributes) if attributes.get('__slots_optimization__', True): attributes['__slots__'] = mcs.prepare_model_slots(model_fields) cls = type.__new__(mcs, class_name, bases, attributes) cls.__fields__ = mcs.bind_fields_to_model_cls(cls, model_fields) cls.__unique_key__ = mcs.prepare_fields_attribute( attribute_name='__unique_key__', attributes=attributes, class_name=class_name) cls.__view_key__ = mcs.prepare_fields_attribute( attribute_name='__view_key__', attributes=attributes, class_name=class_name) mcs.bind_collection_to_model_cls(cls) return cls @staticmethod def parse_fields(attributes): """Parse model fields.""" return tuple(field.bind_name(name) for name, field in six.iteritems(attributes) if isinstance(field, fields.Field)) @staticmethod def prepare_model_slots(model_fields): """Return tuple of model field slots.""" return tuple(field.storage_name for field in model_fields) @staticmethod @staticmethod def bind_fields_to_model_cls(cls, model_fields): """Bind fields to model class.""" return dict( (field.name, field.bind_model_cls(cls)) for field in model_fields) @staticmethod def bind_collection_to_model_cls(cls): """Bind collection to model's class. If collection was not specialized in process of model's declaration, subclass of collection will be created. """ cls.Collection = type('{0}.Collection'.format(cls.__name__), (cls.Collection,), {'value_type': cls}) cls.Collection.__module__ = cls.__module__
ets-labs/python-domain-models
domain_models/models.py
DomainModelMetaClass.bind_fields_to_model_cls
python
def bind_fields_to_model_cls(cls, model_fields): return dict( (field.name, field.bind_model_cls(cls)) for field in model_fields)
Bind fields to model class.
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/models.py#L64-L67
null
class DomainModelMetaClass(type): """Domain model meta class.""" def __new__(mcs, class_name, bases, attributes): """Domain model class factory.""" model_fields = mcs.parse_fields(attributes) if attributes.get('__slots_optimization__', True): attributes['__slots__'] = mcs.prepare_model_slots(model_fields) cls = type.__new__(mcs, class_name, bases, attributes) cls.__fields__ = mcs.bind_fields_to_model_cls(cls, model_fields) cls.__unique_key__ = mcs.prepare_fields_attribute( attribute_name='__unique_key__', attributes=attributes, class_name=class_name) cls.__view_key__ = mcs.prepare_fields_attribute( attribute_name='__view_key__', attributes=attributes, class_name=class_name) mcs.bind_collection_to_model_cls(cls) return cls @staticmethod def parse_fields(attributes): """Parse model fields.""" return tuple(field.bind_name(name) for name, field in six.iteritems(attributes) if isinstance(field, fields.Field)) @staticmethod def prepare_model_slots(model_fields): """Return tuple of model field slots.""" return tuple(field.storage_name for field in model_fields) @staticmethod def prepare_fields_attribute(attribute_name, attributes, class_name): """Prepare model fields attribute.""" attribute = attributes.get(attribute_name) if not attribute: attribute = tuple() elif isinstance(attribute, std_collections.Iterable): attribute = tuple(attribute) else: raise errors.Error('{0}.{1} is supposed to be a list of {2}, ' 'instead {3} given', class_name, attribute_name, fields.Field, attribute) return attribute @staticmethod @staticmethod def bind_collection_to_model_cls(cls): """Bind collection to model's class. If collection was not specialized in process of model's declaration, subclass of collection will be created. """ cls.Collection = type('{0}.Collection'.format(cls.__name__), (cls.Collection,), {'value_type': cls}) cls.Collection.__module__ = cls.__module__
ets-labs/python-domain-models
domain_models/models.py
DomainModelMetaClass.bind_collection_to_model_cls
python
def bind_collection_to_model_cls(cls): cls.Collection = type('{0}.Collection'.format(cls.__name__), (cls.Collection,), {'value_type': cls}) cls.Collection.__module__ = cls.__module__
Bind collection to model's class. If collection was not specialized in process of model's declaration, subclass of collection will be created.
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/models.py#L70-L79
null
class DomainModelMetaClass(type): """Domain model meta class.""" def __new__(mcs, class_name, bases, attributes): """Domain model class factory.""" model_fields = mcs.parse_fields(attributes) if attributes.get('__slots_optimization__', True): attributes['__slots__'] = mcs.prepare_model_slots(model_fields) cls = type.__new__(mcs, class_name, bases, attributes) cls.__fields__ = mcs.bind_fields_to_model_cls(cls, model_fields) cls.__unique_key__ = mcs.prepare_fields_attribute( attribute_name='__unique_key__', attributes=attributes, class_name=class_name) cls.__view_key__ = mcs.prepare_fields_attribute( attribute_name='__view_key__', attributes=attributes, class_name=class_name) mcs.bind_collection_to_model_cls(cls) return cls @staticmethod def parse_fields(attributes): """Parse model fields.""" return tuple(field.bind_name(name) for name, field in six.iteritems(attributes) if isinstance(field, fields.Field)) @staticmethod def prepare_model_slots(model_fields): """Return tuple of model field slots.""" return tuple(field.storage_name for field in model_fields) @staticmethod def prepare_fields_attribute(attribute_name, attributes, class_name): """Prepare model fields attribute.""" attribute = attributes.get(attribute_name) if not attribute: attribute = tuple() elif isinstance(attribute, std_collections.Iterable): attribute = tuple(attribute) else: raise errors.Error('{0}.{1} is supposed to be a list of {2}, ' 'instead {3} given', class_name, attribute_name, fields.Field, attribute) return attribute @staticmethod def bind_fields_to_model_cls(cls, model_fields): """Bind fields to model class.""" return dict( (field.name, field.bind_model_cls(cls)) for field in model_fields) @staticmethod
ets-labs/python-domain-models
domain_models/collections.py
Collection.append
python
def append(self, value): return super(Collection, self).append( self._ensure_value_is_valid(value))
Add an item to the end of the list.
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/collections.py#L22-L25
[ "def _ensure_value_is_valid(self, value):\n \"\"\"Ensure that value is a valid collection's value.\"\"\"\n if not isinstance(value, self.__class__.value_type):\n raise TypeError('{0} is not valid collection value, instance '\n 'of {1} required'.format(\n ...
class Collection(list): """Collection.""" value_type = object """Type of values that collection could contain.""" def __init__(self, iterable=None, type_check=True): """Initializer.""" if not iterable: iterable = tuple() if type_check: iterable = self._ensure_iterable_is_valid(iterable) super(Collection, self).__init__(iterable) def extend(self, iterable): """Extend the list by appending all the items in the given list.""" return super(Collection, self).extend( self._ensure_iterable_is_valid(iterable)) def insert(self, index, value): """Insert an item at a given position.""" return super(Collection, self).insert( index, self._ensure_value_is_valid(value)) def __setitem__(self, index, value): """Set an item at a given position.""" if isinstance(index, slice): return super(Collection, self).__setitem__(index, self.__class__(value)) else: return super(Collection, self).__setitem__( index, self._ensure_value_is_valid(value)) def __getitem__(self, index): """Return value by index or slice of values if index is slice.""" value = super(Collection, self).__getitem__(index) if isinstance(index, slice): return self.__class__(value, type_check=False) return value if six.PY2: # pragma: nocover def __getslice__(self, start, stop): """Return slice of values.""" return self.__class__(super(Collection, self).__getslice__(start, stop), type_check=False) def __setslice__(self, start, stop, iterable): """Set slice of values.""" super(Collection, self).__setslice__(start, stop, self.__class__(iterable)) def _ensure_iterable_is_valid(self, iterable): """Ensure that iterable values are a valid collection's values.""" for value in iterable: self._ensure_value_is_valid(value) return iterable def _ensure_value_is_valid(self, value): """Ensure that value is a valid collection's value.""" if not isinstance(value, self.__class__.value_type): raise TypeError('{0} is not valid collection value, instance ' 'of {1} required'.format( value, self.__class__.value_type)) return value
ets-labs/python-domain-models
domain_models/collections.py
Collection.extend
python
def extend(self, iterable): return super(Collection, self).extend( self._ensure_iterable_is_valid(iterable))
Extend the list by appending all the items in the given list.
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/collections.py#L27-L30
[ "def _ensure_iterable_is_valid(self, iterable):\n \"\"\"Ensure that iterable values are a valid collection's values.\"\"\"\n for value in iterable:\n self._ensure_value_is_valid(value)\n return iterable\n" ]
class Collection(list): """Collection.""" value_type = object """Type of values that collection could contain.""" def __init__(self, iterable=None, type_check=True): """Initializer.""" if not iterable: iterable = tuple() if type_check: iterable = self._ensure_iterable_is_valid(iterable) super(Collection, self).__init__(iterable) def append(self, value): """Add an item to the end of the list.""" return super(Collection, self).append( self._ensure_value_is_valid(value)) def insert(self, index, value): """Insert an item at a given position.""" return super(Collection, self).insert( index, self._ensure_value_is_valid(value)) def __setitem__(self, index, value): """Set an item at a given position.""" if isinstance(index, slice): return super(Collection, self).__setitem__(index, self.__class__(value)) else: return super(Collection, self).__setitem__( index, self._ensure_value_is_valid(value)) def __getitem__(self, index): """Return value by index or slice of values if index is slice.""" value = super(Collection, self).__getitem__(index) if isinstance(index, slice): return self.__class__(value, type_check=False) return value if six.PY2: # pragma: nocover def __getslice__(self, start, stop): """Return slice of values.""" return self.__class__(super(Collection, self).__getslice__(start, stop), type_check=False) def __setslice__(self, start, stop, iterable): """Set slice of values.""" super(Collection, self).__setslice__(start, stop, self.__class__(iterable)) def _ensure_iterable_is_valid(self, iterable): """Ensure that iterable values are a valid collection's values.""" for value in iterable: self._ensure_value_is_valid(value) return iterable def _ensure_value_is_valid(self, value): """Ensure that value is a valid collection's value.""" if not isinstance(value, self.__class__.value_type): raise TypeError('{0} is not valid collection value, instance ' 'of {1} required'.format( value, self.__class__.value_type)) return value
ets-labs/python-domain-models
domain_models/collections.py
Collection.insert
python
def insert(self, index, value): return super(Collection, self).insert( index, self._ensure_value_is_valid(value))
Insert an item at a given position.
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/collections.py#L32-L35
[ "def _ensure_value_is_valid(self, value):\n \"\"\"Ensure that value is a valid collection's value.\"\"\"\n if not isinstance(value, self.__class__.value_type):\n raise TypeError('{0} is not valid collection value, instance '\n 'of {1} required'.format(\n ...
class Collection(list): """Collection.""" value_type = object """Type of values that collection could contain.""" def __init__(self, iterable=None, type_check=True): """Initializer.""" if not iterable: iterable = tuple() if type_check: iterable = self._ensure_iterable_is_valid(iterable) super(Collection, self).__init__(iterable) def append(self, value): """Add an item to the end of the list.""" return super(Collection, self).append( self._ensure_value_is_valid(value)) def extend(self, iterable): """Extend the list by appending all the items in the given list.""" return super(Collection, self).extend( self._ensure_iterable_is_valid(iterable)) def __setitem__(self, index, value): """Set an item at a given position.""" if isinstance(index, slice): return super(Collection, self).__setitem__(index, self.__class__(value)) else: return super(Collection, self).__setitem__( index, self._ensure_value_is_valid(value)) def __getitem__(self, index): """Return value by index or slice of values if index is slice.""" value = super(Collection, self).__getitem__(index) if isinstance(index, slice): return self.__class__(value, type_check=False) return value if six.PY2: # pragma: nocover def __getslice__(self, start, stop): """Return slice of values.""" return self.__class__(super(Collection, self).__getslice__(start, stop), type_check=False) def __setslice__(self, start, stop, iterable): """Set slice of values.""" super(Collection, self).__setslice__(start, stop, self.__class__(iterable)) def _ensure_iterable_is_valid(self, iterable): """Ensure that iterable values are a valid collection's values.""" for value in iterable: self._ensure_value_is_valid(value) return iterable def _ensure_value_is_valid(self, value): """Ensure that value is a valid collection's value.""" if not isinstance(value, self.__class__.value_type): raise TypeError('{0} is not valid collection value, instance ' 'of {1} required'.format( value, self.__class__.value_type)) return value
ets-labs/python-domain-models
domain_models/collections.py
Collection._ensure_value_is_valid
python
def _ensure_value_is_valid(self, value): if not isinstance(value, self.__class__.value_type): raise TypeError('{0} is not valid collection value, instance ' 'of {1} required'.format( value, self.__class__.value_type)) return value
Ensure that value is a valid collection's value.
train
https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/collections.py#L71-L77
null
class Collection(list): """Collection.""" value_type = object """Type of values that collection could contain.""" def __init__(self, iterable=None, type_check=True): """Initializer.""" if not iterable: iterable = tuple() if type_check: iterable = self._ensure_iterable_is_valid(iterable) super(Collection, self).__init__(iterable) def append(self, value): """Add an item to the end of the list.""" return super(Collection, self).append( self._ensure_value_is_valid(value)) def extend(self, iterable): """Extend the list by appending all the items in the given list.""" return super(Collection, self).extend( self._ensure_iterable_is_valid(iterable)) def insert(self, index, value): """Insert an item at a given position.""" return super(Collection, self).insert( index, self._ensure_value_is_valid(value)) def __setitem__(self, index, value): """Set an item at a given position.""" if isinstance(index, slice): return super(Collection, self).__setitem__(index, self.__class__(value)) else: return super(Collection, self).__setitem__( index, self._ensure_value_is_valid(value)) def __getitem__(self, index): """Return value by index or slice of values if index is slice.""" value = super(Collection, self).__getitem__(index) if isinstance(index, slice): return self.__class__(value, type_check=False) return value if six.PY2: # pragma: nocover def __getslice__(self, start, stop): """Return slice of values.""" return self.__class__(super(Collection, self).__getslice__(start, stop), type_check=False) def __setslice__(self, start, stop, iterable): """Set slice of values.""" super(Collection, self).__setslice__(start, stop, self.__class__(iterable)) def _ensure_iterable_is_valid(self, iterable): """Ensure that iterable values are a valid collection's values.""" for value in iterable: self._ensure_value_is_valid(value) return iterable
stephrdev/django-formwizard
formwizard/views.py
WizardView.as_view
python
def as_view(cls, *args, **kwargs): initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs)
This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L103-L110
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.get_initkwargs
python
def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs
Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L113-L170
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.get_form_list
python
def get_form_list(self): form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list
This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms).
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L179-L200
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.dispatch
python
def dispatch(self, request, *args, **kwargs): # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response
This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies).
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L202-L222
[ "def get_storage(path, *args, **kwargs):\n i = path.rfind('.')\n module, attr = path[:i], path[i+1:]\n try:\n mod = import_module(module)\n except ImportError, e:\n raise MissingStorageModule(\n 'Error loading storage %s: \"%s\"' % (module, e))\n try:\n storage_class =...
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.get
python
def get(self, request, *args, **kwargs): self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form())
This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L224-L236
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.post
python
def post(self, *args, **kwargs): # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form)
This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available)
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L238-L285
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.render_next_step
python
def render_next_step(self, form, **kwargs): # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs)
THis method gets called when the next step/form should be rendered. `form` contains the last/current form.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L287-L301
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.render_done
python
def render_done(self, form, **kwargs): final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response
This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L303-L325
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.get_form_prefix
python
def get_form_prefix(self, step=None, form=None): if step is None: step = self.steps.current return str(step)
Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L327-L338
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.get_form
python
def get_form(self, step=None, data=None, files=None): if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs)
Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L363-L388
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.render_revalidation_failure
python
def render_revalidation_failure(self, step, form, **kwargs): self.storage.current_step = step return self.render(form, **kwargs)
Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L404-L411
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.get_all_cleaned_data
python
def get_all_cleaned_data(self): cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data
Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L427-L447
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.get_cleaned_data_for_step
python
def get_cleaned_data_for_step(self, step): if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None
Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L449-L461
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.get_next_step
python
def get_next_step(self, step=None): if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None
Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L463-L475
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.get_prev_step
python
def get_prev_step(self, step=None): if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None
Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L477-L489
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.get_step_index
python
def get_step_index(self, step=None): if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step)
Returns the index for the given `step` name. If no step is given, the current step will be used to get the index.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L491-L498
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.get_context_data
python
def get_context_data(self, form, *args, **kwargs): context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context
Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L500-L531
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context) def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
WizardView.render
python
def render(self, form=None, **kwargs): form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context)
Returns a ``HttpResponse`` containing a all needed context data.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L533-L539
null
class WizardView(TemplateView): """ The WizardView is used to create multi-page forms and handles all the storage and validation stuff. The wizard is based on Django's generic class based views. """ storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = 'formwizard/wizard_form.html' def __repr__(self): return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list) @classonlymethod def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwargs(*args, **kwargs) return super(WizardView, cls).as_view(**initkwargs) @classmethod def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the formwizard will convert the class list to (`zero_based_counter`, `form_class`). This is needed to access the form for a specific step. * `initial_dict` - contains a dictionary of initial data dictionaries. The key should be equal to the `step_name` in the `form_list` (or the str of the zero based counter - if no step_names added in the `form_list`) * `instance_dict` - contains a dictionary of instance objects. This list is only used when `ModelForm`s are used. The key should be equal to the `step_name` in the `form_list`. Same rules as for `initial_dict` apply. * `condition_dict` - contains a dictionary of boolean values or callables. If the value of for a specific `step_name` is callable it will be called with the formwizard instance as the only argument. If the return value is true, the step's form will be used. """ kwargs.update({ 'initial_dict': initial_dict or {}, 'instance_dict': instance_dict or {}, 'condition_dict': condition_dict or {}, }) init_form_list = SortedDict() assert len(form_list) > 0, 'at least one form is needed' # walk through the passed form list for i, form in enumerate(form_list): if isinstance(form, (list, tuple)): # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list[unicode(form[0])] = form[1] else: # if not, add the form with a zero based counter as unicode init_form_list[unicode(i)] = form # walk through the ne created list of forms for form in init_form_list.itervalues(): if issubclass(form, formsets.BaseFormSet): # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form.form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form.base_fields.itervalues(): if (isinstance(field, forms.FileField) and not hasattr(cls, 'file_storage')): raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs['form_list'] = init_form_list return kwargs def get_wizard_name(self): return normalize_name(self.__class__.__name__) def get_prefix(self): # TODO: Add some kind of unique id to prefix return self.wizard_name def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in self.form_list.iteritems(): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. After processing the request using the `dispatch` method, the response gets updated by the storage engine (for example add cookies). """ # add the storage engine to the current formwizard instance self.wizard_name = self.get_wizard_name() self.prefix = self.get_prefix() self.storage = get_storage(self.storage_name, self.prefix, request, getattr(self, 'file_storage', None)) self.steps = StepsHelper(self) response = super(WizardView, self).dispatch(request, *args, **kwargs) # update the response (e.g. adding cookies) self.storage.update_response(response) return response def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first step. """ self.storage.reset() # reset the current step to the first step. self.storage.current_step = self.steps.first return self.render(self.get_form()) def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self.request.POST.get('wizard_prev_step', None) if wizard_prev_step and wizard_prev_step in self.get_form_list(): self.storage.current_step = wizard_prev_step form = self.get_form( data=self.storage.get_step_data(self.steps.current), files=self.storage.get_step_files(self.steps.current)) return self.render(form) # Check if form was refreshed management_form = ManagementForm(self.request.POST, prefix=self.prefix) if not management_form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered.') form_current_step = management_form.cleaned_data['current_step'] if (form_current_step != self.steps.current and self.storage.current_step is not None): # form refreshed, change current step self.storage.current_step = form_current_step # get the form for the current step form = self.get_form(data=self.request.POST, files=self.request.FILES) # and try to validate if form.is_valid(): # if the form is valid, store the cleaned data and files. self.storage.set_step_data(self.steps.current, self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form)) # check if the current step is the last step if self.steps.current == self.steps.last: # no more steps, render done view return self.render_done(form, **kwargs) else: # proceed to the next step return self.render_next_step(form) return self.render(form) def render_next_step(self, form, **kwargs): """ THis method gets called when the next step/form should be rendered. `form` contains the last/current form. """ # get the form instance based on the data from the storage backend # (if available). next_step = self.steps.next new_form = self.get_form(next_step, data=self.storage.get_step_data(next_step), files=self.storage.get_step_files(next_step)) # change the stored current step self.storage.current_step = next_step return self.render(new_form, **kwargs) def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. """ final_form_list = [] # walk through the form list and try to validate the data again. for form_key in self.get_form_list(): form_obj = self.get_form(step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key)) if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) final_form_list.append(form_obj) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self.done(final_form_list, **kwargs) self.storage.reset() return done_response def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will determine the current step automatically. """ if step is None: step = self.steps.current return str(step) def get_form_initial(self, step): """ Returns a dictionary which will be passed to the form for `step` as `initial`. If no initial data was provied while initializing the form wizard, a empty dictionary will be returned. """ return self.initial_dict.get(step, {}) def get_form_instance(self, step): """ Returns a object which will be passed to the form for `step` as `instance`. If no instance object was provied while initializing the form wizard, None be returned. """ return self.instance_dict.get(step, None) def get_form_kwargs(self, step=None): """ Returns the keyword arguments for instantiating the form (or formset) on given step. """ return {} def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or queryset (for `ModelForm` or `ModelFormSet`) will be added too. """ if step is None: step = self.steps.current # prepare the kwargs for the form instance. kwargs = self.get_form_kwargs(step) kwargs.update({ 'data': data, 'files': files, 'prefix': self.get_form_prefix(step, self.form_list[step]), 'initial': self.get_form_initial(step), }) if issubclass(self.form_list[step], forms.ModelForm): # If the form is based on ModelForm, add instance if available. kwargs.update({'instance': self.get_form_instance(step)}) elif issubclass(self.form_list[step], forms.models.BaseModelFormSet): # If the form is based on ModelFormSet, add queryset if available. kwargs.update({'queryset': self.get_form_instance(step)}) return self.form_list[step](**kwargs) def process_step(self, form): """ This method is used to postprocess the form data. By default, it returns the raw `form.data` dictionary. """ return self.get_form_step_data(form) def process_step_files(self, form): """ This method is used to postprocess the form files. By default, it returns the raw `form.files` dictionary. """ return self.get_form_step_files(form) def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return self.render(form, **kwargs) def get_form_step_data(self, form): """ Is used to return the raw form data. You may use this method to manipulate the data. """ return form.data def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for form_key in self.get_form_list(): form_obj = self.get_form( step=form_key, data=self.storage.get_step_data(form_key), files=self.storage.get_step_files(form_key) ) if form_obj.is_valid(): if isinstance(form_obj.cleaned_data, (tuple, list)): cleaned_data.update({ 'formset-%s' % form_key: form_obj.cleaned_data }) else: cleaned_data.update(form_obj.cleaned_data) return cleaned_data def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: form_obj = self.get_form(step=step, data=self.storage.get_step_data(step), files=self.storage.get_step_files(step)) if form_obj.is_valid(): return form_obj.cleaned_data return None def get_next_step(self, step=None): """ Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) + 1 if len(form_list.keyOrder) > key: return form_list.keyOrder[key] return None def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = self.steps.current form_list = self.get_form_list() key = form_list.keyOrder.index(step) - 1 if key >= 0: return form_list.keyOrder[key] return None def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step) def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: * all extra data stored in the storage backend * `form` - form instance of the current step * `wizard` - the wizard instance itself Example: .. code-block:: python class MyWizard(FormWizard): def get_context_data(self, form, **kwargs): context = super(MyWizard, self).get_context_data(form, **kwargs) if self.steps.current == 'my_step_name': context.update({'another_var': True}) return context """ context = super(WizardView, self).get_context_data(*args, **kwargs) context.update(self.storage.extra_data) context['wizard'] = { 'form': form, 'steps': self.steps, 'management_form': ManagementForm(prefix=self.prefix, initial={ 'current_step': self.steps.current, }), } return context def done(self, form_list, **kwargs): """ This method muss be overrided by a subclass to process to form data after processing all steps. """ raise NotImplementedError("Your %s class has not defined a done() " "method, which is required." % self.__class__.__name__)
stephrdev/django-formwizard
formwizard/views.py
NamedUrlWizardView.get_initkwargs
python
def get_initkwargs(cls, *args, **kwargs): assert 'url_name' in kwargs, 'URL name is needed to resolve correct wizard URLs' extra_kwargs = { 'done_step_name': kwargs.pop('done_step_name', 'done'), 'url_name': kwargs.pop('url_name'), } initkwargs = super(NamedUrlWizardView, cls).get_initkwargs(*args, **kwargs) initkwargs.update(extra_kwargs) assert initkwargs['done_step_name'] not in initkwargs['form_list'], \ 'step name "%s" is reserved for "done" view' % initkwargs['done_step_name'] return initkwargs
We require a url_name to reverse URLs later. Additionally users can pass a done_step_name to change the URL name of the "done" view.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L572-L588
null
class NamedUrlWizardView(WizardView): """ A WizardView with URL named steps support. """ url_name = None done_step_name = None @classmethod def get(self, *args, **kwargs): """ This renders the form or, if needed, does the http redirects. """ step_url = kwargs.get('step', None) if step_url is None: if 'reset' in self.request.GET: self.storage.reset() self.storage.current_step = self.steps.first if self.request.GET: query_string = "?%s" % self.request.GET.urlencode() else: query_string = "" next_step_url = reverse(self.url_name, kwargs={ 'step': self.steps.current, }) + query_string return redirect(next_step_url) # is the current step the "done" name/view? elif step_url == self.done_step_name: last_step = self.steps.last return self.render_done(self.get_form(step=last_step, data=self.storage.get_step_data(last_step), files=self.storage.get_step_files(last_step) ), **kwargs) # is the url step name not equal to the step in the storage? # if yes, change the step in the storage (if name exists) elif step_url == self.steps.current: # URL step name and storage step name are equal, render! return self.render(self.get_form( data=self.storage.current_step_data, files=self.storage.current_step_data, ), **kwargs) elif step_url in self.get_form_list(): self.storage.current_step = step_url return self.render(self.get_form( data=self.storage.current_step_data, files=self.storage.current_step_data, ), **kwargs) # invalid step name, reset to first and redirect. else: self.storage.current_step = self.steps.first return redirect(self.url_name, step=self.steps.first) def post(self, *args, **kwargs): """ Do a redirect if user presses the prev. step button. The rest of this is super'd from FormWizard. """ prev_step = self.request.POST.get('wizard_prev_step', None) if prev_step and prev_step in self.get_form_list(): self.storage.current_step = prev_step return redirect(self.url_name, step=prev_step) return super(NamedUrlWizardView, self).post(*args, **kwargs) def render_next_step(self, form, **kwargs): """ When using the NamedUrlFormWizard, we have to redirect to update the browser's URL to match the shown step. """ next_step = self.get_next_step() self.storage.current_step = next_step return redirect(self.url_name, step=next_step) def render_revalidation_failure(self, failed_step, form, **kwargs): """ When a step fails, we have to redirect the user to the first failing step. """ self.storage.current_step = failed_step return redirect(self.url_name, step=failed_step) def render_done(self, form, **kwargs): """ When rendering the done view, we have to redirect first (if the URL name doesn't fit). """ if kwargs.get('step', None) != self.done_step_name: return redirect(self.url_name, step=self.done_step_name) return super(NamedUrlWizardView, self).render_done(form, **kwargs)
stephrdev/django-formwizard
formwizard/views.py
NamedUrlWizardView.get
python
def get(self, *args, **kwargs): step_url = kwargs.get('step', None) if step_url is None: if 'reset' in self.request.GET: self.storage.reset() self.storage.current_step = self.steps.first if self.request.GET: query_string = "?%s" % self.request.GET.urlencode() else: query_string = "" next_step_url = reverse(self.url_name, kwargs={ 'step': self.steps.current, }) + query_string return redirect(next_step_url) # is the current step the "done" name/view? elif step_url == self.done_step_name: last_step = self.steps.last return self.render_done(self.get_form(step=last_step, data=self.storage.get_step_data(last_step), files=self.storage.get_step_files(last_step) ), **kwargs) # is the url step name not equal to the step in the storage? # if yes, change the step in the storage (if name exists) elif step_url == self.steps.current: # URL step name and storage step name are equal, render! return self.render(self.get_form( data=self.storage.current_step_data, files=self.storage.current_step_data, ), **kwargs) elif step_url in self.get_form_list(): self.storage.current_step = step_url return self.render(self.get_form( data=self.storage.current_step_data, files=self.storage.current_step_data, ), **kwargs) # invalid step name, reset to first and redirect. else: self.storage.current_step = self.steps.first return redirect(self.url_name, step=self.steps.first)
This renders the form or, if needed, does the http redirects.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L590-L635
null
class NamedUrlWizardView(WizardView): """ A WizardView with URL named steps support. """ url_name = None done_step_name = None @classmethod def get_initkwargs(cls, *args, **kwargs): """ We require a url_name to reverse URLs later. Additionally users can pass a done_step_name to change the URL name of the "done" view. """ assert 'url_name' in kwargs, 'URL name is needed to resolve correct wizard URLs' extra_kwargs = { 'done_step_name': kwargs.pop('done_step_name', 'done'), 'url_name': kwargs.pop('url_name'), } initkwargs = super(NamedUrlWizardView, cls).get_initkwargs(*args, **kwargs) initkwargs.update(extra_kwargs) assert initkwargs['done_step_name'] not in initkwargs['form_list'], \ 'step name "%s" is reserved for "done" view' % initkwargs['done_step_name'] return initkwargs def post(self, *args, **kwargs): """ Do a redirect if user presses the prev. step button. The rest of this is super'd from FormWizard. """ prev_step = self.request.POST.get('wizard_prev_step', None) if prev_step and prev_step in self.get_form_list(): self.storage.current_step = prev_step return redirect(self.url_name, step=prev_step) return super(NamedUrlWizardView, self).post(*args, **kwargs) def render_next_step(self, form, **kwargs): """ When using the NamedUrlFormWizard, we have to redirect to update the browser's URL to match the shown step. """ next_step = self.get_next_step() self.storage.current_step = next_step return redirect(self.url_name, step=next_step) def render_revalidation_failure(self, failed_step, form, **kwargs): """ When a step fails, we have to redirect the user to the first failing step. """ self.storage.current_step = failed_step return redirect(self.url_name, step=failed_step) def render_done(self, form, **kwargs): """ When rendering the done view, we have to redirect first (if the URL name doesn't fit). """ if kwargs.get('step', None) != self.done_step_name: return redirect(self.url_name, step=self.done_step_name) return super(NamedUrlWizardView, self).render_done(form, **kwargs)
stephrdev/django-formwizard
formwizard/views.py
NamedUrlWizardView.post
python
def post(self, *args, **kwargs): prev_step = self.request.POST.get('wizard_prev_step', None) if prev_step and prev_step in self.get_form_list(): self.storage.current_step = prev_step return redirect(self.url_name, step=prev_step) return super(NamedUrlWizardView, self).post(*args, **kwargs)
Do a redirect if user presses the prev. step button. The rest of this is super'd from FormWizard.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L637-L646
null
class NamedUrlWizardView(WizardView): """ A WizardView with URL named steps support. """ url_name = None done_step_name = None @classmethod def get_initkwargs(cls, *args, **kwargs): """ We require a url_name to reverse URLs later. Additionally users can pass a done_step_name to change the URL name of the "done" view. """ assert 'url_name' in kwargs, 'URL name is needed to resolve correct wizard URLs' extra_kwargs = { 'done_step_name': kwargs.pop('done_step_name', 'done'), 'url_name': kwargs.pop('url_name'), } initkwargs = super(NamedUrlWizardView, cls).get_initkwargs(*args, **kwargs) initkwargs.update(extra_kwargs) assert initkwargs['done_step_name'] not in initkwargs['form_list'], \ 'step name "%s" is reserved for "done" view' % initkwargs['done_step_name'] return initkwargs def get(self, *args, **kwargs): """ This renders the form or, if needed, does the http redirects. """ step_url = kwargs.get('step', None) if step_url is None: if 'reset' in self.request.GET: self.storage.reset() self.storage.current_step = self.steps.first if self.request.GET: query_string = "?%s" % self.request.GET.urlencode() else: query_string = "" next_step_url = reverse(self.url_name, kwargs={ 'step': self.steps.current, }) + query_string return redirect(next_step_url) # is the current step the "done" name/view? elif step_url == self.done_step_name: last_step = self.steps.last return self.render_done(self.get_form(step=last_step, data=self.storage.get_step_data(last_step), files=self.storage.get_step_files(last_step) ), **kwargs) # is the url step name not equal to the step in the storage? # if yes, change the step in the storage (if name exists) elif step_url == self.steps.current: # URL step name and storage step name are equal, render! return self.render(self.get_form( data=self.storage.current_step_data, files=self.storage.current_step_data, ), **kwargs) elif step_url in self.get_form_list(): self.storage.current_step = step_url return self.render(self.get_form( data=self.storage.current_step_data, files=self.storage.current_step_data, ), **kwargs) # invalid step name, reset to first and redirect. else: self.storage.current_step = self.steps.first return redirect(self.url_name, step=self.steps.first) def render_next_step(self, form, **kwargs): """ When using the NamedUrlFormWizard, we have to redirect to update the browser's URL to match the shown step. """ next_step = self.get_next_step() self.storage.current_step = next_step return redirect(self.url_name, step=next_step) def render_revalidation_failure(self, failed_step, form, **kwargs): """ When a step fails, we have to redirect the user to the first failing step. """ self.storage.current_step = failed_step return redirect(self.url_name, step=failed_step) def render_done(self, form, **kwargs): """ When rendering the done view, we have to redirect first (if the URL name doesn't fit). """ if kwargs.get('step', None) != self.done_step_name: return redirect(self.url_name, step=self.done_step_name) return super(NamedUrlWizardView, self).render_done(form, **kwargs)
stephrdev/django-formwizard
formwizard/views.py
NamedUrlWizardView.render_next_step
python
def render_next_step(self, form, **kwargs): next_step = self.get_next_step() self.storage.current_step = next_step return redirect(self.url_name, step=next_step)
When using the NamedUrlFormWizard, we have to redirect to update the browser's URL to match the shown step.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L648-L655
null
class NamedUrlWizardView(WizardView): """ A WizardView with URL named steps support. """ url_name = None done_step_name = None @classmethod def get_initkwargs(cls, *args, **kwargs): """ We require a url_name to reverse URLs later. Additionally users can pass a done_step_name to change the URL name of the "done" view. """ assert 'url_name' in kwargs, 'URL name is needed to resolve correct wizard URLs' extra_kwargs = { 'done_step_name': kwargs.pop('done_step_name', 'done'), 'url_name': kwargs.pop('url_name'), } initkwargs = super(NamedUrlWizardView, cls).get_initkwargs(*args, **kwargs) initkwargs.update(extra_kwargs) assert initkwargs['done_step_name'] not in initkwargs['form_list'], \ 'step name "%s" is reserved for "done" view' % initkwargs['done_step_name'] return initkwargs def get(self, *args, **kwargs): """ This renders the form or, if needed, does the http redirects. """ step_url = kwargs.get('step', None) if step_url is None: if 'reset' in self.request.GET: self.storage.reset() self.storage.current_step = self.steps.first if self.request.GET: query_string = "?%s" % self.request.GET.urlencode() else: query_string = "" next_step_url = reverse(self.url_name, kwargs={ 'step': self.steps.current, }) + query_string return redirect(next_step_url) # is the current step the "done" name/view? elif step_url == self.done_step_name: last_step = self.steps.last return self.render_done(self.get_form(step=last_step, data=self.storage.get_step_data(last_step), files=self.storage.get_step_files(last_step) ), **kwargs) # is the url step name not equal to the step in the storage? # if yes, change the step in the storage (if name exists) elif step_url == self.steps.current: # URL step name and storage step name are equal, render! return self.render(self.get_form( data=self.storage.current_step_data, files=self.storage.current_step_data, ), **kwargs) elif step_url in self.get_form_list(): self.storage.current_step = step_url return self.render(self.get_form( data=self.storage.current_step_data, files=self.storage.current_step_data, ), **kwargs) # invalid step name, reset to first and redirect. else: self.storage.current_step = self.steps.first return redirect(self.url_name, step=self.steps.first) def post(self, *args, **kwargs): """ Do a redirect if user presses the prev. step button. The rest of this is super'd from FormWizard. """ prev_step = self.request.POST.get('wizard_prev_step', None) if prev_step and prev_step in self.get_form_list(): self.storage.current_step = prev_step return redirect(self.url_name, step=prev_step) return super(NamedUrlWizardView, self).post(*args, **kwargs) def render_revalidation_failure(self, failed_step, form, **kwargs): """ When a step fails, we have to redirect the user to the first failing step. """ self.storage.current_step = failed_step return redirect(self.url_name, step=failed_step) def render_done(self, form, **kwargs): """ When rendering the done view, we have to redirect first (if the URL name doesn't fit). """ if kwargs.get('step', None) != self.done_step_name: return redirect(self.url_name, step=self.done_step_name) return super(NamedUrlWizardView, self).render_done(form, **kwargs)
stephrdev/django-formwizard
formwizard/views.py
NamedUrlWizardView.render_revalidation_failure
python
def render_revalidation_failure(self, failed_step, form, **kwargs): self.storage.current_step = failed_step return redirect(self.url_name, step=failed_step)
When a step fails, we have to redirect the user to the first failing step.
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L657-L663
null
class NamedUrlWizardView(WizardView): """ A WizardView with URL named steps support. """ url_name = None done_step_name = None @classmethod def get_initkwargs(cls, *args, **kwargs): """ We require a url_name to reverse URLs later. Additionally users can pass a done_step_name to change the URL name of the "done" view. """ assert 'url_name' in kwargs, 'URL name is needed to resolve correct wizard URLs' extra_kwargs = { 'done_step_name': kwargs.pop('done_step_name', 'done'), 'url_name': kwargs.pop('url_name'), } initkwargs = super(NamedUrlWizardView, cls).get_initkwargs(*args, **kwargs) initkwargs.update(extra_kwargs) assert initkwargs['done_step_name'] not in initkwargs['form_list'], \ 'step name "%s" is reserved for "done" view' % initkwargs['done_step_name'] return initkwargs def get(self, *args, **kwargs): """ This renders the form or, if needed, does the http redirects. """ step_url = kwargs.get('step', None) if step_url is None: if 'reset' in self.request.GET: self.storage.reset() self.storage.current_step = self.steps.first if self.request.GET: query_string = "?%s" % self.request.GET.urlencode() else: query_string = "" next_step_url = reverse(self.url_name, kwargs={ 'step': self.steps.current, }) + query_string return redirect(next_step_url) # is the current step the "done" name/view? elif step_url == self.done_step_name: last_step = self.steps.last return self.render_done(self.get_form(step=last_step, data=self.storage.get_step_data(last_step), files=self.storage.get_step_files(last_step) ), **kwargs) # is the url step name not equal to the step in the storage? # if yes, change the step in the storage (if name exists) elif step_url == self.steps.current: # URL step name and storage step name are equal, render! return self.render(self.get_form( data=self.storage.current_step_data, files=self.storage.current_step_data, ), **kwargs) elif step_url in self.get_form_list(): self.storage.current_step = step_url return self.render(self.get_form( data=self.storage.current_step_data, files=self.storage.current_step_data, ), **kwargs) # invalid step name, reset to first and redirect. else: self.storage.current_step = self.steps.first return redirect(self.url_name, step=self.steps.first) def post(self, *args, **kwargs): """ Do a redirect if user presses the prev. step button. The rest of this is super'd from FormWizard. """ prev_step = self.request.POST.get('wizard_prev_step', None) if prev_step and prev_step in self.get_form_list(): self.storage.current_step = prev_step return redirect(self.url_name, step=prev_step) return super(NamedUrlWizardView, self).post(*args, **kwargs) def render_next_step(self, form, **kwargs): """ When using the NamedUrlFormWizard, we have to redirect to update the browser's URL to match the shown step. """ next_step = self.get_next_step() self.storage.current_step = next_step return redirect(self.url_name, step=next_step) def render_done(self, form, **kwargs): """ When rendering the done view, we have to redirect first (if the URL name doesn't fit). """ if kwargs.get('step', None) != self.done_step_name: return redirect(self.url_name, step=self.done_step_name) return super(NamedUrlWizardView, self).render_done(form, **kwargs)
stephrdev/django-formwizard
formwizard/views.py
NamedUrlWizardView.render_done
python
def render_done(self, form, **kwargs): if kwargs.get('step', None) != self.done_step_name: return redirect(self.url_name, step=self.done_step_name) return super(NamedUrlWizardView, self).render_done(form, **kwargs)
When rendering the done view, we have to redirect first (if the URL name doesn't fit).
train
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L665-L672
null
class NamedUrlWizardView(WizardView): """ A WizardView with URL named steps support. """ url_name = None done_step_name = None @classmethod def get_initkwargs(cls, *args, **kwargs): """ We require a url_name to reverse URLs later. Additionally users can pass a done_step_name to change the URL name of the "done" view. """ assert 'url_name' in kwargs, 'URL name is needed to resolve correct wizard URLs' extra_kwargs = { 'done_step_name': kwargs.pop('done_step_name', 'done'), 'url_name': kwargs.pop('url_name'), } initkwargs = super(NamedUrlWizardView, cls).get_initkwargs(*args, **kwargs) initkwargs.update(extra_kwargs) assert initkwargs['done_step_name'] not in initkwargs['form_list'], \ 'step name "%s" is reserved for "done" view' % initkwargs['done_step_name'] return initkwargs def get(self, *args, **kwargs): """ This renders the form or, if needed, does the http redirects. """ step_url = kwargs.get('step', None) if step_url is None: if 'reset' in self.request.GET: self.storage.reset() self.storage.current_step = self.steps.first if self.request.GET: query_string = "?%s" % self.request.GET.urlencode() else: query_string = "" next_step_url = reverse(self.url_name, kwargs={ 'step': self.steps.current, }) + query_string return redirect(next_step_url) # is the current step the "done" name/view? elif step_url == self.done_step_name: last_step = self.steps.last return self.render_done(self.get_form(step=last_step, data=self.storage.get_step_data(last_step), files=self.storage.get_step_files(last_step) ), **kwargs) # is the url step name not equal to the step in the storage? # if yes, change the step in the storage (if name exists) elif step_url == self.steps.current: # URL step name and storage step name are equal, render! return self.render(self.get_form( data=self.storage.current_step_data, files=self.storage.current_step_data, ), **kwargs) elif step_url in self.get_form_list(): self.storage.current_step = step_url return self.render(self.get_form( data=self.storage.current_step_data, files=self.storage.current_step_data, ), **kwargs) # invalid step name, reset to first and redirect. else: self.storage.current_step = self.steps.first return redirect(self.url_name, step=self.steps.first) def post(self, *args, **kwargs): """ Do a redirect if user presses the prev. step button. The rest of this is super'd from FormWizard. """ prev_step = self.request.POST.get('wizard_prev_step', None) if prev_step and prev_step in self.get_form_list(): self.storage.current_step = prev_step return redirect(self.url_name, step=prev_step) return super(NamedUrlWizardView, self).post(*args, **kwargs) def render_next_step(self, form, **kwargs): """ When using the NamedUrlFormWizard, we have to redirect to update the browser's URL to match the shown step. """ next_step = self.get_next_step() self.storage.current_step = next_step return redirect(self.url_name, step=next_step) def render_revalidation_failure(self, failed_step, form, **kwargs): """ When a step fails, we have to redirect the user to the first failing step. """ self.storage.current_step = failed_step return redirect(self.url_name, step=failed_step)
hwmrocker/smtplibaio
smtplibaio/streams.py
SMTPStreamReader.read_reply
python
async def read_reply(self): code = 500 messages = [] go_on = True while go_on: try: line = await self.readline() except ValueError as e: # ValueError is raised when limit is reached before we could # get an entire line. # We return what we got with a 500 code and we stop to read # the reply to avoid being flooded. code = 500 go_on = False else: try: code = int(line[:3]) except ValueError as e: # We either: # - Got an empty line (connection is probably down), # - Got a line without a valid return code. # In both case, it shouldn't happen, hence: raise ConnectionResetError("Connection lost.") from e else: # Check is we have a multiline response: go_on = line[3:4] == b"-" message = line[4:].strip(b" \t\r\n").decode("ascii") messages.append(message) full_message = "\n".join(messages) return code, full_message
Reads a reply from the server. Raises: ConnectionResetError: If the connection with the server is lost (we can't read any response anymore). Or if the server replies without a proper return code. Returns: (int, str): A (code, full_message) 2-tuple consisting of: - server response code ; - server response string corresponding to response code (multiline responses are returned in a single string).
train
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/streams.py#L31-L79
null
class SMTPStreamReader(StreamReader): """ StreamReader used to communicate with the server during the SMTP session. .. seealso:: `asyncio Streams API <https://docs.python.org/3/library/asyncio-stream.html>`_ """ # RFC 2821 § 4.5.3.1 says a line is max. 512 chars long. # We chose to support a bit more :o) line_max_length = 8192 def __init__(self, limit=line_max_length, loop=None): """ Initializes a new SMTPStreamReader instance. Args: limit (int): Maximal length of data that can be returned in bytes, not counting the separator. RFC 2821 specifies this should be 512, but the default provided value is 8192. loop (:obj:`asyncio.BaseEventLoop`): Event loop to connect to. """ super().__init__(limit, loop)
hwmrocker/smtplibaio
smtplibaio/streams.py
SMTPStreamWriter.send_command
python
async def send_command(self, command): command = "{}\r\n".format(command).encode("ascii", errors="backslashreplace") self.write(command) # Don't forget to drain or the command will stay buffered: await self.drain()
Sends the given command to the server. Args: command (str): Command to send to the server. Raises: ConnectionResetError: If the connection with the server is lost. (Shouldn't it raise BrokenPipeError too ?)
train
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/streams.py#L89-L105
null
class SMTPStreamWriter(StreamWriter): """ StreamWriter used to communicate with the server during the SMTP session. .. seealso:: `asyncio Streams API <https://docs.python.org/3/library/asyncio-stream.html>`_ """
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.fqdn
python
def fqdn(self): if self._fqdn is None: # Let's try to retrieve it: self._fqdn = socket.getfqdn() if "." not in self._fqdn: try: info = socket.getaddrinfo( host="localhost", port=None, proto=socket.IPPROTO_TCP ) except socket.gaierror: addr = "127.0.0.1" else: # We only consider the first returned result and we're # only interested in getting the IP(v4 or v6) address: addr = info[0][4][0] self._fqdn = "[{}]".format(addr) return self._fqdn
Returns the string used to identify the client when initiating a SMTP session. RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do: - Use the client FQDN ; - If it isn't available, we SHOULD fall back to an address literal. Returns: str: The value that should be used as the client FQDN. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 .. _`§ 4.1.3`: https//tools.ietf.org/html/rfc5321#section-4.1.3
train
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L132-L166
null
class SMTP: """ SMTP or ESMTP client. This should follow RFC 5321 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP Authentication) and RFC 2487 (Secure SMTP over TLS). Attributes: hostname (str): Hostname of the SMTP server we are connecting to. port (int): Port on which the SMTP server listens for connections. timeout (int): Not used. last_helo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *HELO* response. last_ehlo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *EHLO* response. supports_esmtp (bool): True if the server supports ESMTP (set after a *EHLO* command, False otherwise. esmtp_extensions (dict): ESMTP extensions and parameters supported by the SMTP server (set after a *EHLO* command). auth_mechanisms (list of str): Authentication mechanisms supported by the SMTP server. ssl_context (bool): Always False. (Used in SMTP_SSL subclass) reader (:class:`streams.SMTPStreamReader`): SMTP stream reader, used to read server responses. writer (:class:`streams.SMTPStreamWriter`): SMTP stream writer, used to send commands to the server. transport (:class:`asyncio.BaseTransport`): Communication channel abstraction between client and server. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): If True, the connection is made using the aioopenssl module. Defaults to False. _fqdn (str): Client FQDN. Used to identify the client to the server. Class Attributes: _default_port (int): Default port to use. Defaults to 25. _supported_auth_mechanisms (dict): Dict containing the information about supported authentication mechanisms, ordered by preference of use. The entries consist in : - The authentication mechanism name, in lowercase, as given by SMTP servers. - The name of the method to call to authenticate using the mechanism. """ _default_port = 25 _supported_auth_mechanisms = { "cram-md5": "_auth_cram_md5", "plain": "_auth_plain", "login": "_auth_login", } def __init__( self, hostname="localhost", port=_default_port, fqdn=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, loop=None, use_aioopenssl=False, ): """ Initializes a new :class:`SMTP` instance. Args: hostname (str): Hostname of the SMTP server to connect to. port (int): Port to use to connect to the SMTP server. fqdn (str or None): Client Fully Qualified Domain Name. This is used to identify the client to the server. timeout (int): Not used. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): Use the aioopenssl module to open the connection. This is mandatory if you plan on using STARTTLS. """ self.hostname = hostname try: self.port = int(port) except ValueError: self.port = self.__class__._default_port self.timeout = timeout self._fqdn = fqdn self.loop = loop or asyncio.get_event_loop() self.use_aioopenssl = use_aioopenssl self.reset_state() @property def reset_state(self): """ Resets some attributes to their default values. This is especially useful when initializing a newly created :class:`SMTP` instance and when closing an existing SMTP session. It allows us to use the same SMTP instance and connect several times. """ self.last_helo_response = (None, None) self.last_ehlo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] self.ssl_context = False self.reader = None self.writer = None self.transport = None async def __aenter__(self): """ Enters the asynchronous context manager. Also tries to connect to the server. Raises: SMTPConnectionRefusedError: If the connection between client and SMTP server can not be established. .. seealso:: :meth:`SMTP.connect` """ await self.connect() return self async def __aexit__(self, *args): """ Exits the asynchronous context manager. Closes the connection and resets instance attributes. .. seealso:: :meth:`SMTP.quit` """ await self.quit() async def connect(self): """ Connects to the server. .. note:: This method is automatically invoked by :meth:`SMTP.__aenter__`. The code is mostly borrowed from the :func:`asyncio.streams.open_connection` source code. Raises: ConnectionError subclass: If the connection between client and SMTP server can not be established. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ # First build the reader: self.reader = SMTPStreamReader(loop=self.loop) # Then build the protocol: protocol = asyncio.StreamReaderProtocol(self.reader, loop=self.loop) # With the just-built reader and protocol, create the connection and # get the transport stream: conn = { "protocol_factory": lambda: protocol, "host": self.hostname, "port": self.port, } if self.use_aioopenssl: conn.update( { "use_starttls": not self.ssl_context, "ssl_context_factory": lambda transport: self.ssl_context, "server_hostname": self.hostname, # For SSL } ) import aioopenssl # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await aioopenssl.create_starttls_connection( self.loop, **conn ) # HACK: aioopenssl transports don't implement is_closing, and thus drain() fails... self.transport.is_closing = lambda: False else: conn["ssl"] = self.ssl_context # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await self.loop.create_connection(**conn) # If the connection has been established, build the writer: self.writer = SMTPStreamWriter(self.transport, protocol, self.reader, self.loop) code, message = await self.reader.read_reply() if code != 220: raise ConnectionRefusedError(code, message) return code, message async def do_cmd(self, *args, success=None): """ Sends the given command to the server. Args: *args: Command and arguments to be sent to the server. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ if success is None: success = (250,) cmd = " ".join(args) await self.writer.send_command(cmd) code, message = await self.reader.read_reply() if code not in success: raise SMTPCommandFailedError(code, message, cmd) return code, message async def helo(self, from_host=None): """ Sends a SMTP 'HELO' command. - Identifies the client and starts the session. If given ``from_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our HELO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("HELO", from_host) self.last_helo_response = (code, message) return code, message async def ehlo(self, from_host=None): """ Sends a SMTP 'EHLO' command. - Identifies the client and starts the session. If given ``from`_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("EHLO", from_host) self.last_ehlo_response = (code, message) extns, auths = SMTP.parse_esmtp_extensions(message) self.esmtp_extensions = extns self.auth_mechanisms = auths self.supports_esmtp = True return code, message async def help(self, command_name=None): """ Sends a SMTP 'HELP' command. For further details please check out `RFC 5321 § 4.1.1.8`_. Args: command_name (str or None, optional): Name of a command for which you want help. For example, if you want to get help about the '*RSET*' command, you'd call ``help('RSET')``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the HELP command fails. Returns: Help text as given by the server. .. _`RFC 5321 § 4.1.1.8`: https://tools.ietf.org/html/rfc5321#section-4.1.1.8 """ if command_name is None: command_name = "" code, message = await self.do_cmd("HELP", command_name) return message async def rset(self): """ Sends a SMTP 'RSET' command. - Resets the session. For further details, please check out `RFC 5321 § 4.1.1.5`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RSET command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.5`: https://tools.ietf.org/html/rfc5321#section-4.1.1.5 """ return await self.do_cmd("RSET") async def noop(self): """ Sends a SMTP 'NOOP' command. - Doesn't do anything. For further details, please check out `RFC 5321 § 4.1.1.9`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the NOOP command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.9`: https://tools.ietf.org/html/rfc5321#section-4.1.1.9 """ return await self.do_cmd("NOOP") async def vrfy(self, address): """ Sends a SMTP 'VRFY' command. - Tests the validity of the given address. For further details, please check out `RFC 5321 § 4.1.1.6`_. Args: address (str): E-mail address to be checked. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the VRFY command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.6`: https://tools.ietf.org/html/rfc5321#section-4.1.1.6 """ return await self.do_cmd("VRFY", address) async def expn(self, address): """ Sends a SMTP 'EXPN' command. - Expands a mailing-list. For further details, please check out `RFC 5321 § 4.1.1.7`_. Args: address (str): E-mail address to expand. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the EXPN command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.7`: https://tools.ietf.org/html/rfc5321#section-4.1.1.7 """ return await self.do_cmd("EXPN", address) async def mail(self, sender, options=None): """ Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] from_addr = "FROM:{}".format(quoteaddr(sender)) code, message = await self.do_cmd("MAIL", from_addr, *options) return code, message async def rcpt(self, recipient, options=None): """ Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. options (list of str or None, optional): Additional options to send along with the *RCPT* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RCPT command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.3`: https://tools.ietf.org/html/rfc5321#section-4.1.1.3 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] to_addr = "TO:{}".format(quoteaddr(recipient)) code, message = await self.do_cmd("RCPT", to_addr, *options) return code, message async def quit(self): """ Sends a SMTP 'QUIT' command. - Ends the session. For further details, please check out `RFC 5321 § 4.1.1.10`_. Returns: (int, str): A (code, message) 2-tuple containing the server response. If the connection is already closed when calling this method, returns (-1, None). .. _`RFC 5321 § 4.1.1.10`: https://tools.ietf.org/html/rfc5321#section-4.1.1.10 """ code = -1 message = None try: code, message = await self.do_cmd("QUIT") except ConnectionError: # We voluntarily ignore this kind of exceptions since... the # connection seems already closed. pass except SMTPCommandFailedError: pass await self.close() return code, message async def data(self, email_message): """ Sends a SMTP 'DATA' command. - Transmits the message to the server. If ``email_message`` is a bytes object, sends it as it is. Else, makes all the required changes so it can be safely trasmitted to the SMTP server.` For further details, please check out `RFC 5321 § 4.1.1.4`_. Args: email_message (str or bytes): Message to be sent. Raises: ConnectionError subclass: If the connection to the server is unexpectedely lost. SMTPCommandFailedError: If the DATA command fails. Returns: (int, str): A (code, message) 2-tuple containing the server last response (the one the server sent after all data were sent by the client). .. seealso: :meth:`SMTP.prepare_message` .. _`RFC 5321 § 4.1.1.4`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 """ code, message = await self.do_cmd("DATA", success=(354,)) email_message = SMTP.prepare_message(email_message) self.writer.write(email_message) # write is non-blocking. await self.writer.drain() # don't forget to drain. code, message = await self.reader.read_reply() return code, message async def auth(self, username, password): """ Tries to authenticate user against the SMTP server. Args: username (str): Username to authenticate with. password (str): Password to use along with the given ``username``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPLoginError: If the authentication failed (either because all attempts failed or because there was no suitable authentication mechanism). Returns: (int, str): A (code, message) 2-tuple containing the last server response. """ # EHLO/HELO is required: await self.ehlo_or_helo_if_needed() errors = [] # To store SMTPAuthenticationErrors code = message = None # Try to authenticate using all mechanisms supported by both # server and client (and only these): for auth, meth in self.__class__._supported_auth_mechanisms.items(): if auth in self.auth_mechanisms: auth_func = getattr(self, meth) try: code, message = await auth_func(username, password) except SMTPAuthenticationError as e: errors.append(e) else: break else: if not errors: err = "Could not find any suitable authentication mechanism." errors.append(SMTPAuthenticationError(-1, err)) raise SMTPLoginError(errors) return code, message async def starttls(self, context=None): """ Upgrades the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports SSL/TLS, this will encrypt the rest of the SMTP session. Raises: SMTPCommandNotSupportedError: If the server does not support STARTTLS. SMTPCommandFailedError: If the STARTTLS command fails BadImplementationError: If the connection does not use aioopenssl. Args: context (:obj:`OpenSSL.SSL.Context`): SSL context Returns: (int, message): A (code, message) 2-tuple containing the server response. """ if not self.use_aioopenssl: raise BadImplementationError("This connection does not use aioopenssl") import aioopenssl import OpenSSL await self.ehlo_or_helo_if_needed() if "starttls" not in self.esmtp_extensions: raise SMTPCommandNotSupportedError("STARTTLS") code, message = await self.do_cmd("STARTTLS", success=(220,)) # Don't check for code, do_cmd did it if context is None: context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD) await self.transport.starttls(ssl_context=context) # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. # FIXME: wouldn't it be better to use reset_state here ? # And reset self.reader, self.writer and self.transport just after # Maybe also self.ssl_context ? self.last_ehlo_response = (None, None) self.last_helo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] return (code, message) async def sendmail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while sending message.") >>> else: >>> print("Result: {}.".format(r)) >>> except ConnectionError as e: >>> print(e) Result: {}. Args: sender (str): E-mail address of the sender. recipients (list of str or str): E-mail(s) address(es) of the recipient(s). message (str or bytes): Message body. mail_options (list of str): ESMTP options (such as *8BITMIME*) to send along the *MAIL* command. rcpt_options (list of str): ESMTP options (such as *DSN*) to send along all the *RCPT* commands. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPCommandFailedError: If the server refuses our MAIL command. SMTPCommandFailedError: If the server refuses our DATA command. SMTPNoRecipientError: If the server refuses all given recipients. Returns: dict: A dict containing an entry for each recipient that was refused. Each entry is associated with a (code, message) 2-tuple containing the error code and message, as returned by the server. When everythign runs smoothly, the returning dict is empty. .. note:: The connection remains open after. It's your responsibility to close it. A good practice is to use the asynchronous context manager instead. See :meth:`SMTP.__aenter__` for further details. """ # Make sure `recipients` is a list: if isinstance(recipients, str): recipients = [recipients] # Set some defaults values: if mail_options is None: mail_options = [] if rcpt_options is None: rcpt_options = [] # EHLO or HELO is required: await self.ehlo_or_helo_if_needed() if self.supports_esmtp: if "size" in self.esmtp_extensions: mail_options.append("size={}".format(len(message))) await self.mail(sender, mail_options) errors = [] for recipient in recipients: try: await self.rcpt(recipient, rcpt_options) except SMTPCommandFailedError as e: errors.append(e) if len(recipients) == len(errors): # The server refused all our recipients: raise SMTPNoRecipientError(errors) await self.data(message) # If we got here then somebody got our mail: return errors async def send_mail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Alias for :meth:`SMTP.sendmail`. """ return await self.sendmail( sender, recipients, message, mail_options, rcpt_options ) async def ehlo_or_helo_if_needed(self): """ Calls :meth:`SMTP.ehlo` and/or :meth:`SMTP.helo` if needed. If there hasn't been any previous *EHLO* or *HELO* command this session, tries to initiate the session. *EHLO* is tried first. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. """ no_helo = self.last_helo_response == (None, None) no_ehlo = self.last_ehlo_response == (None, None) if no_helo and no_ehlo: try: # First we try EHLO: await self.ehlo() except SMTPCommandFailedError: # EHLO failed, let's try HELO: await self.helo() async def close(self): """ Cleans up after the connection to the SMTP server has been closed (voluntarily or not). """ if self.writer is not None: # Close the transport: try: self.writer.close() except OSError as exc: if exc.errno != errno.ENOTCONN: raise self.reset_state() async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challenge is hashed using HMAC-MD5 and the user password as key (shared secret) ; 3) The hashed challenge is converted to a string of lowercase hexadecimal digits ; 4) The username and a space character are prepended to the hex digits ; 5) The concatenation is base64-encoded and sent to the server. 6) If the server replies with a return code of 235, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "CRAM-MD5" code, message = await self.do_cmd("AUTH", mechanism, success=(334,)) decoded_challenge = base64.b64decode(message) challenge_hash = hmac.new( key=password.encode("utf-8"), msg=decoded_challenge, digestmod="md5" ) hex_hash = challenge_hash.hexdigest() response = "{} {}".format(username, hex_hash) encoded_response = SMTP.b64enc(response) try: code, message = await self.do_cmd(encoded_response, success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_login(self, username, password): """ Performs an authentication attempt using the LOGIN mechanism. Protocol: 1. The username is base64-encoded ; 2. The string 'AUTH LOGIN' and a space character are prepended to the base64-encoded username and sent to the server ; 3. If the server replies with a 334 return code, we can go on: 1) The password is base64-encoded and sent to the server ; 2) If the server replies with a 235 return code, the user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "LOGIN" code, message = await self.do_cmd( "AUTH", mechanism, SMTP.b64enc(username), success=(334,) ) try: code, message = await self.do_cmd(SMTP.b64enc(password), success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_plain(self, username, password): """ Performs an authentication attempt using the PLAIN mechanism. Protocol: 1. Format the username and password in a suitable way ; 2. The formatted string is base64-encoded ; 3. The string 'AUTH PLAIN' and a space character are prepended to the base64-encoded username and password and sent to the server ; 4. If the server replies with a 235 return code, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "PLAIN" credentials = "\0{}\0{}".format(username, password) encoded_credentials = SMTP.b64enc(credentials) try: code, message = await self.do_cmd( "AUTH", mechanism, encoded_credentials, success=(235, 503) ) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message @staticmethod def parse_esmtp_extensions(message): """ Parses the response given by an ESMTP server after a *EHLO* command. The response is parsed to build: - A dict of supported ESMTP extensions (with parameters, if any). - A list of supported authentication methods. Returns: (dict, list): A (extensions, auth_mechanisms) 2-tuple containing the supported extensions and authentication methods. """ extns = {} auths = [] oldstyle_auth_regex = re.compile(r"auth=(?P<auth>.*)", re.IGNORECASE) extension_regex = re.compile( r"(?P<feature>[a-z0-9][a-z0-9\-]*) ?", re.IGNORECASE ) lines = message.splitlines() for line in lines[1:]: # To be able to communicate with as many SMTP servers as possible, # we have to take the old-style auth advertisement into account. match = oldstyle_auth_regex.match(line) if match: auth = match.group("auth")[0] auth = auth.lower().strip() if auth not in auths: auths.append(auth) # RFC 1869 requires a space between EHLO keyword and parameters. # It's actually stricter, in that only spaces are allowed between # parameters, but were not going to check for that here. # Note that the space isn't present if there are no parameters. match = extension_regex.match(line) if match: feature = match.group("feature").lower() params = match.string[match.end("feature") :].strip() extns[feature] = params if feature == "auth": auths.extend([param.strip().lower() for param in params.split()]) return extns, auths @staticmethod def prepare_message(message): """ Returns the given message encoded in ascii with a format suitable for SMTP transmission: - Makes sure the message is ASCII encoded ; - Normalizes line endings to '\r\n' ; - Adds a (second) period at the beginning of lines that start with a period ; - Makes sure the message ends with '\r\n.\r\n'. For further details, please check out RFC 5321 `§ 4.1.1.4`_ and `§ 4.5.2`_. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 .. _`§ 4.5.2`: https://tools.ietf.org/html/rfc5321#section-4.5.2 """ if isinstance(message, bytes): bytes_message = message else: bytes_message = message.encode("ascii") # The original algorithm uses regexes to do this stuff. # This one is -IMHO- more pythonic and it is slightly faster. # # Another version is even faster, but I chose to keep something # more pythonic and readable. # FYI, the fastest way to do all this stuff seems to be # (according to my benchmarks): # # bytes_message.replace(b"\r\n", b"\n") \ # .replace(b"\r", b"\n") \ # .replace(b"\n", b"\r\n") # # DOT_LINE_REGEX = re.compile(rb"^\.", re.MULTILINE) # bytes_message = DOT_LINE_REGEX.sub(b"..", bytes_message) # # if not bytes_message.endswith(b"\r\n"): # bytes_message += b"\r\n" # # bytes_message += b"\r\n.\r\n" lines = [] for line in bytes_message.splitlines(): if line.startswith(b"."): line = line.replace(b".", b"..", 1) lines.append(line) # Recompose the message with <CRLF> only: bytes_message = b"\r\n".join(lines) # Make sure message ends with <CRLF>.<CRLF>: bytes_message += b"\r\n.\r\n" return bytes_message @staticmethod def b64enc(s): """ Base64-encodes the given string and returns it as a :obj:`str`. This is a simple helper function that takes a str, base64-encodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: s (str): String to be converted to base64. Returns: str: A base64-encoded string. """ return base64.b64encode(s.encode("utf-8")).decode("utf-8") @staticmethod def b64dec(b): """ Base64-decodes the given :obj:`bytes` and converts it to a :obj:`str`. This is a simple helper function that takes a bytes, base64-decodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: b (bytes): A base64-encoded bytes. Returns: str: A base64-decoded string. """ return base64.b64decode(b).decode("utf-8")
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.reset_state
python
def reset_state(self): self.last_helo_response = (None, None) self.last_ehlo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] self.ssl_context = False self.reader = None self.writer = None self.transport = None
Resets some attributes to their default values. This is especially useful when initializing a newly created :class:`SMTP` instance and when closing an existing SMTP session. It allows us to use the same SMTP instance and connect several times.
train
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L168-L189
null
class SMTP: """ SMTP or ESMTP client. This should follow RFC 5321 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP Authentication) and RFC 2487 (Secure SMTP over TLS). Attributes: hostname (str): Hostname of the SMTP server we are connecting to. port (int): Port on which the SMTP server listens for connections. timeout (int): Not used. last_helo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *HELO* response. last_ehlo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *EHLO* response. supports_esmtp (bool): True if the server supports ESMTP (set after a *EHLO* command, False otherwise. esmtp_extensions (dict): ESMTP extensions and parameters supported by the SMTP server (set after a *EHLO* command). auth_mechanisms (list of str): Authentication mechanisms supported by the SMTP server. ssl_context (bool): Always False. (Used in SMTP_SSL subclass) reader (:class:`streams.SMTPStreamReader`): SMTP stream reader, used to read server responses. writer (:class:`streams.SMTPStreamWriter`): SMTP stream writer, used to send commands to the server. transport (:class:`asyncio.BaseTransport`): Communication channel abstraction between client and server. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): If True, the connection is made using the aioopenssl module. Defaults to False. _fqdn (str): Client FQDN. Used to identify the client to the server. Class Attributes: _default_port (int): Default port to use. Defaults to 25. _supported_auth_mechanisms (dict): Dict containing the information about supported authentication mechanisms, ordered by preference of use. The entries consist in : - The authentication mechanism name, in lowercase, as given by SMTP servers. - The name of the method to call to authenticate using the mechanism. """ _default_port = 25 _supported_auth_mechanisms = { "cram-md5": "_auth_cram_md5", "plain": "_auth_plain", "login": "_auth_login", } def __init__( self, hostname="localhost", port=_default_port, fqdn=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, loop=None, use_aioopenssl=False, ): """ Initializes a new :class:`SMTP` instance. Args: hostname (str): Hostname of the SMTP server to connect to. port (int): Port to use to connect to the SMTP server. fqdn (str or None): Client Fully Qualified Domain Name. This is used to identify the client to the server. timeout (int): Not used. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): Use the aioopenssl module to open the connection. This is mandatory if you plan on using STARTTLS. """ self.hostname = hostname try: self.port = int(port) except ValueError: self.port = self.__class__._default_port self.timeout = timeout self._fqdn = fqdn self.loop = loop or asyncio.get_event_loop() self.use_aioopenssl = use_aioopenssl self.reset_state() @property def fqdn(self): """ Returns the string used to identify the client when initiating a SMTP session. RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do: - Use the client FQDN ; - If it isn't available, we SHOULD fall back to an address literal. Returns: str: The value that should be used as the client FQDN. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 .. _`§ 4.1.3`: https//tools.ietf.org/html/rfc5321#section-4.1.3 """ if self._fqdn is None: # Let's try to retrieve it: self._fqdn = socket.getfqdn() if "." not in self._fqdn: try: info = socket.getaddrinfo( host="localhost", port=None, proto=socket.IPPROTO_TCP ) except socket.gaierror: addr = "127.0.0.1" else: # We only consider the first returned result and we're # only interested in getting the IP(v4 or v6) address: addr = info[0][4][0] self._fqdn = "[{}]".format(addr) return self._fqdn async def __aenter__(self): """ Enters the asynchronous context manager. Also tries to connect to the server. Raises: SMTPConnectionRefusedError: If the connection between client and SMTP server can not be established. .. seealso:: :meth:`SMTP.connect` """ await self.connect() return self async def __aexit__(self, *args): """ Exits the asynchronous context manager. Closes the connection and resets instance attributes. .. seealso:: :meth:`SMTP.quit` """ await self.quit() async def connect(self): """ Connects to the server. .. note:: This method is automatically invoked by :meth:`SMTP.__aenter__`. The code is mostly borrowed from the :func:`asyncio.streams.open_connection` source code. Raises: ConnectionError subclass: If the connection between client and SMTP server can not be established. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ # First build the reader: self.reader = SMTPStreamReader(loop=self.loop) # Then build the protocol: protocol = asyncio.StreamReaderProtocol(self.reader, loop=self.loop) # With the just-built reader and protocol, create the connection and # get the transport stream: conn = { "protocol_factory": lambda: protocol, "host": self.hostname, "port": self.port, } if self.use_aioopenssl: conn.update( { "use_starttls": not self.ssl_context, "ssl_context_factory": lambda transport: self.ssl_context, "server_hostname": self.hostname, # For SSL } ) import aioopenssl # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await aioopenssl.create_starttls_connection( self.loop, **conn ) # HACK: aioopenssl transports don't implement is_closing, and thus drain() fails... self.transport.is_closing = lambda: False else: conn["ssl"] = self.ssl_context # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await self.loop.create_connection(**conn) # If the connection has been established, build the writer: self.writer = SMTPStreamWriter(self.transport, protocol, self.reader, self.loop) code, message = await self.reader.read_reply() if code != 220: raise ConnectionRefusedError(code, message) return code, message async def do_cmd(self, *args, success=None): """ Sends the given command to the server. Args: *args: Command and arguments to be sent to the server. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ if success is None: success = (250,) cmd = " ".join(args) await self.writer.send_command(cmd) code, message = await self.reader.read_reply() if code not in success: raise SMTPCommandFailedError(code, message, cmd) return code, message async def helo(self, from_host=None): """ Sends a SMTP 'HELO' command. - Identifies the client and starts the session. If given ``from_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our HELO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("HELO", from_host) self.last_helo_response = (code, message) return code, message async def ehlo(self, from_host=None): """ Sends a SMTP 'EHLO' command. - Identifies the client and starts the session. If given ``from`_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("EHLO", from_host) self.last_ehlo_response = (code, message) extns, auths = SMTP.parse_esmtp_extensions(message) self.esmtp_extensions = extns self.auth_mechanisms = auths self.supports_esmtp = True return code, message async def help(self, command_name=None): """ Sends a SMTP 'HELP' command. For further details please check out `RFC 5321 § 4.1.1.8`_. Args: command_name (str or None, optional): Name of a command for which you want help. For example, if you want to get help about the '*RSET*' command, you'd call ``help('RSET')``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the HELP command fails. Returns: Help text as given by the server. .. _`RFC 5321 § 4.1.1.8`: https://tools.ietf.org/html/rfc5321#section-4.1.1.8 """ if command_name is None: command_name = "" code, message = await self.do_cmd("HELP", command_name) return message async def rset(self): """ Sends a SMTP 'RSET' command. - Resets the session. For further details, please check out `RFC 5321 § 4.1.1.5`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RSET command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.5`: https://tools.ietf.org/html/rfc5321#section-4.1.1.5 """ return await self.do_cmd("RSET") async def noop(self): """ Sends a SMTP 'NOOP' command. - Doesn't do anything. For further details, please check out `RFC 5321 § 4.1.1.9`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the NOOP command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.9`: https://tools.ietf.org/html/rfc5321#section-4.1.1.9 """ return await self.do_cmd("NOOP") async def vrfy(self, address): """ Sends a SMTP 'VRFY' command. - Tests the validity of the given address. For further details, please check out `RFC 5321 § 4.1.1.6`_. Args: address (str): E-mail address to be checked. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the VRFY command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.6`: https://tools.ietf.org/html/rfc5321#section-4.1.1.6 """ return await self.do_cmd("VRFY", address) async def expn(self, address): """ Sends a SMTP 'EXPN' command. - Expands a mailing-list. For further details, please check out `RFC 5321 § 4.1.1.7`_. Args: address (str): E-mail address to expand. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the EXPN command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.7`: https://tools.ietf.org/html/rfc5321#section-4.1.1.7 """ return await self.do_cmd("EXPN", address) async def mail(self, sender, options=None): """ Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] from_addr = "FROM:{}".format(quoteaddr(sender)) code, message = await self.do_cmd("MAIL", from_addr, *options) return code, message async def rcpt(self, recipient, options=None): """ Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. options (list of str or None, optional): Additional options to send along with the *RCPT* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RCPT command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.3`: https://tools.ietf.org/html/rfc5321#section-4.1.1.3 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] to_addr = "TO:{}".format(quoteaddr(recipient)) code, message = await self.do_cmd("RCPT", to_addr, *options) return code, message async def quit(self): """ Sends a SMTP 'QUIT' command. - Ends the session. For further details, please check out `RFC 5321 § 4.1.1.10`_. Returns: (int, str): A (code, message) 2-tuple containing the server response. If the connection is already closed when calling this method, returns (-1, None). .. _`RFC 5321 § 4.1.1.10`: https://tools.ietf.org/html/rfc5321#section-4.1.1.10 """ code = -1 message = None try: code, message = await self.do_cmd("QUIT") except ConnectionError: # We voluntarily ignore this kind of exceptions since... the # connection seems already closed. pass except SMTPCommandFailedError: pass await self.close() return code, message async def data(self, email_message): """ Sends a SMTP 'DATA' command. - Transmits the message to the server. If ``email_message`` is a bytes object, sends it as it is. Else, makes all the required changes so it can be safely trasmitted to the SMTP server.` For further details, please check out `RFC 5321 § 4.1.1.4`_. Args: email_message (str or bytes): Message to be sent. Raises: ConnectionError subclass: If the connection to the server is unexpectedely lost. SMTPCommandFailedError: If the DATA command fails. Returns: (int, str): A (code, message) 2-tuple containing the server last response (the one the server sent after all data were sent by the client). .. seealso: :meth:`SMTP.prepare_message` .. _`RFC 5321 § 4.1.1.4`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 """ code, message = await self.do_cmd("DATA", success=(354,)) email_message = SMTP.prepare_message(email_message) self.writer.write(email_message) # write is non-blocking. await self.writer.drain() # don't forget to drain. code, message = await self.reader.read_reply() return code, message async def auth(self, username, password): """ Tries to authenticate user against the SMTP server. Args: username (str): Username to authenticate with. password (str): Password to use along with the given ``username``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPLoginError: If the authentication failed (either because all attempts failed or because there was no suitable authentication mechanism). Returns: (int, str): A (code, message) 2-tuple containing the last server response. """ # EHLO/HELO is required: await self.ehlo_or_helo_if_needed() errors = [] # To store SMTPAuthenticationErrors code = message = None # Try to authenticate using all mechanisms supported by both # server and client (and only these): for auth, meth in self.__class__._supported_auth_mechanisms.items(): if auth in self.auth_mechanisms: auth_func = getattr(self, meth) try: code, message = await auth_func(username, password) except SMTPAuthenticationError as e: errors.append(e) else: break else: if not errors: err = "Could not find any suitable authentication mechanism." errors.append(SMTPAuthenticationError(-1, err)) raise SMTPLoginError(errors) return code, message async def starttls(self, context=None): """ Upgrades the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports SSL/TLS, this will encrypt the rest of the SMTP session. Raises: SMTPCommandNotSupportedError: If the server does not support STARTTLS. SMTPCommandFailedError: If the STARTTLS command fails BadImplementationError: If the connection does not use aioopenssl. Args: context (:obj:`OpenSSL.SSL.Context`): SSL context Returns: (int, message): A (code, message) 2-tuple containing the server response. """ if not self.use_aioopenssl: raise BadImplementationError("This connection does not use aioopenssl") import aioopenssl import OpenSSL await self.ehlo_or_helo_if_needed() if "starttls" not in self.esmtp_extensions: raise SMTPCommandNotSupportedError("STARTTLS") code, message = await self.do_cmd("STARTTLS", success=(220,)) # Don't check for code, do_cmd did it if context is None: context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD) await self.transport.starttls(ssl_context=context) # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. # FIXME: wouldn't it be better to use reset_state here ? # And reset self.reader, self.writer and self.transport just after # Maybe also self.ssl_context ? self.last_ehlo_response = (None, None) self.last_helo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] return (code, message) async def sendmail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while sending message.") >>> else: >>> print("Result: {}.".format(r)) >>> except ConnectionError as e: >>> print(e) Result: {}. Args: sender (str): E-mail address of the sender. recipients (list of str or str): E-mail(s) address(es) of the recipient(s). message (str or bytes): Message body. mail_options (list of str): ESMTP options (such as *8BITMIME*) to send along the *MAIL* command. rcpt_options (list of str): ESMTP options (such as *DSN*) to send along all the *RCPT* commands. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPCommandFailedError: If the server refuses our MAIL command. SMTPCommandFailedError: If the server refuses our DATA command. SMTPNoRecipientError: If the server refuses all given recipients. Returns: dict: A dict containing an entry for each recipient that was refused. Each entry is associated with a (code, message) 2-tuple containing the error code and message, as returned by the server. When everythign runs smoothly, the returning dict is empty. .. note:: The connection remains open after. It's your responsibility to close it. A good practice is to use the asynchronous context manager instead. See :meth:`SMTP.__aenter__` for further details. """ # Make sure `recipients` is a list: if isinstance(recipients, str): recipients = [recipients] # Set some defaults values: if mail_options is None: mail_options = [] if rcpt_options is None: rcpt_options = [] # EHLO or HELO is required: await self.ehlo_or_helo_if_needed() if self.supports_esmtp: if "size" in self.esmtp_extensions: mail_options.append("size={}".format(len(message))) await self.mail(sender, mail_options) errors = [] for recipient in recipients: try: await self.rcpt(recipient, rcpt_options) except SMTPCommandFailedError as e: errors.append(e) if len(recipients) == len(errors): # The server refused all our recipients: raise SMTPNoRecipientError(errors) await self.data(message) # If we got here then somebody got our mail: return errors async def send_mail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Alias for :meth:`SMTP.sendmail`. """ return await self.sendmail( sender, recipients, message, mail_options, rcpt_options ) async def ehlo_or_helo_if_needed(self): """ Calls :meth:`SMTP.ehlo` and/or :meth:`SMTP.helo` if needed. If there hasn't been any previous *EHLO* or *HELO* command this session, tries to initiate the session. *EHLO* is tried first. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. """ no_helo = self.last_helo_response == (None, None) no_ehlo = self.last_ehlo_response == (None, None) if no_helo and no_ehlo: try: # First we try EHLO: await self.ehlo() except SMTPCommandFailedError: # EHLO failed, let's try HELO: await self.helo() async def close(self): """ Cleans up after the connection to the SMTP server has been closed (voluntarily or not). """ if self.writer is not None: # Close the transport: try: self.writer.close() except OSError as exc: if exc.errno != errno.ENOTCONN: raise self.reset_state() async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challenge is hashed using HMAC-MD5 and the user password as key (shared secret) ; 3) The hashed challenge is converted to a string of lowercase hexadecimal digits ; 4) The username and a space character are prepended to the hex digits ; 5) The concatenation is base64-encoded and sent to the server. 6) If the server replies with a return code of 235, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "CRAM-MD5" code, message = await self.do_cmd("AUTH", mechanism, success=(334,)) decoded_challenge = base64.b64decode(message) challenge_hash = hmac.new( key=password.encode("utf-8"), msg=decoded_challenge, digestmod="md5" ) hex_hash = challenge_hash.hexdigest() response = "{} {}".format(username, hex_hash) encoded_response = SMTP.b64enc(response) try: code, message = await self.do_cmd(encoded_response, success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_login(self, username, password): """ Performs an authentication attempt using the LOGIN mechanism. Protocol: 1. The username is base64-encoded ; 2. The string 'AUTH LOGIN' and a space character are prepended to the base64-encoded username and sent to the server ; 3. If the server replies with a 334 return code, we can go on: 1) The password is base64-encoded and sent to the server ; 2) If the server replies with a 235 return code, the user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "LOGIN" code, message = await self.do_cmd( "AUTH", mechanism, SMTP.b64enc(username), success=(334,) ) try: code, message = await self.do_cmd(SMTP.b64enc(password), success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_plain(self, username, password): """ Performs an authentication attempt using the PLAIN mechanism. Protocol: 1. Format the username and password in a suitable way ; 2. The formatted string is base64-encoded ; 3. The string 'AUTH PLAIN' and a space character are prepended to the base64-encoded username and password and sent to the server ; 4. If the server replies with a 235 return code, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "PLAIN" credentials = "\0{}\0{}".format(username, password) encoded_credentials = SMTP.b64enc(credentials) try: code, message = await self.do_cmd( "AUTH", mechanism, encoded_credentials, success=(235, 503) ) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message @staticmethod def parse_esmtp_extensions(message): """ Parses the response given by an ESMTP server after a *EHLO* command. The response is parsed to build: - A dict of supported ESMTP extensions (with parameters, if any). - A list of supported authentication methods. Returns: (dict, list): A (extensions, auth_mechanisms) 2-tuple containing the supported extensions and authentication methods. """ extns = {} auths = [] oldstyle_auth_regex = re.compile(r"auth=(?P<auth>.*)", re.IGNORECASE) extension_regex = re.compile( r"(?P<feature>[a-z0-9][a-z0-9\-]*) ?", re.IGNORECASE ) lines = message.splitlines() for line in lines[1:]: # To be able to communicate with as many SMTP servers as possible, # we have to take the old-style auth advertisement into account. match = oldstyle_auth_regex.match(line) if match: auth = match.group("auth")[0] auth = auth.lower().strip() if auth not in auths: auths.append(auth) # RFC 1869 requires a space between EHLO keyword and parameters. # It's actually stricter, in that only spaces are allowed between # parameters, but were not going to check for that here. # Note that the space isn't present if there are no parameters. match = extension_regex.match(line) if match: feature = match.group("feature").lower() params = match.string[match.end("feature") :].strip() extns[feature] = params if feature == "auth": auths.extend([param.strip().lower() for param in params.split()]) return extns, auths @staticmethod def prepare_message(message): """ Returns the given message encoded in ascii with a format suitable for SMTP transmission: - Makes sure the message is ASCII encoded ; - Normalizes line endings to '\r\n' ; - Adds a (second) period at the beginning of lines that start with a period ; - Makes sure the message ends with '\r\n.\r\n'. For further details, please check out RFC 5321 `§ 4.1.1.4`_ and `§ 4.5.2`_. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 .. _`§ 4.5.2`: https://tools.ietf.org/html/rfc5321#section-4.5.2 """ if isinstance(message, bytes): bytes_message = message else: bytes_message = message.encode("ascii") # The original algorithm uses regexes to do this stuff. # This one is -IMHO- more pythonic and it is slightly faster. # # Another version is even faster, but I chose to keep something # more pythonic and readable. # FYI, the fastest way to do all this stuff seems to be # (according to my benchmarks): # # bytes_message.replace(b"\r\n", b"\n") \ # .replace(b"\r", b"\n") \ # .replace(b"\n", b"\r\n") # # DOT_LINE_REGEX = re.compile(rb"^\.", re.MULTILINE) # bytes_message = DOT_LINE_REGEX.sub(b"..", bytes_message) # # if not bytes_message.endswith(b"\r\n"): # bytes_message += b"\r\n" # # bytes_message += b"\r\n.\r\n" lines = [] for line in bytes_message.splitlines(): if line.startswith(b"."): line = line.replace(b".", b"..", 1) lines.append(line) # Recompose the message with <CRLF> only: bytes_message = b"\r\n".join(lines) # Make sure message ends with <CRLF>.<CRLF>: bytes_message += b"\r\n.\r\n" return bytes_message @staticmethod def b64enc(s): """ Base64-encodes the given string and returns it as a :obj:`str`. This is a simple helper function that takes a str, base64-encodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: s (str): String to be converted to base64. Returns: str: A base64-encoded string. """ return base64.b64encode(s.encode("utf-8")).decode("utf-8") @staticmethod def b64dec(b): """ Base64-decodes the given :obj:`bytes` and converts it to a :obj:`str`. This is a simple helper function that takes a bytes, base64-decodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: b (bytes): A base64-encoded bytes. Returns: str: A base64-decoded string. """ return base64.b64decode(b).decode("utf-8")
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.connect
python
async def connect(self): # First build the reader: self.reader = SMTPStreamReader(loop=self.loop) # Then build the protocol: protocol = asyncio.StreamReaderProtocol(self.reader, loop=self.loop) # With the just-built reader and protocol, create the connection and # get the transport stream: conn = { "protocol_factory": lambda: protocol, "host": self.hostname, "port": self.port, } if self.use_aioopenssl: conn.update( { "use_starttls": not self.ssl_context, "ssl_context_factory": lambda transport: self.ssl_context, "server_hostname": self.hostname, # For SSL } ) import aioopenssl # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await aioopenssl.create_starttls_connection( self.loop, **conn ) # HACK: aioopenssl transports don't implement is_closing, and thus drain() fails... self.transport.is_closing = lambda: False else: conn["ssl"] = self.ssl_context # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await self.loop.create_connection(**conn) # If the connection has been established, build the writer: self.writer = SMTPStreamWriter(self.transport, protocol, self.reader, self.loop) code, message = await self.reader.read_reply() if code != 220: raise ConnectionRefusedError(code, message) return code, message
Connects to the server. .. note:: This method is automatically invoked by :meth:`SMTP.__aenter__`. The code is mostly borrowed from the :func:`asyncio.streams.open_connection` source code. Raises: ConnectionError subclass: If the connection between client and SMTP server can not be established. Returns: (int, str): A (code, message) 2-tuple containing the server response.
train
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L217-L277
[ "async def read_reply(self):\n \"\"\"\n Reads a reply from the server.\n\n Raises:\n ConnectionResetError: If the connection with the server is lost\n (we can't read any response anymore). Or if the server\n replies without a proper return code.\n\n Returns:\n (int, s...
class SMTP: """ SMTP or ESMTP client. This should follow RFC 5321 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP Authentication) and RFC 2487 (Secure SMTP over TLS). Attributes: hostname (str): Hostname of the SMTP server we are connecting to. port (int): Port on which the SMTP server listens for connections. timeout (int): Not used. last_helo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *HELO* response. last_ehlo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *EHLO* response. supports_esmtp (bool): True if the server supports ESMTP (set after a *EHLO* command, False otherwise. esmtp_extensions (dict): ESMTP extensions and parameters supported by the SMTP server (set after a *EHLO* command). auth_mechanisms (list of str): Authentication mechanisms supported by the SMTP server. ssl_context (bool): Always False. (Used in SMTP_SSL subclass) reader (:class:`streams.SMTPStreamReader`): SMTP stream reader, used to read server responses. writer (:class:`streams.SMTPStreamWriter`): SMTP stream writer, used to send commands to the server. transport (:class:`asyncio.BaseTransport`): Communication channel abstraction between client and server. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): If True, the connection is made using the aioopenssl module. Defaults to False. _fqdn (str): Client FQDN. Used to identify the client to the server. Class Attributes: _default_port (int): Default port to use. Defaults to 25. _supported_auth_mechanisms (dict): Dict containing the information about supported authentication mechanisms, ordered by preference of use. The entries consist in : - The authentication mechanism name, in lowercase, as given by SMTP servers. - The name of the method to call to authenticate using the mechanism. """ _default_port = 25 _supported_auth_mechanisms = { "cram-md5": "_auth_cram_md5", "plain": "_auth_plain", "login": "_auth_login", } def __init__( self, hostname="localhost", port=_default_port, fqdn=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, loop=None, use_aioopenssl=False, ): """ Initializes a new :class:`SMTP` instance. Args: hostname (str): Hostname of the SMTP server to connect to. port (int): Port to use to connect to the SMTP server. fqdn (str or None): Client Fully Qualified Domain Name. This is used to identify the client to the server. timeout (int): Not used. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): Use the aioopenssl module to open the connection. This is mandatory if you plan on using STARTTLS. """ self.hostname = hostname try: self.port = int(port) except ValueError: self.port = self.__class__._default_port self.timeout = timeout self._fqdn = fqdn self.loop = loop or asyncio.get_event_loop() self.use_aioopenssl = use_aioopenssl self.reset_state() @property def fqdn(self): """ Returns the string used to identify the client when initiating a SMTP session. RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do: - Use the client FQDN ; - If it isn't available, we SHOULD fall back to an address literal. Returns: str: The value that should be used as the client FQDN. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 .. _`§ 4.1.3`: https//tools.ietf.org/html/rfc5321#section-4.1.3 """ if self._fqdn is None: # Let's try to retrieve it: self._fqdn = socket.getfqdn() if "." not in self._fqdn: try: info = socket.getaddrinfo( host="localhost", port=None, proto=socket.IPPROTO_TCP ) except socket.gaierror: addr = "127.0.0.1" else: # We only consider the first returned result and we're # only interested in getting the IP(v4 or v6) address: addr = info[0][4][0] self._fqdn = "[{}]".format(addr) return self._fqdn def reset_state(self): """ Resets some attributes to their default values. This is especially useful when initializing a newly created :class:`SMTP` instance and when closing an existing SMTP session. It allows us to use the same SMTP instance and connect several times. """ self.last_helo_response = (None, None) self.last_ehlo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] self.ssl_context = False self.reader = None self.writer = None self.transport = None async def __aenter__(self): """ Enters the asynchronous context manager. Also tries to connect to the server. Raises: SMTPConnectionRefusedError: If the connection between client and SMTP server can not be established. .. seealso:: :meth:`SMTP.connect` """ await self.connect() return self async def __aexit__(self, *args): """ Exits the asynchronous context manager. Closes the connection and resets instance attributes. .. seealso:: :meth:`SMTP.quit` """ await self.quit() async def do_cmd(self, *args, success=None): """ Sends the given command to the server. Args: *args: Command and arguments to be sent to the server. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ if success is None: success = (250,) cmd = " ".join(args) await self.writer.send_command(cmd) code, message = await self.reader.read_reply() if code not in success: raise SMTPCommandFailedError(code, message, cmd) return code, message async def helo(self, from_host=None): """ Sends a SMTP 'HELO' command. - Identifies the client and starts the session. If given ``from_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our HELO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("HELO", from_host) self.last_helo_response = (code, message) return code, message async def ehlo(self, from_host=None): """ Sends a SMTP 'EHLO' command. - Identifies the client and starts the session. If given ``from`_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("EHLO", from_host) self.last_ehlo_response = (code, message) extns, auths = SMTP.parse_esmtp_extensions(message) self.esmtp_extensions = extns self.auth_mechanisms = auths self.supports_esmtp = True return code, message async def help(self, command_name=None): """ Sends a SMTP 'HELP' command. For further details please check out `RFC 5321 § 4.1.1.8`_. Args: command_name (str or None, optional): Name of a command for which you want help. For example, if you want to get help about the '*RSET*' command, you'd call ``help('RSET')``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the HELP command fails. Returns: Help text as given by the server. .. _`RFC 5321 § 4.1.1.8`: https://tools.ietf.org/html/rfc5321#section-4.1.1.8 """ if command_name is None: command_name = "" code, message = await self.do_cmd("HELP", command_name) return message async def rset(self): """ Sends a SMTP 'RSET' command. - Resets the session. For further details, please check out `RFC 5321 § 4.1.1.5`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RSET command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.5`: https://tools.ietf.org/html/rfc5321#section-4.1.1.5 """ return await self.do_cmd("RSET") async def noop(self): """ Sends a SMTP 'NOOP' command. - Doesn't do anything. For further details, please check out `RFC 5321 § 4.1.1.9`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the NOOP command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.9`: https://tools.ietf.org/html/rfc5321#section-4.1.1.9 """ return await self.do_cmd("NOOP") async def vrfy(self, address): """ Sends a SMTP 'VRFY' command. - Tests the validity of the given address. For further details, please check out `RFC 5321 § 4.1.1.6`_. Args: address (str): E-mail address to be checked. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the VRFY command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.6`: https://tools.ietf.org/html/rfc5321#section-4.1.1.6 """ return await self.do_cmd("VRFY", address) async def expn(self, address): """ Sends a SMTP 'EXPN' command. - Expands a mailing-list. For further details, please check out `RFC 5321 § 4.1.1.7`_. Args: address (str): E-mail address to expand. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the EXPN command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.7`: https://tools.ietf.org/html/rfc5321#section-4.1.1.7 """ return await self.do_cmd("EXPN", address) async def mail(self, sender, options=None): """ Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] from_addr = "FROM:{}".format(quoteaddr(sender)) code, message = await self.do_cmd("MAIL", from_addr, *options) return code, message async def rcpt(self, recipient, options=None): """ Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. options (list of str or None, optional): Additional options to send along with the *RCPT* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RCPT command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.3`: https://tools.ietf.org/html/rfc5321#section-4.1.1.3 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] to_addr = "TO:{}".format(quoteaddr(recipient)) code, message = await self.do_cmd("RCPT", to_addr, *options) return code, message async def quit(self): """ Sends a SMTP 'QUIT' command. - Ends the session. For further details, please check out `RFC 5321 § 4.1.1.10`_. Returns: (int, str): A (code, message) 2-tuple containing the server response. If the connection is already closed when calling this method, returns (-1, None). .. _`RFC 5321 § 4.1.1.10`: https://tools.ietf.org/html/rfc5321#section-4.1.1.10 """ code = -1 message = None try: code, message = await self.do_cmd("QUIT") except ConnectionError: # We voluntarily ignore this kind of exceptions since... the # connection seems already closed. pass except SMTPCommandFailedError: pass await self.close() return code, message async def data(self, email_message): """ Sends a SMTP 'DATA' command. - Transmits the message to the server. If ``email_message`` is a bytes object, sends it as it is. Else, makes all the required changes so it can be safely trasmitted to the SMTP server.` For further details, please check out `RFC 5321 § 4.1.1.4`_. Args: email_message (str or bytes): Message to be sent. Raises: ConnectionError subclass: If the connection to the server is unexpectedely lost. SMTPCommandFailedError: If the DATA command fails. Returns: (int, str): A (code, message) 2-tuple containing the server last response (the one the server sent after all data were sent by the client). .. seealso: :meth:`SMTP.prepare_message` .. _`RFC 5321 § 4.1.1.4`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 """ code, message = await self.do_cmd("DATA", success=(354,)) email_message = SMTP.prepare_message(email_message) self.writer.write(email_message) # write is non-blocking. await self.writer.drain() # don't forget to drain. code, message = await self.reader.read_reply() return code, message async def auth(self, username, password): """ Tries to authenticate user against the SMTP server. Args: username (str): Username to authenticate with. password (str): Password to use along with the given ``username``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPLoginError: If the authentication failed (either because all attempts failed or because there was no suitable authentication mechanism). Returns: (int, str): A (code, message) 2-tuple containing the last server response. """ # EHLO/HELO is required: await self.ehlo_or_helo_if_needed() errors = [] # To store SMTPAuthenticationErrors code = message = None # Try to authenticate using all mechanisms supported by both # server and client (and only these): for auth, meth in self.__class__._supported_auth_mechanisms.items(): if auth in self.auth_mechanisms: auth_func = getattr(self, meth) try: code, message = await auth_func(username, password) except SMTPAuthenticationError as e: errors.append(e) else: break else: if not errors: err = "Could not find any suitable authentication mechanism." errors.append(SMTPAuthenticationError(-1, err)) raise SMTPLoginError(errors) return code, message async def starttls(self, context=None): """ Upgrades the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports SSL/TLS, this will encrypt the rest of the SMTP session. Raises: SMTPCommandNotSupportedError: If the server does not support STARTTLS. SMTPCommandFailedError: If the STARTTLS command fails BadImplementationError: If the connection does not use aioopenssl. Args: context (:obj:`OpenSSL.SSL.Context`): SSL context Returns: (int, message): A (code, message) 2-tuple containing the server response. """ if not self.use_aioopenssl: raise BadImplementationError("This connection does not use aioopenssl") import aioopenssl import OpenSSL await self.ehlo_or_helo_if_needed() if "starttls" not in self.esmtp_extensions: raise SMTPCommandNotSupportedError("STARTTLS") code, message = await self.do_cmd("STARTTLS", success=(220,)) # Don't check for code, do_cmd did it if context is None: context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD) await self.transport.starttls(ssl_context=context) # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. # FIXME: wouldn't it be better to use reset_state here ? # And reset self.reader, self.writer and self.transport just after # Maybe also self.ssl_context ? self.last_ehlo_response = (None, None) self.last_helo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] return (code, message) async def sendmail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while sending message.") >>> else: >>> print("Result: {}.".format(r)) >>> except ConnectionError as e: >>> print(e) Result: {}. Args: sender (str): E-mail address of the sender. recipients (list of str or str): E-mail(s) address(es) of the recipient(s). message (str or bytes): Message body. mail_options (list of str): ESMTP options (such as *8BITMIME*) to send along the *MAIL* command. rcpt_options (list of str): ESMTP options (such as *DSN*) to send along all the *RCPT* commands. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPCommandFailedError: If the server refuses our MAIL command. SMTPCommandFailedError: If the server refuses our DATA command. SMTPNoRecipientError: If the server refuses all given recipients. Returns: dict: A dict containing an entry for each recipient that was refused. Each entry is associated with a (code, message) 2-tuple containing the error code and message, as returned by the server. When everythign runs smoothly, the returning dict is empty. .. note:: The connection remains open after. It's your responsibility to close it. A good practice is to use the asynchronous context manager instead. See :meth:`SMTP.__aenter__` for further details. """ # Make sure `recipients` is a list: if isinstance(recipients, str): recipients = [recipients] # Set some defaults values: if mail_options is None: mail_options = [] if rcpt_options is None: rcpt_options = [] # EHLO or HELO is required: await self.ehlo_or_helo_if_needed() if self.supports_esmtp: if "size" in self.esmtp_extensions: mail_options.append("size={}".format(len(message))) await self.mail(sender, mail_options) errors = [] for recipient in recipients: try: await self.rcpt(recipient, rcpt_options) except SMTPCommandFailedError as e: errors.append(e) if len(recipients) == len(errors): # The server refused all our recipients: raise SMTPNoRecipientError(errors) await self.data(message) # If we got here then somebody got our mail: return errors async def send_mail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Alias for :meth:`SMTP.sendmail`. """ return await self.sendmail( sender, recipients, message, mail_options, rcpt_options ) async def ehlo_or_helo_if_needed(self): """ Calls :meth:`SMTP.ehlo` and/or :meth:`SMTP.helo` if needed. If there hasn't been any previous *EHLO* or *HELO* command this session, tries to initiate the session. *EHLO* is tried first. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. """ no_helo = self.last_helo_response == (None, None) no_ehlo = self.last_ehlo_response == (None, None) if no_helo and no_ehlo: try: # First we try EHLO: await self.ehlo() except SMTPCommandFailedError: # EHLO failed, let's try HELO: await self.helo() async def close(self): """ Cleans up after the connection to the SMTP server has been closed (voluntarily or not). """ if self.writer is not None: # Close the transport: try: self.writer.close() except OSError as exc: if exc.errno != errno.ENOTCONN: raise self.reset_state() async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challenge is hashed using HMAC-MD5 and the user password as key (shared secret) ; 3) The hashed challenge is converted to a string of lowercase hexadecimal digits ; 4) The username and a space character are prepended to the hex digits ; 5) The concatenation is base64-encoded and sent to the server. 6) If the server replies with a return code of 235, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "CRAM-MD5" code, message = await self.do_cmd("AUTH", mechanism, success=(334,)) decoded_challenge = base64.b64decode(message) challenge_hash = hmac.new( key=password.encode("utf-8"), msg=decoded_challenge, digestmod="md5" ) hex_hash = challenge_hash.hexdigest() response = "{} {}".format(username, hex_hash) encoded_response = SMTP.b64enc(response) try: code, message = await self.do_cmd(encoded_response, success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_login(self, username, password): """ Performs an authentication attempt using the LOGIN mechanism. Protocol: 1. The username is base64-encoded ; 2. The string 'AUTH LOGIN' and a space character are prepended to the base64-encoded username and sent to the server ; 3. If the server replies with a 334 return code, we can go on: 1) The password is base64-encoded and sent to the server ; 2) If the server replies with a 235 return code, the user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "LOGIN" code, message = await self.do_cmd( "AUTH", mechanism, SMTP.b64enc(username), success=(334,) ) try: code, message = await self.do_cmd(SMTP.b64enc(password), success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_plain(self, username, password): """ Performs an authentication attempt using the PLAIN mechanism. Protocol: 1. Format the username and password in a suitable way ; 2. The formatted string is base64-encoded ; 3. The string 'AUTH PLAIN' and a space character are prepended to the base64-encoded username and password and sent to the server ; 4. If the server replies with a 235 return code, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "PLAIN" credentials = "\0{}\0{}".format(username, password) encoded_credentials = SMTP.b64enc(credentials) try: code, message = await self.do_cmd( "AUTH", mechanism, encoded_credentials, success=(235, 503) ) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message @staticmethod def parse_esmtp_extensions(message): """ Parses the response given by an ESMTP server after a *EHLO* command. The response is parsed to build: - A dict of supported ESMTP extensions (with parameters, if any). - A list of supported authentication methods. Returns: (dict, list): A (extensions, auth_mechanisms) 2-tuple containing the supported extensions and authentication methods. """ extns = {} auths = [] oldstyle_auth_regex = re.compile(r"auth=(?P<auth>.*)", re.IGNORECASE) extension_regex = re.compile( r"(?P<feature>[a-z0-9][a-z0-9\-]*) ?", re.IGNORECASE ) lines = message.splitlines() for line in lines[1:]: # To be able to communicate with as many SMTP servers as possible, # we have to take the old-style auth advertisement into account. match = oldstyle_auth_regex.match(line) if match: auth = match.group("auth")[0] auth = auth.lower().strip() if auth not in auths: auths.append(auth) # RFC 1869 requires a space between EHLO keyword and parameters. # It's actually stricter, in that only spaces are allowed between # parameters, but were not going to check for that here. # Note that the space isn't present if there are no parameters. match = extension_regex.match(line) if match: feature = match.group("feature").lower() params = match.string[match.end("feature") :].strip() extns[feature] = params if feature == "auth": auths.extend([param.strip().lower() for param in params.split()]) return extns, auths @staticmethod def prepare_message(message): """ Returns the given message encoded in ascii with a format suitable for SMTP transmission: - Makes sure the message is ASCII encoded ; - Normalizes line endings to '\r\n' ; - Adds a (second) period at the beginning of lines that start with a period ; - Makes sure the message ends with '\r\n.\r\n'. For further details, please check out RFC 5321 `§ 4.1.1.4`_ and `§ 4.5.2`_. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 .. _`§ 4.5.2`: https://tools.ietf.org/html/rfc5321#section-4.5.2 """ if isinstance(message, bytes): bytes_message = message else: bytes_message = message.encode("ascii") # The original algorithm uses regexes to do this stuff. # This one is -IMHO- more pythonic and it is slightly faster. # # Another version is even faster, but I chose to keep something # more pythonic and readable. # FYI, the fastest way to do all this stuff seems to be # (according to my benchmarks): # # bytes_message.replace(b"\r\n", b"\n") \ # .replace(b"\r", b"\n") \ # .replace(b"\n", b"\r\n") # # DOT_LINE_REGEX = re.compile(rb"^\.", re.MULTILINE) # bytes_message = DOT_LINE_REGEX.sub(b"..", bytes_message) # # if not bytes_message.endswith(b"\r\n"): # bytes_message += b"\r\n" # # bytes_message += b"\r\n.\r\n" lines = [] for line in bytes_message.splitlines(): if line.startswith(b"."): line = line.replace(b".", b"..", 1) lines.append(line) # Recompose the message with <CRLF> only: bytes_message = b"\r\n".join(lines) # Make sure message ends with <CRLF>.<CRLF>: bytes_message += b"\r\n.\r\n" return bytes_message @staticmethod def b64enc(s): """ Base64-encodes the given string and returns it as a :obj:`str`. This is a simple helper function that takes a str, base64-encodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: s (str): String to be converted to base64. Returns: str: A base64-encoded string. """ return base64.b64encode(s.encode("utf-8")).decode("utf-8") @staticmethod def b64dec(b): """ Base64-decodes the given :obj:`bytes` and converts it to a :obj:`str`. This is a simple helper function that takes a bytes, base64-decodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: b (bytes): A base64-encoded bytes. Returns: str: A base64-decoded string. """ return base64.b64decode(b).decode("utf-8")
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.do_cmd
python
async def do_cmd(self, *args, success=None): if success is None: success = (250,) cmd = " ".join(args) await self.writer.send_command(cmd) code, message = await self.reader.read_reply() if code not in success: raise SMTPCommandFailedError(code, message, cmd) return code, message
Sends the given command to the server. Args: *args: Command and arguments to be sent to the server. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response.
train
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L279-L306
null
class SMTP: """ SMTP or ESMTP client. This should follow RFC 5321 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP Authentication) and RFC 2487 (Secure SMTP over TLS). Attributes: hostname (str): Hostname of the SMTP server we are connecting to. port (int): Port on which the SMTP server listens for connections. timeout (int): Not used. last_helo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *HELO* response. last_ehlo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *EHLO* response. supports_esmtp (bool): True if the server supports ESMTP (set after a *EHLO* command, False otherwise. esmtp_extensions (dict): ESMTP extensions and parameters supported by the SMTP server (set after a *EHLO* command). auth_mechanisms (list of str): Authentication mechanisms supported by the SMTP server. ssl_context (bool): Always False. (Used in SMTP_SSL subclass) reader (:class:`streams.SMTPStreamReader`): SMTP stream reader, used to read server responses. writer (:class:`streams.SMTPStreamWriter`): SMTP stream writer, used to send commands to the server. transport (:class:`asyncio.BaseTransport`): Communication channel abstraction between client and server. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): If True, the connection is made using the aioopenssl module. Defaults to False. _fqdn (str): Client FQDN. Used to identify the client to the server. Class Attributes: _default_port (int): Default port to use. Defaults to 25. _supported_auth_mechanisms (dict): Dict containing the information about supported authentication mechanisms, ordered by preference of use. The entries consist in : - The authentication mechanism name, in lowercase, as given by SMTP servers. - The name of the method to call to authenticate using the mechanism. """ _default_port = 25 _supported_auth_mechanisms = { "cram-md5": "_auth_cram_md5", "plain": "_auth_plain", "login": "_auth_login", } def __init__( self, hostname="localhost", port=_default_port, fqdn=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, loop=None, use_aioopenssl=False, ): """ Initializes a new :class:`SMTP` instance. Args: hostname (str): Hostname of the SMTP server to connect to. port (int): Port to use to connect to the SMTP server. fqdn (str or None): Client Fully Qualified Domain Name. This is used to identify the client to the server. timeout (int): Not used. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): Use the aioopenssl module to open the connection. This is mandatory if you plan on using STARTTLS. """ self.hostname = hostname try: self.port = int(port) except ValueError: self.port = self.__class__._default_port self.timeout = timeout self._fqdn = fqdn self.loop = loop or asyncio.get_event_loop() self.use_aioopenssl = use_aioopenssl self.reset_state() @property def fqdn(self): """ Returns the string used to identify the client when initiating a SMTP session. RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do: - Use the client FQDN ; - If it isn't available, we SHOULD fall back to an address literal. Returns: str: The value that should be used as the client FQDN. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 .. _`§ 4.1.3`: https//tools.ietf.org/html/rfc5321#section-4.1.3 """ if self._fqdn is None: # Let's try to retrieve it: self._fqdn = socket.getfqdn() if "." not in self._fqdn: try: info = socket.getaddrinfo( host="localhost", port=None, proto=socket.IPPROTO_TCP ) except socket.gaierror: addr = "127.0.0.1" else: # We only consider the first returned result and we're # only interested in getting the IP(v4 or v6) address: addr = info[0][4][0] self._fqdn = "[{}]".format(addr) return self._fqdn def reset_state(self): """ Resets some attributes to their default values. This is especially useful when initializing a newly created :class:`SMTP` instance and when closing an existing SMTP session. It allows us to use the same SMTP instance and connect several times. """ self.last_helo_response = (None, None) self.last_ehlo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] self.ssl_context = False self.reader = None self.writer = None self.transport = None async def __aenter__(self): """ Enters the asynchronous context manager. Also tries to connect to the server. Raises: SMTPConnectionRefusedError: If the connection between client and SMTP server can not be established. .. seealso:: :meth:`SMTP.connect` """ await self.connect() return self async def __aexit__(self, *args): """ Exits the asynchronous context manager. Closes the connection and resets instance attributes. .. seealso:: :meth:`SMTP.quit` """ await self.quit() async def connect(self): """ Connects to the server. .. note:: This method is automatically invoked by :meth:`SMTP.__aenter__`. The code is mostly borrowed from the :func:`asyncio.streams.open_connection` source code. Raises: ConnectionError subclass: If the connection between client and SMTP server can not be established. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ # First build the reader: self.reader = SMTPStreamReader(loop=self.loop) # Then build the protocol: protocol = asyncio.StreamReaderProtocol(self.reader, loop=self.loop) # With the just-built reader and protocol, create the connection and # get the transport stream: conn = { "protocol_factory": lambda: protocol, "host": self.hostname, "port": self.port, } if self.use_aioopenssl: conn.update( { "use_starttls": not self.ssl_context, "ssl_context_factory": lambda transport: self.ssl_context, "server_hostname": self.hostname, # For SSL } ) import aioopenssl # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await aioopenssl.create_starttls_connection( self.loop, **conn ) # HACK: aioopenssl transports don't implement is_closing, and thus drain() fails... self.transport.is_closing = lambda: False else: conn["ssl"] = self.ssl_context # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await self.loop.create_connection(**conn) # If the connection has been established, build the writer: self.writer = SMTPStreamWriter(self.transport, protocol, self.reader, self.loop) code, message = await self.reader.read_reply() if code != 220: raise ConnectionRefusedError(code, message) return code, message async def helo(self, from_host=None): """ Sends a SMTP 'HELO' command. - Identifies the client and starts the session. If given ``from_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our HELO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("HELO", from_host) self.last_helo_response = (code, message) return code, message async def ehlo(self, from_host=None): """ Sends a SMTP 'EHLO' command. - Identifies the client and starts the session. If given ``from`_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("EHLO", from_host) self.last_ehlo_response = (code, message) extns, auths = SMTP.parse_esmtp_extensions(message) self.esmtp_extensions = extns self.auth_mechanisms = auths self.supports_esmtp = True return code, message async def help(self, command_name=None): """ Sends a SMTP 'HELP' command. For further details please check out `RFC 5321 § 4.1.1.8`_. Args: command_name (str or None, optional): Name of a command for which you want help. For example, if you want to get help about the '*RSET*' command, you'd call ``help('RSET')``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the HELP command fails. Returns: Help text as given by the server. .. _`RFC 5321 § 4.1.1.8`: https://tools.ietf.org/html/rfc5321#section-4.1.1.8 """ if command_name is None: command_name = "" code, message = await self.do_cmd("HELP", command_name) return message async def rset(self): """ Sends a SMTP 'RSET' command. - Resets the session. For further details, please check out `RFC 5321 § 4.1.1.5`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RSET command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.5`: https://tools.ietf.org/html/rfc5321#section-4.1.1.5 """ return await self.do_cmd("RSET") async def noop(self): """ Sends a SMTP 'NOOP' command. - Doesn't do anything. For further details, please check out `RFC 5321 § 4.1.1.9`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the NOOP command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.9`: https://tools.ietf.org/html/rfc5321#section-4.1.1.9 """ return await self.do_cmd("NOOP") async def vrfy(self, address): """ Sends a SMTP 'VRFY' command. - Tests the validity of the given address. For further details, please check out `RFC 5321 § 4.1.1.6`_. Args: address (str): E-mail address to be checked. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the VRFY command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.6`: https://tools.ietf.org/html/rfc5321#section-4.1.1.6 """ return await self.do_cmd("VRFY", address) async def expn(self, address): """ Sends a SMTP 'EXPN' command. - Expands a mailing-list. For further details, please check out `RFC 5321 § 4.1.1.7`_. Args: address (str): E-mail address to expand. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the EXPN command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.7`: https://tools.ietf.org/html/rfc5321#section-4.1.1.7 """ return await self.do_cmd("EXPN", address) async def mail(self, sender, options=None): """ Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] from_addr = "FROM:{}".format(quoteaddr(sender)) code, message = await self.do_cmd("MAIL", from_addr, *options) return code, message async def rcpt(self, recipient, options=None): """ Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. options (list of str or None, optional): Additional options to send along with the *RCPT* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RCPT command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.3`: https://tools.ietf.org/html/rfc5321#section-4.1.1.3 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] to_addr = "TO:{}".format(quoteaddr(recipient)) code, message = await self.do_cmd("RCPT", to_addr, *options) return code, message async def quit(self): """ Sends a SMTP 'QUIT' command. - Ends the session. For further details, please check out `RFC 5321 § 4.1.1.10`_. Returns: (int, str): A (code, message) 2-tuple containing the server response. If the connection is already closed when calling this method, returns (-1, None). .. _`RFC 5321 § 4.1.1.10`: https://tools.ietf.org/html/rfc5321#section-4.1.1.10 """ code = -1 message = None try: code, message = await self.do_cmd("QUIT") except ConnectionError: # We voluntarily ignore this kind of exceptions since... the # connection seems already closed. pass except SMTPCommandFailedError: pass await self.close() return code, message async def data(self, email_message): """ Sends a SMTP 'DATA' command. - Transmits the message to the server. If ``email_message`` is a bytes object, sends it as it is. Else, makes all the required changes so it can be safely trasmitted to the SMTP server.` For further details, please check out `RFC 5321 § 4.1.1.4`_. Args: email_message (str or bytes): Message to be sent. Raises: ConnectionError subclass: If the connection to the server is unexpectedely lost. SMTPCommandFailedError: If the DATA command fails. Returns: (int, str): A (code, message) 2-tuple containing the server last response (the one the server sent after all data were sent by the client). .. seealso: :meth:`SMTP.prepare_message` .. _`RFC 5321 § 4.1.1.4`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 """ code, message = await self.do_cmd("DATA", success=(354,)) email_message = SMTP.prepare_message(email_message) self.writer.write(email_message) # write is non-blocking. await self.writer.drain() # don't forget to drain. code, message = await self.reader.read_reply() return code, message async def auth(self, username, password): """ Tries to authenticate user against the SMTP server. Args: username (str): Username to authenticate with. password (str): Password to use along with the given ``username``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPLoginError: If the authentication failed (either because all attempts failed or because there was no suitable authentication mechanism). Returns: (int, str): A (code, message) 2-tuple containing the last server response. """ # EHLO/HELO is required: await self.ehlo_or_helo_if_needed() errors = [] # To store SMTPAuthenticationErrors code = message = None # Try to authenticate using all mechanisms supported by both # server and client (and only these): for auth, meth in self.__class__._supported_auth_mechanisms.items(): if auth in self.auth_mechanisms: auth_func = getattr(self, meth) try: code, message = await auth_func(username, password) except SMTPAuthenticationError as e: errors.append(e) else: break else: if not errors: err = "Could not find any suitable authentication mechanism." errors.append(SMTPAuthenticationError(-1, err)) raise SMTPLoginError(errors) return code, message async def starttls(self, context=None): """ Upgrades the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports SSL/TLS, this will encrypt the rest of the SMTP session. Raises: SMTPCommandNotSupportedError: If the server does not support STARTTLS. SMTPCommandFailedError: If the STARTTLS command fails BadImplementationError: If the connection does not use aioopenssl. Args: context (:obj:`OpenSSL.SSL.Context`): SSL context Returns: (int, message): A (code, message) 2-tuple containing the server response. """ if not self.use_aioopenssl: raise BadImplementationError("This connection does not use aioopenssl") import aioopenssl import OpenSSL await self.ehlo_or_helo_if_needed() if "starttls" not in self.esmtp_extensions: raise SMTPCommandNotSupportedError("STARTTLS") code, message = await self.do_cmd("STARTTLS", success=(220,)) # Don't check for code, do_cmd did it if context is None: context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD) await self.transport.starttls(ssl_context=context) # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. # FIXME: wouldn't it be better to use reset_state here ? # And reset self.reader, self.writer and self.transport just after # Maybe also self.ssl_context ? self.last_ehlo_response = (None, None) self.last_helo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] return (code, message) async def sendmail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while sending message.") >>> else: >>> print("Result: {}.".format(r)) >>> except ConnectionError as e: >>> print(e) Result: {}. Args: sender (str): E-mail address of the sender. recipients (list of str or str): E-mail(s) address(es) of the recipient(s). message (str or bytes): Message body. mail_options (list of str): ESMTP options (such as *8BITMIME*) to send along the *MAIL* command. rcpt_options (list of str): ESMTP options (such as *DSN*) to send along all the *RCPT* commands. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPCommandFailedError: If the server refuses our MAIL command. SMTPCommandFailedError: If the server refuses our DATA command. SMTPNoRecipientError: If the server refuses all given recipients. Returns: dict: A dict containing an entry for each recipient that was refused. Each entry is associated with a (code, message) 2-tuple containing the error code and message, as returned by the server. When everythign runs smoothly, the returning dict is empty. .. note:: The connection remains open after. It's your responsibility to close it. A good practice is to use the asynchronous context manager instead. See :meth:`SMTP.__aenter__` for further details. """ # Make sure `recipients` is a list: if isinstance(recipients, str): recipients = [recipients] # Set some defaults values: if mail_options is None: mail_options = [] if rcpt_options is None: rcpt_options = [] # EHLO or HELO is required: await self.ehlo_or_helo_if_needed() if self.supports_esmtp: if "size" in self.esmtp_extensions: mail_options.append("size={}".format(len(message))) await self.mail(sender, mail_options) errors = [] for recipient in recipients: try: await self.rcpt(recipient, rcpt_options) except SMTPCommandFailedError as e: errors.append(e) if len(recipients) == len(errors): # The server refused all our recipients: raise SMTPNoRecipientError(errors) await self.data(message) # If we got here then somebody got our mail: return errors async def send_mail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Alias for :meth:`SMTP.sendmail`. """ return await self.sendmail( sender, recipients, message, mail_options, rcpt_options ) async def ehlo_or_helo_if_needed(self): """ Calls :meth:`SMTP.ehlo` and/or :meth:`SMTP.helo` if needed. If there hasn't been any previous *EHLO* or *HELO* command this session, tries to initiate the session. *EHLO* is tried first. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. """ no_helo = self.last_helo_response == (None, None) no_ehlo = self.last_ehlo_response == (None, None) if no_helo and no_ehlo: try: # First we try EHLO: await self.ehlo() except SMTPCommandFailedError: # EHLO failed, let's try HELO: await self.helo() async def close(self): """ Cleans up after the connection to the SMTP server has been closed (voluntarily or not). """ if self.writer is not None: # Close the transport: try: self.writer.close() except OSError as exc: if exc.errno != errno.ENOTCONN: raise self.reset_state() async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challenge is hashed using HMAC-MD5 and the user password as key (shared secret) ; 3) The hashed challenge is converted to a string of lowercase hexadecimal digits ; 4) The username and a space character are prepended to the hex digits ; 5) The concatenation is base64-encoded and sent to the server. 6) If the server replies with a return code of 235, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "CRAM-MD5" code, message = await self.do_cmd("AUTH", mechanism, success=(334,)) decoded_challenge = base64.b64decode(message) challenge_hash = hmac.new( key=password.encode("utf-8"), msg=decoded_challenge, digestmod="md5" ) hex_hash = challenge_hash.hexdigest() response = "{} {}".format(username, hex_hash) encoded_response = SMTP.b64enc(response) try: code, message = await self.do_cmd(encoded_response, success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_login(self, username, password): """ Performs an authentication attempt using the LOGIN mechanism. Protocol: 1. The username is base64-encoded ; 2. The string 'AUTH LOGIN' and a space character are prepended to the base64-encoded username and sent to the server ; 3. If the server replies with a 334 return code, we can go on: 1) The password is base64-encoded and sent to the server ; 2) If the server replies with a 235 return code, the user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "LOGIN" code, message = await self.do_cmd( "AUTH", mechanism, SMTP.b64enc(username), success=(334,) ) try: code, message = await self.do_cmd(SMTP.b64enc(password), success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_plain(self, username, password): """ Performs an authentication attempt using the PLAIN mechanism. Protocol: 1. Format the username and password in a suitable way ; 2. The formatted string is base64-encoded ; 3. The string 'AUTH PLAIN' and a space character are prepended to the base64-encoded username and password and sent to the server ; 4. If the server replies with a 235 return code, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "PLAIN" credentials = "\0{}\0{}".format(username, password) encoded_credentials = SMTP.b64enc(credentials) try: code, message = await self.do_cmd( "AUTH", mechanism, encoded_credentials, success=(235, 503) ) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message @staticmethod def parse_esmtp_extensions(message): """ Parses the response given by an ESMTP server after a *EHLO* command. The response is parsed to build: - A dict of supported ESMTP extensions (with parameters, if any). - A list of supported authentication methods. Returns: (dict, list): A (extensions, auth_mechanisms) 2-tuple containing the supported extensions and authentication methods. """ extns = {} auths = [] oldstyle_auth_regex = re.compile(r"auth=(?P<auth>.*)", re.IGNORECASE) extension_regex = re.compile( r"(?P<feature>[a-z0-9][a-z0-9\-]*) ?", re.IGNORECASE ) lines = message.splitlines() for line in lines[1:]: # To be able to communicate with as many SMTP servers as possible, # we have to take the old-style auth advertisement into account. match = oldstyle_auth_regex.match(line) if match: auth = match.group("auth")[0] auth = auth.lower().strip() if auth not in auths: auths.append(auth) # RFC 1869 requires a space between EHLO keyword and parameters. # It's actually stricter, in that only spaces are allowed between # parameters, but were not going to check for that here. # Note that the space isn't present if there are no parameters. match = extension_regex.match(line) if match: feature = match.group("feature").lower() params = match.string[match.end("feature") :].strip() extns[feature] = params if feature == "auth": auths.extend([param.strip().lower() for param in params.split()]) return extns, auths @staticmethod def prepare_message(message): """ Returns the given message encoded in ascii with a format suitable for SMTP transmission: - Makes sure the message is ASCII encoded ; - Normalizes line endings to '\r\n' ; - Adds a (second) period at the beginning of lines that start with a period ; - Makes sure the message ends with '\r\n.\r\n'. For further details, please check out RFC 5321 `§ 4.1.1.4`_ and `§ 4.5.2`_. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 .. _`§ 4.5.2`: https://tools.ietf.org/html/rfc5321#section-4.5.2 """ if isinstance(message, bytes): bytes_message = message else: bytes_message = message.encode("ascii") # The original algorithm uses regexes to do this stuff. # This one is -IMHO- more pythonic and it is slightly faster. # # Another version is even faster, but I chose to keep something # more pythonic and readable. # FYI, the fastest way to do all this stuff seems to be # (according to my benchmarks): # # bytes_message.replace(b"\r\n", b"\n") \ # .replace(b"\r", b"\n") \ # .replace(b"\n", b"\r\n") # # DOT_LINE_REGEX = re.compile(rb"^\.", re.MULTILINE) # bytes_message = DOT_LINE_REGEX.sub(b"..", bytes_message) # # if not bytes_message.endswith(b"\r\n"): # bytes_message += b"\r\n" # # bytes_message += b"\r\n.\r\n" lines = [] for line in bytes_message.splitlines(): if line.startswith(b"."): line = line.replace(b".", b"..", 1) lines.append(line) # Recompose the message with <CRLF> only: bytes_message = b"\r\n".join(lines) # Make sure message ends with <CRLF>.<CRLF>: bytes_message += b"\r\n.\r\n" return bytes_message @staticmethod def b64enc(s): """ Base64-encodes the given string and returns it as a :obj:`str`. This is a simple helper function that takes a str, base64-encodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: s (str): String to be converted to base64. Returns: str: A base64-encoded string. """ return base64.b64encode(s.encode("utf-8")).decode("utf-8") @staticmethod def b64dec(b): """ Base64-decodes the given :obj:`bytes` and converts it to a :obj:`str`. This is a simple helper function that takes a bytes, base64-decodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: b (bytes): A base64-encoded bytes. Returns: str: A base64-decoded string. """ return base64.b64decode(b).decode("utf-8")
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.helo
python
async def helo(self, from_host=None): if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("HELO", from_host) self.last_helo_response = (code, message) return code, message
Sends a SMTP 'HELO' command. - Identifies the client and starts the session. If given ``from_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our HELO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1
train
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L308-L338
[ "async def do_cmd(self, *args, success=None):\n \"\"\"\n Sends the given command to the server.\n\n Args:\n *args: Command and arguments to be sent to the server.\n\n Raises:\n ConnectionResetError: If the connection with the server is\n unexpectedely lost.\n SMTPCommandF...
class SMTP: """ SMTP or ESMTP client. This should follow RFC 5321 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP Authentication) and RFC 2487 (Secure SMTP over TLS). Attributes: hostname (str): Hostname of the SMTP server we are connecting to. port (int): Port on which the SMTP server listens for connections. timeout (int): Not used. last_helo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *HELO* response. last_ehlo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *EHLO* response. supports_esmtp (bool): True if the server supports ESMTP (set after a *EHLO* command, False otherwise. esmtp_extensions (dict): ESMTP extensions and parameters supported by the SMTP server (set after a *EHLO* command). auth_mechanisms (list of str): Authentication mechanisms supported by the SMTP server. ssl_context (bool): Always False. (Used in SMTP_SSL subclass) reader (:class:`streams.SMTPStreamReader`): SMTP stream reader, used to read server responses. writer (:class:`streams.SMTPStreamWriter`): SMTP stream writer, used to send commands to the server. transport (:class:`asyncio.BaseTransport`): Communication channel abstraction between client and server. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): If True, the connection is made using the aioopenssl module. Defaults to False. _fqdn (str): Client FQDN. Used to identify the client to the server. Class Attributes: _default_port (int): Default port to use. Defaults to 25. _supported_auth_mechanisms (dict): Dict containing the information about supported authentication mechanisms, ordered by preference of use. The entries consist in : - The authentication mechanism name, in lowercase, as given by SMTP servers. - The name of the method to call to authenticate using the mechanism. """ _default_port = 25 _supported_auth_mechanisms = { "cram-md5": "_auth_cram_md5", "plain": "_auth_plain", "login": "_auth_login", } def __init__( self, hostname="localhost", port=_default_port, fqdn=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, loop=None, use_aioopenssl=False, ): """ Initializes a new :class:`SMTP` instance. Args: hostname (str): Hostname of the SMTP server to connect to. port (int): Port to use to connect to the SMTP server. fqdn (str or None): Client Fully Qualified Domain Name. This is used to identify the client to the server. timeout (int): Not used. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): Use the aioopenssl module to open the connection. This is mandatory if you plan on using STARTTLS. """ self.hostname = hostname try: self.port = int(port) except ValueError: self.port = self.__class__._default_port self.timeout = timeout self._fqdn = fqdn self.loop = loop or asyncio.get_event_loop() self.use_aioopenssl = use_aioopenssl self.reset_state() @property def fqdn(self): """ Returns the string used to identify the client when initiating a SMTP session. RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do: - Use the client FQDN ; - If it isn't available, we SHOULD fall back to an address literal. Returns: str: The value that should be used as the client FQDN. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 .. _`§ 4.1.3`: https//tools.ietf.org/html/rfc5321#section-4.1.3 """ if self._fqdn is None: # Let's try to retrieve it: self._fqdn = socket.getfqdn() if "." not in self._fqdn: try: info = socket.getaddrinfo( host="localhost", port=None, proto=socket.IPPROTO_TCP ) except socket.gaierror: addr = "127.0.0.1" else: # We only consider the first returned result and we're # only interested in getting the IP(v4 or v6) address: addr = info[0][4][0] self._fqdn = "[{}]".format(addr) return self._fqdn def reset_state(self): """ Resets some attributes to their default values. This is especially useful when initializing a newly created :class:`SMTP` instance and when closing an existing SMTP session. It allows us to use the same SMTP instance and connect several times. """ self.last_helo_response = (None, None) self.last_ehlo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] self.ssl_context = False self.reader = None self.writer = None self.transport = None async def __aenter__(self): """ Enters the asynchronous context manager. Also tries to connect to the server. Raises: SMTPConnectionRefusedError: If the connection between client and SMTP server can not be established. .. seealso:: :meth:`SMTP.connect` """ await self.connect() return self async def __aexit__(self, *args): """ Exits the asynchronous context manager. Closes the connection and resets instance attributes. .. seealso:: :meth:`SMTP.quit` """ await self.quit() async def connect(self): """ Connects to the server. .. note:: This method is automatically invoked by :meth:`SMTP.__aenter__`. The code is mostly borrowed from the :func:`asyncio.streams.open_connection` source code. Raises: ConnectionError subclass: If the connection between client and SMTP server can not be established. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ # First build the reader: self.reader = SMTPStreamReader(loop=self.loop) # Then build the protocol: protocol = asyncio.StreamReaderProtocol(self.reader, loop=self.loop) # With the just-built reader and protocol, create the connection and # get the transport stream: conn = { "protocol_factory": lambda: protocol, "host": self.hostname, "port": self.port, } if self.use_aioopenssl: conn.update( { "use_starttls": not self.ssl_context, "ssl_context_factory": lambda transport: self.ssl_context, "server_hostname": self.hostname, # For SSL } ) import aioopenssl # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await aioopenssl.create_starttls_connection( self.loop, **conn ) # HACK: aioopenssl transports don't implement is_closing, and thus drain() fails... self.transport.is_closing = lambda: False else: conn["ssl"] = self.ssl_context # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await self.loop.create_connection(**conn) # If the connection has been established, build the writer: self.writer = SMTPStreamWriter(self.transport, protocol, self.reader, self.loop) code, message = await self.reader.read_reply() if code != 220: raise ConnectionRefusedError(code, message) return code, message async def do_cmd(self, *args, success=None): """ Sends the given command to the server. Args: *args: Command and arguments to be sent to the server. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ if success is None: success = (250,) cmd = " ".join(args) await self.writer.send_command(cmd) code, message = await self.reader.read_reply() if code not in success: raise SMTPCommandFailedError(code, message, cmd) return code, message async def ehlo(self, from_host=None): """ Sends a SMTP 'EHLO' command. - Identifies the client and starts the session. If given ``from`_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("EHLO", from_host) self.last_ehlo_response = (code, message) extns, auths = SMTP.parse_esmtp_extensions(message) self.esmtp_extensions = extns self.auth_mechanisms = auths self.supports_esmtp = True return code, message async def help(self, command_name=None): """ Sends a SMTP 'HELP' command. For further details please check out `RFC 5321 § 4.1.1.8`_. Args: command_name (str or None, optional): Name of a command for which you want help. For example, if you want to get help about the '*RSET*' command, you'd call ``help('RSET')``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the HELP command fails. Returns: Help text as given by the server. .. _`RFC 5321 § 4.1.1.8`: https://tools.ietf.org/html/rfc5321#section-4.1.1.8 """ if command_name is None: command_name = "" code, message = await self.do_cmd("HELP", command_name) return message async def rset(self): """ Sends a SMTP 'RSET' command. - Resets the session. For further details, please check out `RFC 5321 § 4.1.1.5`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RSET command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.5`: https://tools.ietf.org/html/rfc5321#section-4.1.1.5 """ return await self.do_cmd("RSET") async def noop(self): """ Sends a SMTP 'NOOP' command. - Doesn't do anything. For further details, please check out `RFC 5321 § 4.1.1.9`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the NOOP command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.9`: https://tools.ietf.org/html/rfc5321#section-4.1.1.9 """ return await self.do_cmd("NOOP") async def vrfy(self, address): """ Sends a SMTP 'VRFY' command. - Tests the validity of the given address. For further details, please check out `RFC 5321 § 4.1.1.6`_. Args: address (str): E-mail address to be checked. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the VRFY command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.6`: https://tools.ietf.org/html/rfc5321#section-4.1.1.6 """ return await self.do_cmd("VRFY", address) async def expn(self, address): """ Sends a SMTP 'EXPN' command. - Expands a mailing-list. For further details, please check out `RFC 5321 § 4.1.1.7`_. Args: address (str): E-mail address to expand. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the EXPN command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.7`: https://tools.ietf.org/html/rfc5321#section-4.1.1.7 """ return await self.do_cmd("EXPN", address) async def mail(self, sender, options=None): """ Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] from_addr = "FROM:{}".format(quoteaddr(sender)) code, message = await self.do_cmd("MAIL", from_addr, *options) return code, message async def rcpt(self, recipient, options=None): """ Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. options (list of str or None, optional): Additional options to send along with the *RCPT* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RCPT command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.3`: https://tools.ietf.org/html/rfc5321#section-4.1.1.3 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] to_addr = "TO:{}".format(quoteaddr(recipient)) code, message = await self.do_cmd("RCPT", to_addr, *options) return code, message async def quit(self): """ Sends a SMTP 'QUIT' command. - Ends the session. For further details, please check out `RFC 5321 § 4.1.1.10`_. Returns: (int, str): A (code, message) 2-tuple containing the server response. If the connection is already closed when calling this method, returns (-1, None). .. _`RFC 5321 § 4.1.1.10`: https://tools.ietf.org/html/rfc5321#section-4.1.1.10 """ code = -1 message = None try: code, message = await self.do_cmd("QUIT") except ConnectionError: # We voluntarily ignore this kind of exceptions since... the # connection seems already closed. pass except SMTPCommandFailedError: pass await self.close() return code, message async def data(self, email_message): """ Sends a SMTP 'DATA' command. - Transmits the message to the server. If ``email_message`` is a bytes object, sends it as it is. Else, makes all the required changes so it can be safely trasmitted to the SMTP server.` For further details, please check out `RFC 5321 § 4.1.1.4`_. Args: email_message (str or bytes): Message to be sent. Raises: ConnectionError subclass: If the connection to the server is unexpectedely lost. SMTPCommandFailedError: If the DATA command fails. Returns: (int, str): A (code, message) 2-tuple containing the server last response (the one the server sent after all data were sent by the client). .. seealso: :meth:`SMTP.prepare_message` .. _`RFC 5321 § 4.1.1.4`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 """ code, message = await self.do_cmd("DATA", success=(354,)) email_message = SMTP.prepare_message(email_message) self.writer.write(email_message) # write is non-blocking. await self.writer.drain() # don't forget to drain. code, message = await self.reader.read_reply() return code, message async def auth(self, username, password): """ Tries to authenticate user against the SMTP server. Args: username (str): Username to authenticate with. password (str): Password to use along with the given ``username``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPLoginError: If the authentication failed (either because all attempts failed or because there was no suitable authentication mechanism). Returns: (int, str): A (code, message) 2-tuple containing the last server response. """ # EHLO/HELO is required: await self.ehlo_or_helo_if_needed() errors = [] # To store SMTPAuthenticationErrors code = message = None # Try to authenticate using all mechanisms supported by both # server and client (and only these): for auth, meth in self.__class__._supported_auth_mechanisms.items(): if auth in self.auth_mechanisms: auth_func = getattr(self, meth) try: code, message = await auth_func(username, password) except SMTPAuthenticationError as e: errors.append(e) else: break else: if not errors: err = "Could not find any suitable authentication mechanism." errors.append(SMTPAuthenticationError(-1, err)) raise SMTPLoginError(errors) return code, message async def starttls(self, context=None): """ Upgrades the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports SSL/TLS, this will encrypt the rest of the SMTP session. Raises: SMTPCommandNotSupportedError: If the server does not support STARTTLS. SMTPCommandFailedError: If the STARTTLS command fails BadImplementationError: If the connection does not use aioopenssl. Args: context (:obj:`OpenSSL.SSL.Context`): SSL context Returns: (int, message): A (code, message) 2-tuple containing the server response. """ if not self.use_aioopenssl: raise BadImplementationError("This connection does not use aioopenssl") import aioopenssl import OpenSSL await self.ehlo_or_helo_if_needed() if "starttls" not in self.esmtp_extensions: raise SMTPCommandNotSupportedError("STARTTLS") code, message = await self.do_cmd("STARTTLS", success=(220,)) # Don't check for code, do_cmd did it if context is None: context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD) await self.transport.starttls(ssl_context=context) # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. # FIXME: wouldn't it be better to use reset_state here ? # And reset self.reader, self.writer and self.transport just after # Maybe also self.ssl_context ? self.last_ehlo_response = (None, None) self.last_helo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] return (code, message) async def sendmail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while sending message.") >>> else: >>> print("Result: {}.".format(r)) >>> except ConnectionError as e: >>> print(e) Result: {}. Args: sender (str): E-mail address of the sender. recipients (list of str or str): E-mail(s) address(es) of the recipient(s). message (str or bytes): Message body. mail_options (list of str): ESMTP options (such as *8BITMIME*) to send along the *MAIL* command. rcpt_options (list of str): ESMTP options (such as *DSN*) to send along all the *RCPT* commands. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPCommandFailedError: If the server refuses our MAIL command. SMTPCommandFailedError: If the server refuses our DATA command. SMTPNoRecipientError: If the server refuses all given recipients. Returns: dict: A dict containing an entry for each recipient that was refused. Each entry is associated with a (code, message) 2-tuple containing the error code and message, as returned by the server. When everythign runs smoothly, the returning dict is empty. .. note:: The connection remains open after. It's your responsibility to close it. A good practice is to use the asynchronous context manager instead. See :meth:`SMTP.__aenter__` for further details. """ # Make sure `recipients` is a list: if isinstance(recipients, str): recipients = [recipients] # Set some defaults values: if mail_options is None: mail_options = [] if rcpt_options is None: rcpt_options = [] # EHLO or HELO is required: await self.ehlo_or_helo_if_needed() if self.supports_esmtp: if "size" in self.esmtp_extensions: mail_options.append("size={}".format(len(message))) await self.mail(sender, mail_options) errors = [] for recipient in recipients: try: await self.rcpt(recipient, rcpt_options) except SMTPCommandFailedError as e: errors.append(e) if len(recipients) == len(errors): # The server refused all our recipients: raise SMTPNoRecipientError(errors) await self.data(message) # If we got here then somebody got our mail: return errors async def send_mail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Alias for :meth:`SMTP.sendmail`. """ return await self.sendmail( sender, recipients, message, mail_options, rcpt_options ) async def ehlo_or_helo_if_needed(self): """ Calls :meth:`SMTP.ehlo` and/or :meth:`SMTP.helo` if needed. If there hasn't been any previous *EHLO* or *HELO* command this session, tries to initiate the session. *EHLO* is tried first. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. """ no_helo = self.last_helo_response == (None, None) no_ehlo = self.last_ehlo_response == (None, None) if no_helo and no_ehlo: try: # First we try EHLO: await self.ehlo() except SMTPCommandFailedError: # EHLO failed, let's try HELO: await self.helo() async def close(self): """ Cleans up after the connection to the SMTP server has been closed (voluntarily or not). """ if self.writer is not None: # Close the transport: try: self.writer.close() except OSError as exc: if exc.errno != errno.ENOTCONN: raise self.reset_state() async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challenge is hashed using HMAC-MD5 and the user password as key (shared secret) ; 3) The hashed challenge is converted to a string of lowercase hexadecimal digits ; 4) The username and a space character are prepended to the hex digits ; 5) The concatenation is base64-encoded and sent to the server. 6) If the server replies with a return code of 235, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "CRAM-MD5" code, message = await self.do_cmd("AUTH", mechanism, success=(334,)) decoded_challenge = base64.b64decode(message) challenge_hash = hmac.new( key=password.encode("utf-8"), msg=decoded_challenge, digestmod="md5" ) hex_hash = challenge_hash.hexdigest() response = "{} {}".format(username, hex_hash) encoded_response = SMTP.b64enc(response) try: code, message = await self.do_cmd(encoded_response, success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_login(self, username, password): """ Performs an authentication attempt using the LOGIN mechanism. Protocol: 1. The username is base64-encoded ; 2. The string 'AUTH LOGIN' and a space character are prepended to the base64-encoded username and sent to the server ; 3. If the server replies with a 334 return code, we can go on: 1) The password is base64-encoded and sent to the server ; 2) If the server replies with a 235 return code, the user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "LOGIN" code, message = await self.do_cmd( "AUTH", mechanism, SMTP.b64enc(username), success=(334,) ) try: code, message = await self.do_cmd(SMTP.b64enc(password), success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_plain(self, username, password): """ Performs an authentication attempt using the PLAIN mechanism. Protocol: 1. Format the username and password in a suitable way ; 2. The formatted string is base64-encoded ; 3. The string 'AUTH PLAIN' and a space character are prepended to the base64-encoded username and password and sent to the server ; 4. If the server replies with a 235 return code, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "PLAIN" credentials = "\0{}\0{}".format(username, password) encoded_credentials = SMTP.b64enc(credentials) try: code, message = await self.do_cmd( "AUTH", mechanism, encoded_credentials, success=(235, 503) ) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message @staticmethod def parse_esmtp_extensions(message): """ Parses the response given by an ESMTP server after a *EHLO* command. The response is parsed to build: - A dict of supported ESMTP extensions (with parameters, if any). - A list of supported authentication methods. Returns: (dict, list): A (extensions, auth_mechanisms) 2-tuple containing the supported extensions and authentication methods. """ extns = {} auths = [] oldstyle_auth_regex = re.compile(r"auth=(?P<auth>.*)", re.IGNORECASE) extension_regex = re.compile( r"(?P<feature>[a-z0-9][a-z0-9\-]*) ?", re.IGNORECASE ) lines = message.splitlines() for line in lines[1:]: # To be able to communicate with as many SMTP servers as possible, # we have to take the old-style auth advertisement into account. match = oldstyle_auth_regex.match(line) if match: auth = match.group("auth")[0] auth = auth.lower().strip() if auth not in auths: auths.append(auth) # RFC 1869 requires a space between EHLO keyword and parameters. # It's actually stricter, in that only spaces are allowed between # parameters, but were not going to check for that here. # Note that the space isn't present if there are no parameters. match = extension_regex.match(line) if match: feature = match.group("feature").lower() params = match.string[match.end("feature") :].strip() extns[feature] = params if feature == "auth": auths.extend([param.strip().lower() for param in params.split()]) return extns, auths @staticmethod def prepare_message(message): """ Returns the given message encoded in ascii with a format suitable for SMTP transmission: - Makes sure the message is ASCII encoded ; - Normalizes line endings to '\r\n' ; - Adds a (second) period at the beginning of lines that start with a period ; - Makes sure the message ends with '\r\n.\r\n'. For further details, please check out RFC 5321 `§ 4.1.1.4`_ and `§ 4.5.2`_. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 .. _`§ 4.5.2`: https://tools.ietf.org/html/rfc5321#section-4.5.2 """ if isinstance(message, bytes): bytes_message = message else: bytes_message = message.encode("ascii") # The original algorithm uses regexes to do this stuff. # This one is -IMHO- more pythonic and it is slightly faster. # # Another version is even faster, but I chose to keep something # more pythonic and readable. # FYI, the fastest way to do all this stuff seems to be # (according to my benchmarks): # # bytes_message.replace(b"\r\n", b"\n") \ # .replace(b"\r", b"\n") \ # .replace(b"\n", b"\r\n") # # DOT_LINE_REGEX = re.compile(rb"^\.", re.MULTILINE) # bytes_message = DOT_LINE_REGEX.sub(b"..", bytes_message) # # if not bytes_message.endswith(b"\r\n"): # bytes_message += b"\r\n" # # bytes_message += b"\r\n.\r\n" lines = [] for line in bytes_message.splitlines(): if line.startswith(b"."): line = line.replace(b".", b"..", 1) lines.append(line) # Recompose the message with <CRLF> only: bytes_message = b"\r\n".join(lines) # Make sure message ends with <CRLF>.<CRLF>: bytes_message += b"\r\n.\r\n" return bytes_message @staticmethod def b64enc(s): """ Base64-encodes the given string and returns it as a :obj:`str`. This is a simple helper function that takes a str, base64-encodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: s (str): String to be converted to base64. Returns: str: A base64-encoded string. """ return base64.b64encode(s.encode("utf-8")).decode("utf-8") @staticmethod def b64dec(b): """ Base64-decodes the given :obj:`bytes` and converts it to a :obj:`str`. This is a simple helper function that takes a bytes, base64-decodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: b (bytes): A base64-encoded bytes. Returns: str: A base64-decoded string. """ return base64.b64decode(b).decode("utf-8")
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.ehlo
python
async def ehlo(self, from_host=None): if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("EHLO", from_host) self.last_ehlo_response = (code, message) extns, auths = SMTP.parse_esmtp_extensions(message) self.esmtp_extensions = extns self.auth_mechanisms = auths self.supports_esmtp = True return code, message
Sends a SMTP 'EHLO' command. - Identifies the client and starts the session. If given ``from`_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1
train
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L340-L375
[ "async def do_cmd(self, *args, success=None):\n \"\"\"\n Sends the given command to the server.\n\n Args:\n *args: Command and arguments to be sent to the server.\n\n Raises:\n ConnectionResetError: If the connection with the server is\n unexpectedely lost.\n SMTPCommandF...
class SMTP: """ SMTP or ESMTP client. This should follow RFC 5321 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP Authentication) and RFC 2487 (Secure SMTP over TLS). Attributes: hostname (str): Hostname of the SMTP server we are connecting to. port (int): Port on which the SMTP server listens for connections. timeout (int): Not used. last_helo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *HELO* response. last_ehlo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *EHLO* response. supports_esmtp (bool): True if the server supports ESMTP (set after a *EHLO* command, False otherwise. esmtp_extensions (dict): ESMTP extensions and parameters supported by the SMTP server (set after a *EHLO* command). auth_mechanisms (list of str): Authentication mechanisms supported by the SMTP server. ssl_context (bool): Always False. (Used in SMTP_SSL subclass) reader (:class:`streams.SMTPStreamReader`): SMTP stream reader, used to read server responses. writer (:class:`streams.SMTPStreamWriter`): SMTP stream writer, used to send commands to the server. transport (:class:`asyncio.BaseTransport`): Communication channel abstraction between client and server. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): If True, the connection is made using the aioopenssl module. Defaults to False. _fqdn (str): Client FQDN. Used to identify the client to the server. Class Attributes: _default_port (int): Default port to use. Defaults to 25. _supported_auth_mechanisms (dict): Dict containing the information about supported authentication mechanisms, ordered by preference of use. The entries consist in : - The authentication mechanism name, in lowercase, as given by SMTP servers. - The name of the method to call to authenticate using the mechanism. """ _default_port = 25 _supported_auth_mechanisms = { "cram-md5": "_auth_cram_md5", "plain": "_auth_plain", "login": "_auth_login", } def __init__( self, hostname="localhost", port=_default_port, fqdn=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, loop=None, use_aioopenssl=False, ): """ Initializes a new :class:`SMTP` instance. Args: hostname (str): Hostname of the SMTP server to connect to. port (int): Port to use to connect to the SMTP server. fqdn (str or None): Client Fully Qualified Domain Name. This is used to identify the client to the server. timeout (int): Not used. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): Use the aioopenssl module to open the connection. This is mandatory if you plan on using STARTTLS. """ self.hostname = hostname try: self.port = int(port) except ValueError: self.port = self.__class__._default_port self.timeout = timeout self._fqdn = fqdn self.loop = loop or asyncio.get_event_loop() self.use_aioopenssl = use_aioopenssl self.reset_state() @property def fqdn(self): """ Returns the string used to identify the client when initiating a SMTP session. RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do: - Use the client FQDN ; - If it isn't available, we SHOULD fall back to an address literal. Returns: str: The value that should be used as the client FQDN. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 .. _`§ 4.1.3`: https//tools.ietf.org/html/rfc5321#section-4.1.3 """ if self._fqdn is None: # Let's try to retrieve it: self._fqdn = socket.getfqdn() if "." not in self._fqdn: try: info = socket.getaddrinfo( host="localhost", port=None, proto=socket.IPPROTO_TCP ) except socket.gaierror: addr = "127.0.0.1" else: # We only consider the first returned result and we're # only interested in getting the IP(v4 or v6) address: addr = info[0][4][0] self._fqdn = "[{}]".format(addr) return self._fqdn def reset_state(self): """ Resets some attributes to their default values. This is especially useful when initializing a newly created :class:`SMTP` instance and when closing an existing SMTP session. It allows us to use the same SMTP instance and connect several times. """ self.last_helo_response = (None, None) self.last_ehlo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] self.ssl_context = False self.reader = None self.writer = None self.transport = None async def __aenter__(self): """ Enters the asynchronous context manager. Also tries to connect to the server. Raises: SMTPConnectionRefusedError: If the connection between client and SMTP server can not be established. .. seealso:: :meth:`SMTP.connect` """ await self.connect() return self async def __aexit__(self, *args): """ Exits the asynchronous context manager. Closes the connection and resets instance attributes. .. seealso:: :meth:`SMTP.quit` """ await self.quit() async def connect(self): """ Connects to the server. .. note:: This method is automatically invoked by :meth:`SMTP.__aenter__`. The code is mostly borrowed from the :func:`asyncio.streams.open_connection` source code. Raises: ConnectionError subclass: If the connection between client and SMTP server can not be established. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ # First build the reader: self.reader = SMTPStreamReader(loop=self.loop) # Then build the protocol: protocol = asyncio.StreamReaderProtocol(self.reader, loop=self.loop) # With the just-built reader and protocol, create the connection and # get the transport stream: conn = { "protocol_factory": lambda: protocol, "host": self.hostname, "port": self.port, } if self.use_aioopenssl: conn.update( { "use_starttls": not self.ssl_context, "ssl_context_factory": lambda transport: self.ssl_context, "server_hostname": self.hostname, # For SSL } ) import aioopenssl # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await aioopenssl.create_starttls_connection( self.loop, **conn ) # HACK: aioopenssl transports don't implement is_closing, and thus drain() fails... self.transport.is_closing = lambda: False else: conn["ssl"] = self.ssl_context # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await self.loop.create_connection(**conn) # If the connection has been established, build the writer: self.writer = SMTPStreamWriter(self.transport, protocol, self.reader, self.loop) code, message = await self.reader.read_reply() if code != 220: raise ConnectionRefusedError(code, message) return code, message async def do_cmd(self, *args, success=None): """ Sends the given command to the server. Args: *args: Command and arguments to be sent to the server. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ if success is None: success = (250,) cmd = " ".join(args) await self.writer.send_command(cmd) code, message = await self.reader.read_reply() if code not in success: raise SMTPCommandFailedError(code, message, cmd) return code, message async def helo(self, from_host=None): """ Sends a SMTP 'HELO' command. - Identifies the client and starts the session. If given ``from_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our HELO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("HELO", from_host) self.last_helo_response = (code, message) return code, message async def help(self, command_name=None): """ Sends a SMTP 'HELP' command. For further details please check out `RFC 5321 § 4.1.1.8`_. Args: command_name (str or None, optional): Name of a command for which you want help. For example, if you want to get help about the '*RSET*' command, you'd call ``help('RSET')``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the HELP command fails. Returns: Help text as given by the server. .. _`RFC 5321 § 4.1.1.8`: https://tools.ietf.org/html/rfc5321#section-4.1.1.8 """ if command_name is None: command_name = "" code, message = await self.do_cmd("HELP", command_name) return message async def rset(self): """ Sends a SMTP 'RSET' command. - Resets the session. For further details, please check out `RFC 5321 § 4.1.1.5`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RSET command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.5`: https://tools.ietf.org/html/rfc5321#section-4.1.1.5 """ return await self.do_cmd("RSET") async def noop(self): """ Sends a SMTP 'NOOP' command. - Doesn't do anything. For further details, please check out `RFC 5321 § 4.1.1.9`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the NOOP command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.9`: https://tools.ietf.org/html/rfc5321#section-4.1.1.9 """ return await self.do_cmd("NOOP") async def vrfy(self, address): """ Sends a SMTP 'VRFY' command. - Tests the validity of the given address. For further details, please check out `RFC 5321 § 4.1.1.6`_. Args: address (str): E-mail address to be checked. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the VRFY command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.6`: https://tools.ietf.org/html/rfc5321#section-4.1.1.6 """ return await self.do_cmd("VRFY", address) async def expn(self, address): """ Sends a SMTP 'EXPN' command. - Expands a mailing-list. For further details, please check out `RFC 5321 § 4.1.1.7`_. Args: address (str): E-mail address to expand. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the EXPN command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.7`: https://tools.ietf.org/html/rfc5321#section-4.1.1.7 """ return await self.do_cmd("EXPN", address) async def mail(self, sender, options=None): """ Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] from_addr = "FROM:{}".format(quoteaddr(sender)) code, message = await self.do_cmd("MAIL", from_addr, *options) return code, message async def rcpt(self, recipient, options=None): """ Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. options (list of str or None, optional): Additional options to send along with the *RCPT* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RCPT command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.3`: https://tools.ietf.org/html/rfc5321#section-4.1.1.3 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] to_addr = "TO:{}".format(quoteaddr(recipient)) code, message = await self.do_cmd("RCPT", to_addr, *options) return code, message async def quit(self): """ Sends a SMTP 'QUIT' command. - Ends the session. For further details, please check out `RFC 5321 § 4.1.1.10`_. Returns: (int, str): A (code, message) 2-tuple containing the server response. If the connection is already closed when calling this method, returns (-1, None). .. _`RFC 5321 § 4.1.1.10`: https://tools.ietf.org/html/rfc5321#section-4.1.1.10 """ code = -1 message = None try: code, message = await self.do_cmd("QUIT") except ConnectionError: # We voluntarily ignore this kind of exceptions since... the # connection seems already closed. pass except SMTPCommandFailedError: pass await self.close() return code, message async def data(self, email_message): """ Sends a SMTP 'DATA' command. - Transmits the message to the server. If ``email_message`` is a bytes object, sends it as it is. Else, makes all the required changes so it can be safely trasmitted to the SMTP server.` For further details, please check out `RFC 5321 § 4.1.1.4`_. Args: email_message (str or bytes): Message to be sent. Raises: ConnectionError subclass: If the connection to the server is unexpectedely lost. SMTPCommandFailedError: If the DATA command fails. Returns: (int, str): A (code, message) 2-tuple containing the server last response (the one the server sent after all data were sent by the client). .. seealso: :meth:`SMTP.prepare_message` .. _`RFC 5321 § 4.1.1.4`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 """ code, message = await self.do_cmd("DATA", success=(354,)) email_message = SMTP.prepare_message(email_message) self.writer.write(email_message) # write is non-blocking. await self.writer.drain() # don't forget to drain. code, message = await self.reader.read_reply() return code, message async def auth(self, username, password): """ Tries to authenticate user against the SMTP server. Args: username (str): Username to authenticate with. password (str): Password to use along with the given ``username``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPLoginError: If the authentication failed (either because all attempts failed or because there was no suitable authentication mechanism). Returns: (int, str): A (code, message) 2-tuple containing the last server response. """ # EHLO/HELO is required: await self.ehlo_or_helo_if_needed() errors = [] # To store SMTPAuthenticationErrors code = message = None # Try to authenticate using all mechanisms supported by both # server and client (and only these): for auth, meth in self.__class__._supported_auth_mechanisms.items(): if auth in self.auth_mechanisms: auth_func = getattr(self, meth) try: code, message = await auth_func(username, password) except SMTPAuthenticationError as e: errors.append(e) else: break else: if not errors: err = "Could not find any suitable authentication mechanism." errors.append(SMTPAuthenticationError(-1, err)) raise SMTPLoginError(errors) return code, message async def starttls(self, context=None): """ Upgrades the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports SSL/TLS, this will encrypt the rest of the SMTP session. Raises: SMTPCommandNotSupportedError: If the server does not support STARTTLS. SMTPCommandFailedError: If the STARTTLS command fails BadImplementationError: If the connection does not use aioopenssl. Args: context (:obj:`OpenSSL.SSL.Context`): SSL context Returns: (int, message): A (code, message) 2-tuple containing the server response. """ if not self.use_aioopenssl: raise BadImplementationError("This connection does not use aioopenssl") import aioopenssl import OpenSSL await self.ehlo_or_helo_if_needed() if "starttls" not in self.esmtp_extensions: raise SMTPCommandNotSupportedError("STARTTLS") code, message = await self.do_cmd("STARTTLS", success=(220,)) # Don't check for code, do_cmd did it if context is None: context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD) await self.transport.starttls(ssl_context=context) # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. # FIXME: wouldn't it be better to use reset_state here ? # And reset self.reader, self.writer and self.transport just after # Maybe also self.ssl_context ? self.last_ehlo_response = (None, None) self.last_helo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] return (code, message) async def sendmail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while sending message.") >>> else: >>> print("Result: {}.".format(r)) >>> except ConnectionError as e: >>> print(e) Result: {}. Args: sender (str): E-mail address of the sender. recipients (list of str or str): E-mail(s) address(es) of the recipient(s). message (str or bytes): Message body. mail_options (list of str): ESMTP options (such as *8BITMIME*) to send along the *MAIL* command. rcpt_options (list of str): ESMTP options (such as *DSN*) to send along all the *RCPT* commands. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPCommandFailedError: If the server refuses our MAIL command. SMTPCommandFailedError: If the server refuses our DATA command. SMTPNoRecipientError: If the server refuses all given recipients. Returns: dict: A dict containing an entry for each recipient that was refused. Each entry is associated with a (code, message) 2-tuple containing the error code and message, as returned by the server. When everythign runs smoothly, the returning dict is empty. .. note:: The connection remains open after. It's your responsibility to close it. A good practice is to use the asynchronous context manager instead. See :meth:`SMTP.__aenter__` for further details. """ # Make sure `recipients` is a list: if isinstance(recipients, str): recipients = [recipients] # Set some defaults values: if mail_options is None: mail_options = [] if rcpt_options is None: rcpt_options = [] # EHLO or HELO is required: await self.ehlo_or_helo_if_needed() if self.supports_esmtp: if "size" in self.esmtp_extensions: mail_options.append("size={}".format(len(message))) await self.mail(sender, mail_options) errors = [] for recipient in recipients: try: await self.rcpt(recipient, rcpt_options) except SMTPCommandFailedError as e: errors.append(e) if len(recipients) == len(errors): # The server refused all our recipients: raise SMTPNoRecipientError(errors) await self.data(message) # If we got here then somebody got our mail: return errors async def send_mail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Alias for :meth:`SMTP.sendmail`. """ return await self.sendmail( sender, recipients, message, mail_options, rcpt_options ) async def ehlo_or_helo_if_needed(self): """ Calls :meth:`SMTP.ehlo` and/or :meth:`SMTP.helo` if needed. If there hasn't been any previous *EHLO* or *HELO* command this session, tries to initiate the session. *EHLO* is tried first. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. """ no_helo = self.last_helo_response == (None, None) no_ehlo = self.last_ehlo_response == (None, None) if no_helo and no_ehlo: try: # First we try EHLO: await self.ehlo() except SMTPCommandFailedError: # EHLO failed, let's try HELO: await self.helo() async def close(self): """ Cleans up after the connection to the SMTP server has been closed (voluntarily or not). """ if self.writer is not None: # Close the transport: try: self.writer.close() except OSError as exc: if exc.errno != errno.ENOTCONN: raise self.reset_state() async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challenge is hashed using HMAC-MD5 and the user password as key (shared secret) ; 3) The hashed challenge is converted to a string of lowercase hexadecimal digits ; 4) The username and a space character are prepended to the hex digits ; 5) The concatenation is base64-encoded and sent to the server. 6) If the server replies with a return code of 235, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "CRAM-MD5" code, message = await self.do_cmd("AUTH", mechanism, success=(334,)) decoded_challenge = base64.b64decode(message) challenge_hash = hmac.new( key=password.encode("utf-8"), msg=decoded_challenge, digestmod="md5" ) hex_hash = challenge_hash.hexdigest() response = "{} {}".format(username, hex_hash) encoded_response = SMTP.b64enc(response) try: code, message = await self.do_cmd(encoded_response, success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_login(self, username, password): """ Performs an authentication attempt using the LOGIN mechanism. Protocol: 1. The username is base64-encoded ; 2. The string 'AUTH LOGIN' and a space character are prepended to the base64-encoded username and sent to the server ; 3. If the server replies with a 334 return code, we can go on: 1) The password is base64-encoded and sent to the server ; 2) If the server replies with a 235 return code, the user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "LOGIN" code, message = await self.do_cmd( "AUTH", mechanism, SMTP.b64enc(username), success=(334,) ) try: code, message = await self.do_cmd(SMTP.b64enc(password), success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_plain(self, username, password): """ Performs an authentication attempt using the PLAIN mechanism. Protocol: 1. Format the username and password in a suitable way ; 2. The formatted string is base64-encoded ; 3. The string 'AUTH PLAIN' and a space character are prepended to the base64-encoded username and password and sent to the server ; 4. If the server replies with a 235 return code, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "PLAIN" credentials = "\0{}\0{}".format(username, password) encoded_credentials = SMTP.b64enc(credentials) try: code, message = await self.do_cmd( "AUTH", mechanism, encoded_credentials, success=(235, 503) ) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message @staticmethod def parse_esmtp_extensions(message): """ Parses the response given by an ESMTP server after a *EHLO* command. The response is parsed to build: - A dict of supported ESMTP extensions (with parameters, if any). - A list of supported authentication methods. Returns: (dict, list): A (extensions, auth_mechanisms) 2-tuple containing the supported extensions and authentication methods. """ extns = {} auths = [] oldstyle_auth_regex = re.compile(r"auth=(?P<auth>.*)", re.IGNORECASE) extension_regex = re.compile( r"(?P<feature>[a-z0-9][a-z0-9\-]*) ?", re.IGNORECASE ) lines = message.splitlines() for line in lines[1:]: # To be able to communicate with as many SMTP servers as possible, # we have to take the old-style auth advertisement into account. match = oldstyle_auth_regex.match(line) if match: auth = match.group("auth")[0] auth = auth.lower().strip() if auth not in auths: auths.append(auth) # RFC 1869 requires a space between EHLO keyword and parameters. # It's actually stricter, in that only spaces are allowed between # parameters, but were not going to check for that here. # Note that the space isn't present if there are no parameters. match = extension_regex.match(line) if match: feature = match.group("feature").lower() params = match.string[match.end("feature") :].strip() extns[feature] = params if feature == "auth": auths.extend([param.strip().lower() for param in params.split()]) return extns, auths @staticmethod def prepare_message(message): """ Returns the given message encoded in ascii with a format suitable for SMTP transmission: - Makes sure the message is ASCII encoded ; - Normalizes line endings to '\r\n' ; - Adds a (second) period at the beginning of lines that start with a period ; - Makes sure the message ends with '\r\n.\r\n'. For further details, please check out RFC 5321 `§ 4.1.1.4`_ and `§ 4.5.2`_. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 .. _`§ 4.5.2`: https://tools.ietf.org/html/rfc5321#section-4.5.2 """ if isinstance(message, bytes): bytes_message = message else: bytes_message = message.encode("ascii") # The original algorithm uses regexes to do this stuff. # This one is -IMHO- more pythonic and it is slightly faster. # # Another version is even faster, but I chose to keep something # more pythonic and readable. # FYI, the fastest way to do all this stuff seems to be # (according to my benchmarks): # # bytes_message.replace(b"\r\n", b"\n") \ # .replace(b"\r", b"\n") \ # .replace(b"\n", b"\r\n") # # DOT_LINE_REGEX = re.compile(rb"^\.", re.MULTILINE) # bytes_message = DOT_LINE_REGEX.sub(b"..", bytes_message) # # if not bytes_message.endswith(b"\r\n"): # bytes_message += b"\r\n" # # bytes_message += b"\r\n.\r\n" lines = [] for line in bytes_message.splitlines(): if line.startswith(b"."): line = line.replace(b".", b"..", 1) lines.append(line) # Recompose the message with <CRLF> only: bytes_message = b"\r\n".join(lines) # Make sure message ends with <CRLF>.<CRLF>: bytes_message += b"\r\n.\r\n" return bytes_message @staticmethod def b64enc(s): """ Base64-encodes the given string and returns it as a :obj:`str`. This is a simple helper function that takes a str, base64-encodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: s (str): String to be converted to base64. Returns: str: A base64-encoded string. """ return base64.b64encode(s.encode("utf-8")).decode("utf-8") @staticmethod def b64dec(b): """ Base64-decodes the given :obj:`bytes` and converts it to a :obj:`str`. This is a simple helper function that takes a bytes, base64-decodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: b (bytes): A base64-encoded bytes. Returns: str: A base64-decoded string. """ return base64.b64decode(b).decode("utf-8")
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.help
python
async def help(self, command_name=None): if command_name is None: command_name = "" code, message = await self.do_cmd("HELP", command_name) return message
Sends a SMTP 'HELP' command. For further details please check out `RFC 5321 § 4.1.1.8`_. Args: command_name (str or None, optional): Name of a command for which you want help. For example, if you want to get help about the '*RSET*' command, you'd call ``help('RSET')``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the HELP command fails. Returns: Help text as given by the server. .. _`RFC 5321 § 4.1.1.8`: https://tools.ietf.org/html/rfc5321#section-4.1.1.8
train
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L377-L403
[ "async def do_cmd(self, *args, success=None):\n \"\"\"\n Sends the given command to the server.\n\n Args:\n *args: Command and arguments to be sent to the server.\n\n Raises:\n ConnectionResetError: If the connection with the server is\n unexpectedely lost.\n SMTPCommandF...
class SMTP: """ SMTP or ESMTP client. This should follow RFC 5321 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP Authentication) and RFC 2487 (Secure SMTP over TLS). Attributes: hostname (str): Hostname of the SMTP server we are connecting to. port (int): Port on which the SMTP server listens for connections. timeout (int): Not used. last_helo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *HELO* response. last_ehlo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *EHLO* response. supports_esmtp (bool): True if the server supports ESMTP (set after a *EHLO* command, False otherwise. esmtp_extensions (dict): ESMTP extensions and parameters supported by the SMTP server (set after a *EHLO* command). auth_mechanisms (list of str): Authentication mechanisms supported by the SMTP server. ssl_context (bool): Always False. (Used in SMTP_SSL subclass) reader (:class:`streams.SMTPStreamReader`): SMTP stream reader, used to read server responses. writer (:class:`streams.SMTPStreamWriter`): SMTP stream writer, used to send commands to the server. transport (:class:`asyncio.BaseTransport`): Communication channel abstraction between client and server. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): If True, the connection is made using the aioopenssl module. Defaults to False. _fqdn (str): Client FQDN. Used to identify the client to the server. Class Attributes: _default_port (int): Default port to use. Defaults to 25. _supported_auth_mechanisms (dict): Dict containing the information about supported authentication mechanisms, ordered by preference of use. The entries consist in : - The authentication mechanism name, in lowercase, as given by SMTP servers. - The name of the method to call to authenticate using the mechanism. """ _default_port = 25 _supported_auth_mechanisms = { "cram-md5": "_auth_cram_md5", "plain": "_auth_plain", "login": "_auth_login", } def __init__( self, hostname="localhost", port=_default_port, fqdn=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, loop=None, use_aioopenssl=False, ): """ Initializes a new :class:`SMTP` instance. Args: hostname (str): Hostname of the SMTP server to connect to. port (int): Port to use to connect to the SMTP server. fqdn (str or None): Client Fully Qualified Domain Name. This is used to identify the client to the server. timeout (int): Not used. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): Use the aioopenssl module to open the connection. This is mandatory if you plan on using STARTTLS. """ self.hostname = hostname try: self.port = int(port) except ValueError: self.port = self.__class__._default_port self.timeout = timeout self._fqdn = fqdn self.loop = loop or asyncio.get_event_loop() self.use_aioopenssl = use_aioopenssl self.reset_state() @property def fqdn(self): """ Returns the string used to identify the client when initiating a SMTP session. RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do: - Use the client FQDN ; - If it isn't available, we SHOULD fall back to an address literal. Returns: str: The value that should be used as the client FQDN. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 .. _`§ 4.1.3`: https//tools.ietf.org/html/rfc5321#section-4.1.3 """ if self._fqdn is None: # Let's try to retrieve it: self._fqdn = socket.getfqdn() if "." not in self._fqdn: try: info = socket.getaddrinfo( host="localhost", port=None, proto=socket.IPPROTO_TCP ) except socket.gaierror: addr = "127.0.0.1" else: # We only consider the first returned result and we're # only interested in getting the IP(v4 or v6) address: addr = info[0][4][0] self._fqdn = "[{}]".format(addr) return self._fqdn def reset_state(self): """ Resets some attributes to their default values. This is especially useful when initializing a newly created :class:`SMTP` instance and when closing an existing SMTP session. It allows us to use the same SMTP instance and connect several times. """ self.last_helo_response = (None, None) self.last_ehlo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] self.ssl_context = False self.reader = None self.writer = None self.transport = None async def __aenter__(self): """ Enters the asynchronous context manager. Also tries to connect to the server. Raises: SMTPConnectionRefusedError: If the connection between client and SMTP server can not be established. .. seealso:: :meth:`SMTP.connect` """ await self.connect() return self async def __aexit__(self, *args): """ Exits the asynchronous context manager. Closes the connection and resets instance attributes. .. seealso:: :meth:`SMTP.quit` """ await self.quit() async def connect(self): """ Connects to the server. .. note:: This method is automatically invoked by :meth:`SMTP.__aenter__`. The code is mostly borrowed from the :func:`asyncio.streams.open_connection` source code. Raises: ConnectionError subclass: If the connection between client and SMTP server can not be established. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ # First build the reader: self.reader = SMTPStreamReader(loop=self.loop) # Then build the protocol: protocol = asyncio.StreamReaderProtocol(self.reader, loop=self.loop) # With the just-built reader and protocol, create the connection and # get the transport stream: conn = { "protocol_factory": lambda: protocol, "host": self.hostname, "port": self.port, } if self.use_aioopenssl: conn.update( { "use_starttls": not self.ssl_context, "ssl_context_factory": lambda transport: self.ssl_context, "server_hostname": self.hostname, # For SSL } ) import aioopenssl # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await aioopenssl.create_starttls_connection( self.loop, **conn ) # HACK: aioopenssl transports don't implement is_closing, and thus drain() fails... self.transport.is_closing = lambda: False else: conn["ssl"] = self.ssl_context # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await self.loop.create_connection(**conn) # If the connection has been established, build the writer: self.writer = SMTPStreamWriter(self.transport, protocol, self.reader, self.loop) code, message = await self.reader.read_reply() if code != 220: raise ConnectionRefusedError(code, message) return code, message async def do_cmd(self, *args, success=None): """ Sends the given command to the server. Args: *args: Command and arguments to be sent to the server. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ if success is None: success = (250,) cmd = " ".join(args) await self.writer.send_command(cmd) code, message = await self.reader.read_reply() if code not in success: raise SMTPCommandFailedError(code, message, cmd) return code, message async def helo(self, from_host=None): """ Sends a SMTP 'HELO' command. - Identifies the client and starts the session. If given ``from_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our HELO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("HELO", from_host) self.last_helo_response = (code, message) return code, message async def ehlo(self, from_host=None): """ Sends a SMTP 'EHLO' command. - Identifies the client and starts the session. If given ``from`_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("EHLO", from_host) self.last_ehlo_response = (code, message) extns, auths = SMTP.parse_esmtp_extensions(message) self.esmtp_extensions = extns self.auth_mechanisms = auths self.supports_esmtp = True return code, message async def rset(self): """ Sends a SMTP 'RSET' command. - Resets the session. For further details, please check out `RFC 5321 § 4.1.1.5`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RSET command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.5`: https://tools.ietf.org/html/rfc5321#section-4.1.1.5 """ return await self.do_cmd("RSET") async def noop(self): """ Sends a SMTP 'NOOP' command. - Doesn't do anything. For further details, please check out `RFC 5321 § 4.1.1.9`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the NOOP command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.9`: https://tools.ietf.org/html/rfc5321#section-4.1.1.9 """ return await self.do_cmd("NOOP") async def vrfy(self, address): """ Sends a SMTP 'VRFY' command. - Tests the validity of the given address. For further details, please check out `RFC 5321 § 4.1.1.6`_. Args: address (str): E-mail address to be checked. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the VRFY command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.6`: https://tools.ietf.org/html/rfc5321#section-4.1.1.6 """ return await self.do_cmd("VRFY", address) async def expn(self, address): """ Sends a SMTP 'EXPN' command. - Expands a mailing-list. For further details, please check out `RFC 5321 § 4.1.1.7`_. Args: address (str): E-mail address to expand. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the EXPN command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.7`: https://tools.ietf.org/html/rfc5321#section-4.1.1.7 """ return await self.do_cmd("EXPN", address) async def mail(self, sender, options=None): """ Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] from_addr = "FROM:{}".format(quoteaddr(sender)) code, message = await self.do_cmd("MAIL", from_addr, *options) return code, message async def rcpt(self, recipient, options=None): """ Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. options (list of str or None, optional): Additional options to send along with the *RCPT* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RCPT command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.3`: https://tools.ietf.org/html/rfc5321#section-4.1.1.3 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] to_addr = "TO:{}".format(quoteaddr(recipient)) code, message = await self.do_cmd("RCPT", to_addr, *options) return code, message async def quit(self): """ Sends a SMTP 'QUIT' command. - Ends the session. For further details, please check out `RFC 5321 § 4.1.1.10`_. Returns: (int, str): A (code, message) 2-tuple containing the server response. If the connection is already closed when calling this method, returns (-1, None). .. _`RFC 5321 § 4.1.1.10`: https://tools.ietf.org/html/rfc5321#section-4.1.1.10 """ code = -1 message = None try: code, message = await self.do_cmd("QUIT") except ConnectionError: # We voluntarily ignore this kind of exceptions since... the # connection seems already closed. pass except SMTPCommandFailedError: pass await self.close() return code, message async def data(self, email_message): """ Sends a SMTP 'DATA' command. - Transmits the message to the server. If ``email_message`` is a bytes object, sends it as it is. Else, makes all the required changes so it can be safely trasmitted to the SMTP server.` For further details, please check out `RFC 5321 § 4.1.1.4`_. Args: email_message (str or bytes): Message to be sent. Raises: ConnectionError subclass: If the connection to the server is unexpectedely lost. SMTPCommandFailedError: If the DATA command fails. Returns: (int, str): A (code, message) 2-tuple containing the server last response (the one the server sent after all data were sent by the client). .. seealso: :meth:`SMTP.prepare_message` .. _`RFC 5321 § 4.1.1.4`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 """ code, message = await self.do_cmd("DATA", success=(354,)) email_message = SMTP.prepare_message(email_message) self.writer.write(email_message) # write is non-blocking. await self.writer.drain() # don't forget to drain. code, message = await self.reader.read_reply() return code, message async def auth(self, username, password): """ Tries to authenticate user against the SMTP server. Args: username (str): Username to authenticate with. password (str): Password to use along with the given ``username``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPLoginError: If the authentication failed (either because all attempts failed or because there was no suitable authentication mechanism). Returns: (int, str): A (code, message) 2-tuple containing the last server response. """ # EHLO/HELO is required: await self.ehlo_or_helo_if_needed() errors = [] # To store SMTPAuthenticationErrors code = message = None # Try to authenticate using all mechanisms supported by both # server and client (and only these): for auth, meth in self.__class__._supported_auth_mechanisms.items(): if auth in self.auth_mechanisms: auth_func = getattr(self, meth) try: code, message = await auth_func(username, password) except SMTPAuthenticationError as e: errors.append(e) else: break else: if not errors: err = "Could not find any suitable authentication mechanism." errors.append(SMTPAuthenticationError(-1, err)) raise SMTPLoginError(errors) return code, message async def starttls(self, context=None): """ Upgrades the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports SSL/TLS, this will encrypt the rest of the SMTP session. Raises: SMTPCommandNotSupportedError: If the server does not support STARTTLS. SMTPCommandFailedError: If the STARTTLS command fails BadImplementationError: If the connection does not use aioopenssl. Args: context (:obj:`OpenSSL.SSL.Context`): SSL context Returns: (int, message): A (code, message) 2-tuple containing the server response. """ if not self.use_aioopenssl: raise BadImplementationError("This connection does not use aioopenssl") import aioopenssl import OpenSSL await self.ehlo_or_helo_if_needed() if "starttls" not in self.esmtp_extensions: raise SMTPCommandNotSupportedError("STARTTLS") code, message = await self.do_cmd("STARTTLS", success=(220,)) # Don't check for code, do_cmd did it if context is None: context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD) await self.transport.starttls(ssl_context=context) # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. # FIXME: wouldn't it be better to use reset_state here ? # And reset self.reader, self.writer and self.transport just after # Maybe also self.ssl_context ? self.last_ehlo_response = (None, None) self.last_helo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] return (code, message) async def sendmail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while sending message.") >>> else: >>> print("Result: {}.".format(r)) >>> except ConnectionError as e: >>> print(e) Result: {}. Args: sender (str): E-mail address of the sender. recipients (list of str or str): E-mail(s) address(es) of the recipient(s). message (str or bytes): Message body. mail_options (list of str): ESMTP options (such as *8BITMIME*) to send along the *MAIL* command. rcpt_options (list of str): ESMTP options (such as *DSN*) to send along all the *RCPT* commands. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPCommandFailedError: If the server refuses our MAIL command. SMTPCommandFailedError: If the server refuses our DATA command. SMTPNoRecipientError: If the server refuses all given recipients. Returns: dict: A dict containing an entry for each recipient that was refused. Each entry is associated with a (code, message) 2-tuple containing the error code and message, as returned by the server. When everythign runs smoothly, the returning dict is empty. .. note:: The connection remains open after. It's your responsibility to close it. A good practice is to use the asynchronous context manager instead. See :meth:`SMTP.__aenter__` for further details. """ # Make sure `recipients` is a list: if isinstance(recipients, str): recipients = [recipients] # Set some defaults values: if mail_options is None: mail_options = [] if rcpt_options is None: rcpt_options = [] # EHLO or HELO is required: await self.ehlo_or_helo_if_needed() if self.supports_esmtp: if "size" in self.esmtp_extensions: mail_options.append("size={}".format(len(message))) await self.mail(sender, mail_options) errors = [] for recipient in recipients: try: await self.rcpt(recipient, rcpt_options) except SMTPCommandFailedError as e: errors.append(e) if len(recipients) == len(errors): # The server refused all our recipients: raise SMTPNoRecipientError(errors) await self.data(message) # If we got here then somebody got our mail: return errors async def send_mail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Alias for :meth:`SMTP.sendmail`. """ return await self.sendmail( sender, recipients, message, mail_options, rcpt_options ) async def ehlo_or_helo_if_needed(self): """ Calls :meth:`SMTP.ehlo` and/or :meth:`SMTP.helo` if needed. If there hasn't been any previous *EHLO* or *HELO* command this session, tries to initiate the session. *EHLO* is tried first. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. """ no_helo = self.last_helo_response == (None, None) no_ehlo = self.last_ehlo_response == (None, None) if no_helo and no_ehlo: try: # First we try EHLO: await self.ehlo() except SMTPCommandFailedError: # EHLO failed, let's try HELO: await self.helo() async def close(self): """ Cleans up after the connection to the SMTP server has been closed (voluntarily or not). """ if self.writer is not None: # Close the transport: try: self.writer.close() except OSError as exc: if exc.errno != errno.ENOTCONN: raise self.reset_state() async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challenge is hashed using HMAC-MD5 and the user password as key (shared secret) ; 3) The hashed challenge is converted to a string of lowercase hexadecimal digits ; 4) The username and a space character are prepended to the hex digits ; 5) The concatenation is base64-encoded and sent to the server. 6) If the server replies with a return code of 235, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "CRAM-MD5" code, message = await self.do_cmd("AUTH", mechanism, success=(334,)) decoded_challenge = base64.b64decode(message) challenge_hash = hmac.new( key=password.encode("utf-8"), msg=decoded_challenge, digestmod="md5" ) hex_hash = challenge_hash.hexdigest() response = "{} {}".format(username, hex_hash) encoded_response = SMTP.b64enc(response) try: code, message = await self.do_cmd(encoded_response, success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_login(self, username, password): """ Performs an authentication attempt using the LOGIN mechanism. Protocol: 1. The username is base64-encoded ; 2. The string 'AUTH LOGIN' and a space character are prepended to the base64-encoded username and sent to the server ; 3. If the server replies with a 334 return code, we can go on: 1) The password is base64-encoded and sent to the server ; 2) If the server replies with a 235 return code, the user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "LOGIN" code, message = await self.do_cmd( "AUTH", mechanism, SMTP.b64enc(username), success=(334,) ) try: code, message = await self.do_cmd(SMTP.b64enc(password), success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_plain(self, username, password): """ Performs an authentication attempt using the PLAIN mechanism. Protocol: 1. Format the username and password in a suitable way ; 2. The formatted string is base64-encoded ; 3. The string 'AUTH PLAIN' and a space character are prepended to the base64-encoded username and password and sent to the server ; 4. If the server replies with a 235 return code, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "PLAIN" credentials = "\0{}\0{}".format(username, password) encoded_credentials = SMTP.b64enc(credentials) try: code, message = await self.do_cmd( "AUTH", mechanism, encoded_credentials, success=(235, 503) ) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message @staticmethod def parse_esmtp_extensions(message): """ Parses the response given by an ESMTP server after a *EHLO* command. The response is parsed to build: - A dict of supported ESMTP extensions (with parameters, if any). - A list of supported authentication methods. Returns: (dict, list): A (extensions, auth_mechanisms) 2-tuple containing the supported extensions and authentication methods. """ extns = {} auths = [] oldstyle_auth_regex = re.compile(r"auth=(?P<auth>.*)", re.IGNORECASE) extension_regex = re.compile( r"(?P<feature>[a-z0-9][a-z0-9\-]*) ?", re.IGNORECASE ) lines = message.splitlines() for line in lines[1:]: # To be able to communicate with as many SMTP servers as possible, # we have to take the old-style auth advertisement into account. match = oldstyle_auth_regex.match(line) if match: auth = match.group("auth")[0] auth = auth.lower().strip() if auth not in auths: auths.append(auth) # RFC 1869 requires a space between EHLO keyword and parameters. # It's actually stricter, in that only spaces are allowed between # parameters, but were not going to check for that here. # Note that the space isn't present if there are no parameters. match = extension_regex.match(line) if match: feature = match.group("feature").lower() params = match.string[match.end("feature") :].strip() extns[feature] = params if feature == "auth": auths.extend([param.strip().lower() for param in params.split()]) return extns, auths @staticmethod def prepare_message(message): """ Returns the given message encoded in ascii with a format suitable for SMTP transmission: - Makes sure the message is ASCII encoded ; - Normalizes line endings to '\r\n' ; - Adds a (second) period at the beginning of lines that start with a period ; - Makes sure the message ends with '\r\n.\r\n'. For further details, please check out RFC 5321 `§ 4.1.1.4`_ and `§ 4.5.2`_. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 .. _`§ 4.5.2`: https://tools.ietf.org/html/rfc5321#section-4.5.2 """ if isinstance(message, bytes): bytes_message = message else: bytes_message = message.encode("ascii") # The original algorithm uses regexes to do this stuff. # This one is -IMHO- more pythonic and it is slightly faster. # # Another version is even faster, but I chose to keep something # more pythonic and readable. # FYI, the fastest way to do all this stuff seems to be # (according to my benchmarks): # # bytes_message.replace(b"\r\n", b"\n") \ # .replace(b"\r", b"\n") \ # .replace(b"\n", b"\r\n") # # DOT_LINE_REGEX = re.compile(rb"^\.", re.MULTILINE) # bytes_message = DOT_LINE_REGEX.sub(b"..", bytes_message) # # if not bytes_message.endswith(b"\r\n"): # bytes_message += b"\r\n" # # bytes_message += b"\r\n.\r\n" lines = [] for line in bytes_message.splitlines(): if line.startswith(b"."): line = line.replace(b".", b"..", 1) lines.append(line) # Recompose the message with <CRLF> only: bytes_message = b"\r\n".join(lines) # Make sure message ends with <CRLF>.<CRLF>: bytes_message += b"\r\n.\r\n" return bytes_message @staticmethod def b64enc(s): """ Base64-encodes the given string and returns it as a :obj:`str`. This is a simple helper function that takes a str, base64-encodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: s (str): String to be converted to base64. Returns: str: A base64-encoded string. """ return base64.b64encode(s.encode("utf-8")).decode("utf-8") @staticmethod def b64dec(b): """ Base64-decodes the given :obj:`bytes` and converts it to a :obj:`str`. This is a simple helper function that takes a bytes, base64-decodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: b (bytes): A base64-encoded bytes. Returns: str: A base64-decoded string. """ return base64.b64decode(b).decode("utf-8")
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.mail
python
async def mail(self, sender, options=None): if options is None: options = [] from_addr = "FROM:{}".format(quoteaddr(sender)) code, message = await self.do_cmd("MAIL", from_addr, *options) return code, message
Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3
train
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L487-L517
[ "async def do_cmd(self, *args, success=None):\n \"\"\"\n Sends the given command to the server.\n\n Args:\n *args: Command and arguments to be sent to the server.\n\n Raises:\n ConnectionResetError: If the connection with the server is\n unexpectedely lost.\n SMTPCommandF...
class SMTP: """ SMTP or ESMTP client. This should follow RFC 5321 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP Authentication) and RFC 2487 (Secure SMTP over TLS). Attributes: hostname (str): Hostname of the SMTP server we are connecting to. port (int): Port on which the SMTP server listens for connections. timeout (int): Not used. last_helo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *HELO* response. last_ehlo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *EHLO* response. supports_esmtp (bool): True if the server supports ESMTP (set after a *EHLO* command, False otherwise. esmtp_extensions (dict): ESMTP extensions and parameters supported by the SMTP server (set after a *EHLO* command). auth_mechanisms (list of str): Authentication mechanisms supported by the SMTP server. ssl_context (bool): Always False. (Used in SMTP_SSL subclass) reader (:class:`streams.SMTPStreamReader`): SMTP stream reader, used to read server responses. writer (:class:`streams.SMTPStreamWriter`): SMTP stream writer, used to send commands to the server. transport (:class:`asyncio.BaseTransport`): Communication channel abstraction between client and server. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): If True, the connection is made using the aioopenssl module. Defaults to False. _fqdn (str): Client FQDN. Used to identify the client to the server. Class Attributes: _default_port (int): Default port to use. Defaults to 25. _supported_auth_mechanisms (dict): Dict containing the information about supported authentication mechanisms, ordered by preference of use. The entries consist in : - The authentication mechanism name, in lowercase, as given by SMTP servers. - The name of the method to call to authenticate using the mechanism. """ _default_port = 25 _supported_auth_mechanisms = { "cram-md5": "_auth_cram_md5", "plain": "_auth_plain", "login": "_auth_login", } def __init__( self, hostname="localhost", port=_default_port, fqdn=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, loop=None, use_aioopenssl=False, ): """ Initializes a new :class:`SMTP` instance. Args: hostname (str): Hostname of the SMTP server to connect to. port (int): Port to use to connect to the SMTP server. fqdn (str or None): Client Fully Qualified Domain Name. This is used to identify the client to the server. timeout (int): Not used. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): Use the aioopenssl module to open the connection. This is mandatory if you plan on using STARTTLS. """ self.hostname = hostname try: self.port = int(port) except ValueError: self.port = self.__class__._default_port self.timeout = timeout self._fqdn = fqdn self.loop = loop or asyncio.get_event_loop() self.use_aioopenssl = use_aioopenssl self.reset_state() @property def fqdn(self): """ Returns the string used to identify the client when initiating a SMTP session. RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do: - Use the client FQDN ; - If it isn't available, we SHOULD fall back to an address literal. Returns: str: The value that should be used as the client FQDN. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 .. _`§ 4.1.3`: https//tools.ietf.org/html/rfc5321#section-4.1.3 """ if self._fqdn is None: # Let's try to retrieve it: self._fqdn = socket.getfqdn() if "." not in self._fqdn: try: info = socket.getaddrinfo( host="localhost", port=None, proto=socket.IPPROTO_TCP ) except socket.gaierror: addr = "127.0.0.1" else: # We only consider the first returned result and we're # only interested in getting the IP(v4 or v6) address: addr = info[0][4][0] self._fqdn = "[{}]".format(addr) return self._fqdn def reset_state(self): """ Resets some attributes to their default values. This is especially useful when initializing a newly created :class:`SMTP` instance and when closing an existing SMTP session. It allows us to use the same SMTP instance and connect several times. """ self.last_helo_response = (None, None) self.last_ehlo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] self.ssl_context = False self.reader = None self.writer = None self.transport = None async def __aenter__(self): """ Enters the asynchronous context manager. Also tries to connect to the server. Raises: SMTPConnectionRefusedError: If the connection between client and SMTP server can not be established. .. seealso:: :meth:`SMTP.connect` """ await self.connect() return self async def __aexit__(self, *args): """ Exits the asynchronous context manager. Closes the connection and resets instance attributes. .. seealso:: :meth:`SMTP.quit` """ await self.quit() async def connect(self): """ Connects to the server. .. note:: This method is automatically invoked by :meth:`SMTP.__aenter__`. The code is mostly borrowed from the :func:`asyncio.streams.open_connection` source code. Raises: ConnectionError subclass: If the connection between client and SMTP server can not be established. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ # First build the reader: self.reader = SMTPStreamReader(loop=self.loop) # Then build the protocol: protocol = asyncio.StreamReaderProtocol(self.reader, loop=self.loop) # With the just-built reader and protocol, create the connection and # get the transport stream: conn = { "protocol_factory": lambda: protocol, "host": self.hostname, "port": self.port, } if self.use_aioopenssl: conn.update( { "use_starttls": not self.ssl_context, "ssl_context_factory": lambda transport: self.ssl_context, "server_hostname": self.hostname, # For SSL } ) import aioopenssl # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await aioopenssl.create_starttls_connection( self.loop, **conn ) # HACK: aioopenssl transports don't implement is_closing, and thus drain() fails... self.transport.is_closing = lambda: False else: conn["ssl"] = self.ssl_context # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await self.loop.create_connection(**conn) # If the connection has been established, build the writer: self.writer = SMTPStreamWriter(self.transport, protocol, self.reader, self.loop) code, message = await self.reader.read_reply() if code != 220: raise ConnectionRefusedError(code, message) return code, message async def do_cmd(self, *args, success=None): """ Sends the given command to the server. Args: *args: Command and arguments to be sent to the server. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ if success is None: success = (250,) cmd = " ".join(args) await self.writer.send_command(cmd) code, message = await self.reader.read_reply() if code not in success: raise SMTPCommandFailedError(code, message, cmd) return code, message async def helo(self, from_host=None): """ Sends a SMTP 'HELO' command. - Identifies the client and starts the session. If given ``from_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our HELO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("HELO", from_host) self.last_helo_response = (code, message) return code, message async def ehlo(self, from_host=None): """ Sends a SMTP 'EHLO' command. - Identifies the client and starts the session. If given ``from`_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("EHLO", from_host) self.last_ehlo_response = (code, message) extns, auths = SMTP.parse_esmtp_extensions(message) self.esmtp_extensions = extns self.auth_mechanisms = auths self.supports_esmtp = True return code, message async def help(self, command_name=None): """ Sends a SMTP 'HELP' command. For further details please check out `RFC 5321 § 4.1.1.8`_. Args: command_name (str or None, optional): Name of a command for which you want help. For example, if you want to get help about the '*RSET*' command, you'd call ``help('RSET')``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the HELP command fails. Returns: Help text as given by the server. .. _`RFC 5321 § 4.1.1.8`: https://tools.ietf.org/html/rfc5321#section-4.1.1.8 """ if command_name is None: command_name = "" code, message = await self.do_cmd("HELP", command_name) return message async def rset(self): """ Sends a SMTP 'RSET' command. - Resets the session. For further details, please check out `RFC 5321 § 4.1.1.5`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RSET command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.5`: https://tools.ietf.org/html/rfc5321#section-4.1.1.5 """ return await self.do_cmd("RSET") async def noop(self): """ Sends a SMTP 'NOOP' command. - Doesn't do anything. For further details, please check out `RFC 5321 § 4.1.1.9`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the NOOP command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.9`: https://tools.ietf.org/html/rfc5321#section-4.1.1.9 """ return await self.do_cmd("NOOP") async def vrfy(self, address): """ Sends a SMTP 'VRFY' command. - Tests the validity of the given address. For further details, please check out `RFC 5321 § 4.1.1.6`_. Args: address (str): E-mail address to be checked. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the VRFY command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.6`: https://tools.ietf.org/html/rfc5321#section-4.1.1.6 """ return await self.do_cmd("VRFY", address) async def expn(self, address): """ Sends a SMTP 'EXPN' command. - Expands a mailing-list. For further details, please check out `RFC 5321 § 4.1.1.7`_. Args: address (str): E-mail address to expand. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the EXPN command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.7`: https://tools.ietf.org/html/rfc5321#section-4.1.1.7 """ return await self.do_cmd("EXPN", address) async def rcpt(self, recipient, options=None): """ Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. options (list of str or None, optional): Additional options to send along with the *RCPT* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RCPT command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.3`: https://tools.ietf.org/html/rfc5321#section-4.1.1.3 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] to_addr = "TO:{}".format(quoteaddr(recipient)) code, message = await self.do_cmd("RCPT", to_addr, *options) return code, message async def quit(self): """ Sends a SMTP 'QUIT' command. - Ends the session. For further details, please check out `RFC 5321 § 4.1.1.10`_. Returns: (int, str): A (code, message) 2-tuple containing the server response. If the connection is already closed when calling this method, returns (-1, None). .. _`RFC 5321 § 4.1.1.10`: https://tools.ietf.org/html/rfc5321#section-4.1.1.10 """ code = -1 message = None try: code, message = await self.do_cmd("QUIT") except ConnectionError: # We voluntarily ignore this kind of exceptions since... the # connection seems already closed. pass except SMTPCommandFailedError: pass await self.close() return code, message async def data(self, email_message): """ Sends a SMTP 'DATA' command. - Transmits the message to the server. If ``email_message`` is a bytes object, sends it as it is. Else, makes all the required changes so it can be safely trasmitted to the SMTP server.` For further details, please check out `RFC 5321 § 4.1.1.4`_. Args: email_message (str or bytes): Message to be sent. Raises: ConnectionError subclass: If the connection to the server is unexpectedely lost. SMTPCommandFailedError: If the DATA command fails. Returns: (int, str): A (code, message) 2-tuple containing the server last response (the one the server sent after all data were sent by the client). .. seealso: :meth:`SMTP.prepare_message` .. _`RFC 5321 § 4.1.1.4`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 """ code, message = await self.do_cmd("DATA", success=(354,)) email_message = SMTP.prepare_message(email_message) self.writer.write(email_message) # write is non-blocking. await self.writer.drain() # don't forget to drain. code, message = await self.reader.read_reply() return code, message async def auth(self, username, password): """ Tries to authenticate user against the SMTP server. Args: username (str): Username to authenticate with. password (str): Password to use along with the given ``username``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPLoginError: If the authentication failed (either because all attempts failed or because there was no suitable authentication mechanism). Returns: (int, str): A (code, message) 2-tuple containing the last server response. """ # EHLO/HELO is required: await self.ehlo_or_helo_if_needed() errors = [] # To store SMTPAuthenticationErrors code = message = None # Try to authenticate using all mechanisms supported by both # server and client (and only these): for auth, meth in self.__class__._supported_auth_mechanisms.items(): if auth in self.auth_mechanisms: auth_func = getattr(self, meth) try: code, message = await auth_func(username, password) except SMTPAuthenticationError as e: errors.append(e) else: break else: if not errors: err = "Could not find any suitable authentication mechanism." errors.append(SMTPAuthenticationError(-1, err)) raise SMTPLoginError(errors) return code, message async def starttls(self, context=None): """ Upgrades the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports SSL/TLS, this will encrypt the rest of the SMTP session. Raises: SMTPCommandNotSupportedError: If the server does not support STARTTLS. SMTPCommandFailedError: If the STARTTLS command fails BadImplementationError: If the connection does not use aioopenssl. Args: context (:obj:`OpenSSL.SSL.Context`): SSL context Returns: (int, message): A (code, message) 2-tuple containing the server response. """ if not self.use_aioopenssl: raise BadImplementationError("This connection does not use aioopenssl") import aioopenssl import OpenSSL await self.ehlo_or_helo_if_needed() if "starttls" not in self.esmtp_extensions: raise SMTPCommandNotSupportedError("STARTTLS") code, message = await self.do_cmd("STARTTLS", success=(220,)) # Don't check for code, do_cmd did it if context is None: context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD) await self.transport.starttls(ssl_context=context) # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. # FIXME: wouldn't it be better to use reset_state here ? # And reset self.reader, self.writer and self.transport just after # Maybe also self.ssl_context ? self.last_ehlo_response = (None, None) self.last_helo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] return (code, message) async def sendmail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while sending message.") >>> else: >>> print("Result: {}.".format(r)) >>> except ConnectionError as e: >>> print(e) Result: {}. Args: sender (str): E-mail address of the sender. recipients (list of str or str): E-mail(s) address(es) of the recipient(s). message (str or bytes): Message body. mail_options (list of str): ESMTP options (such as *8BITMIME*) to send along the *MAIL* command. rcpt_options (list of str): ESMTP options (such as *DSN*) to send along all the *RCPT* commands. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPCommandFailedError: If the server refuses our MAIL command. SMTPCommandFailedError: If the server refuses our DATA command. SMTPNoRecipientError: If the server refuses all given recipients. Returns: dict: A dict containing an entry for each recipient that was refused. Each entry is associated with a (code, message) 2-tuple containing the error code and message, as returned by the server. When everythign runs smoothly, the returning dict is empty. .. note:: The connection remains open after. It's your responsibility to close it. A good practice is to use the asynchronous context manager instead. See :meth:`SMTP.__aenter__` for further details. """ # Make sure `recipients` is a list: if isinstance(recipients, str): recipients = [recipients] # Set some defaults values: if mail_options is None: mail_options = [] if rcpt_options is None: rcpt_options = [] # EHLO or HELO is required: await self.ehlo_or_helo_if_needed() if self.supports_esmtp: if "size" in self.esmtp_extensions: mail_options.append("size={}".format(len(message))) await self.mail(sender, mail_options) errors = [] for recipient in recipients: try: await self.rcpt(recipient, rcpt_options) except SMTPCommandFailedError as e: errors.append(e) if len(recipients) == len(errors): # The server refused all our recipients: raise SMTPNoRecipientError(errors) await self.data(message) # If we got here then somebody got our mail: return errors async def send_mail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Alias for :meth:`SMTP.sendmail`. """ return await self.sendmail( sender, recipients, message, mail_options, rcpt_options ) async def ehlo_or_helo_if_needed(self): """ Calls :meth:`SMTP.ehlo` and/or :meth:`SMTP.helo` if needed. If there hasn't been any previous *EHLO* or *HELO* command this session, tries to initiate the session. *EHLO* is tried first. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. """ no_helo = self.last_helo_response == (None, None) no_ehlo = self.last_ehlo_response == (None, None) if no_helo and no_ehlo: try: # First we try EHLO: await self.ehlo() except SMTPCommandFailedError: # EHLO failed, let's try HELO: await self.helo() async def close(self): """ Cleans up after the connection to the SMTP server has been closed (voluntarily or not). """ if self.writer is not None: # Close the transport: try: self.writer.close() except OSError as exc: if exc.errno != errno.ENOTCONN: raise self.reset_state() async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challenge is hashed using HMAC-MD5 and the user password as key (shared secret) ; 3) The hashed challenge is converted to a string of lowercase hexadecimal digits ; 4) The username and a space character are prepended to the hex digits ; 5) The concatenation is base64-encoded and sent to the server. 6) If the server replies with a return code of 235, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "CRAM-MD5" code, message = await self.do_cmd("AUTH", mechanism, success=(334,)) decoded_challenge = base64.b64decode(message) challenge_hash = hmac.new( key=password.encode("utf-8"), msg=decoded_challenge, digestmod="md5" ) hex_hash = challenge_hash.hexdigest() response = "{} {}".format(username, hex_hash) encoded_response = SMTP.b64enc(response) try: code, message = await self.do_cmd(encoded_response, success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_login(self, username, password): """ Performs an authentication attempt using the LOGIN mechanism. Protocol: 1. The username is base64-encoded ; 2. The string 'AUTH LOGIN' and a space character are prepended to the base64-encoded username and sent to the server ; 3. If the server replies with a 334 return code, we can go on: 1) The password is base64-encoded and sent to the server ; 2) If the server replies with a 235 return code, the user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "LOGIN" code, message = await self.do_cmd( "AUTH", mechanism, SMTP.b64enc(username), success=(334,) ) try: code, message = await self.do_cmd(SMTP.b64enc(password), success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_plain(self, username, password): """ Performs an authentication attempt using the PLAIN mechanism. Protocol: 1. Format the username and password in a suitable way ; 2. The formatted string is base64-encoded ; 3. The string 'AUTH PLAIN' and a space character are prepended to the base64-encoded username and password and sent to the server ; 4. If the server replies with a 235 return code, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "PLAIN" credentials = "\0{}\0{}".format(username, password) encoded_credentials = SMTP.b64enc(credentials) try: code, message = await self.do_cmd( "AUTH", mechanism, encoded_credentials, success=(235, 503) ) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message @staticmethod def parse_esmtp_extensions(message): """ Parses the response given by an ESMTP server after a *EHLO* command. The response is parsed to build: - A dict of supported ESMTP extensions (with parameters, if any). - A list of supported authentication methods. Returns: (dict, list): A (extensions, auth_mechanisms) 2-tuple containing the supported extensions and authentication methods. """ extns = {} auths = [] oldstyle_auth_regex = re.compile(r"auth=(?P<auth>.*)", re.IGNORECASE) extension_regex = re.compile( r"(?P<feature>[a-z0-9][a-z0-9\-]*) ?", re.IGNORECASE ) lines = message.splitlines() for line in lines[1:]: # To be able to communicate with as many SMTP servers as possible, # we have to take the old-style auth advertisement into account. match = oldstyle_auth_regex.match(line) if match: auth = match.group("auth")[0] auth = auth.lower().strip() if auth not in auths: auths.append(auth) # RFC 1869 requires a space between EHLO keyword and parameters. # It's actually stricter, in that only spaces are allowed between # parameters, but were not going to check for that here. # Note that the space isn't present if there are no parameters. match = extension_regex.match(line) if match: feature = match.group("feature").lower() params = match.string[match.end("feature") :].strip() extns[feature] = params if feature == "auth": auths.extend([param.strip().lower() for param in params.split()]) return extns, auths @staticmethod def prepare_message(message): """ Returns the given message encoded in ascii with a format suitable for SMTP transmission: - Makes sure the message is ASCII encoded ; - Normalizes line endings to '\r\n' ; - Adds a (second) period at the beginning of lines that start with a period ; - Makes sure the message ends with '\r\n.\r\n'. For further details, please check out RFC 5321 `§ 4.1.1.4`_ and `§ 4.5.2`_. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 .. _`§ 4.5.2`: https://tools.ietf.org/html/rfc5321#section-4.5.2 """ if isinstance(message, bytes): bytes_message = message else: bytes_message = message.encode("ascii") # The original algorithm uses regexes to do this stuff. # This one is -IMHO- more pythonic and it is slightly faster. # # Another version is even faster, but I chose to keep something # more pythonic and readable. # FYI, the fastest way to do all this stuff seems to be # (according to my benchmarks): # # bytes_message.replace(b"\r\n", b"\n") \ # .replace(b"\r", b"\n") \ # .replace(b"\n", b"\r\n") # # DOT_LINE_REGEX = re.compile(rb"^\.", re.MULTILINE) # bytes_message = DOT_LINE_REGEX.sub(b"..", bytes_message) # # if not bytes_message.endswith(b"\r\n"): # bytes_message += b"\r\n" # # bytes_message += b"\r\n.\r\n" lines = [] for line in bytes_message.splitlines(): if line.startswith(b"."): line = line.replace(b".", b"..", 1) lines.append(line) # Recompose the message with <CRLF> only: bytes_message = b"\r\n".join(lines) # Make sure message ends with <CRLF>.<CRLF>: bytes_message += b"\r\n.\r\n" return bytes_message @staticmethod def b64enc(s): """ Base64-encodes the given string and returns it as a :obj:`str`. This is a simple helper function that takes a str, base64-encodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: s (str): String to be converted to base64. Returns: str: A base64-encoded string. """ return base64.b64encode(s.encode("utf-8")).decode("utf-8") @staticmethod def b64dec(b): """ Base64-decodes the given :obj:`bytes` and converts it to a :obj:`str`. This is a simple helper function that takes a bytes, base64-decodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: b (bytes): A base64-encoded bytes. Returns: str: A base64-decoded string. """ return base64.b64decode(b).decode("utf-8")
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.rcpt
python
async def rcpt(self, recipient, options=None): if options is None: options = [] to_addr = "TO:{}".format(quoteaddr(recipient)) code, message = await self.do_cmd("RCPT", to_addr, *options) return code, message
Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. options (list of str or None, optional): Additional options to send along with the *RCPT* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RCPT command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.3`: https://tools.ietf.org/html/rfc5321#section-4.1.1.3 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3
train
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L519-L549
[ "async def do_cmd(self, *args, success=None):\n \"\"\"\n Sends the given command to the server.\n\n Args:\n *args: Command and arguments to be sent to the server.\n\n Raises:\n ConnectionResetError: If the connection with the server is\n unexpectedely lost.\n SMTPCommandF...
class SMTP: """ SMTP or ESMTP client. This should follow RFC 5321 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP Authentication) and RFC 2487 (Secure SMTP over TLS). Attributes: hostname (str): Hostname of the SMTP server we are connecting to. port (int): Port on which the SMTP server listens for connections. timeout (int): Not used. last_helo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *HELO* response. last_ehlo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *EHLO* response. supports_esmtp (bool): True if the server supports ESMTP (set after a *EHLO* command, False otherwise. esmtp_extensions (dict): ESMTP extensions and parameters supported by the SMTP server (set after a *EHLO* command). auth_mechanisms (list of str): Authentication mechanisms supported by the SMTP server. ssl_context (bool): Always False. (Used in SMTP_SSL subclass) reader (:class:`streams.SMTPStreamReader`): SMTP stream reader, used to read server responses. writer (:class:`streams.SMTPStreamWriter`): SMTP stream writer, used to send commands to the server. transport (:class:`asyncio.BaseTransport`): Communication channel abstraction between client and server. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): If True, the connection is made using the aioopenssl module. Defaults to False. _fqdn (str): Client FQDN. Used to identify the client to the server. Class Attributes: _default_port (int): Default port to use. Defaults to 25. _supported_auth_mechanisms (dict): Dict containing the information about supported authentication mechanisms, ordered by preference of use. The entries consist in : - The authentication mechanism name, in lowercase, as given by SMTP servers. - The name of the method to call to authenticate using the mechanism. """ _default_port = 25 _supported_auth_mechanisms = { "cram-md5": "_auth_cram_md5", "plain": "_auth_plain", "login": "_auth_login", } def __init__( self, hostname="localhost", port=_default_port, fqdn=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, loop=None, use_aioopenssl=False, ): """ Initializes a new :class:`SMTP` instance. Args: hostname (str): Hostname of the SMTP server to connect to. port (int): Port to use to connect to the SMTP server. fqdn (str or None): Client Fully Qualified Domain Name. This is used to identify the client to the server. timeout (int): Not used. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): Use the aioopenssl module to open the connection. This is mandatory if you plan on using STARTTLS. """ self.hostname = hostname try: self.port = int(port) except ValueError: self.port = self.__class__._default_port self.timeout = timeout self._fqdn = fqdn self.loop = loop or asyncio.get_event_loop() self.use_aioopenssl = use_aioopenssl self.reset_state() @property def fqdn(self): """ Returns the string used to identify the client when initiating a SMTP session. RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do: - Use the client FQDN ; - If it isn't available, we SHOULD fall back to an address literal. Returns: str: The value that should be used as the client FQDN. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 .. _`§ 4.1.3`: https//tools.ietf.org/html/rfc5321#section-4.1.3 """ if self._fqdn is None: # Let's try to retrieve it: self._fqdn = socket.getfqdn() if "." not in self._fqdn: try: info = socket.getaddrinfo( host="localhost", port=None, proto=socket.IPPROTO_TCP ) except socket.gaierror: addr = "127.0.0.1" else: # We only consider the first returned result and we're # only interested in getting the IP(v4 or v6) address: addr = info[0][4][0] self._fqdn = "[{}]".format(addr) return self._fqdn def reset_state(self): """ Resets some attributes to their default values. This is especially useful when initializing a newly created :class:`SMTP` instance and when closing an existing SMTP session. It allows us to use the same SMTP instance and connect several times. """ self.last_helo_response = (None, None) self.last_ehlo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] self.ssl_context = False self.reader = None self.writer = None self.transport = None async def __aenter__(self): """ Enters the asynchronous context manager. Also tries to connect to the server. Raises: SMTPConnectionRefusedError: If the connection between client and SMTP server can not be established. .. seealso:: :meth:`SMTP.connect` """ await self.connect() return self async def __aexit__(self, *args): """ Exits the asynchronous context manager. Closes the connection and resets instance attributes. .. seealso:: :meth:`SMTP.quit` """ await self.quit() async def connect(self): """ Connects to the server. .. note:: This method is automatically invoked by :meth:`SMTP.__aenter__`. The code is mostly borrowed from the :func:`asyncio.streams.open_connection` source code. Raises: ConnectionError subclass: If the connection between client and SMTP server can not be established. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ # First build the reader: self.reader = SMTPStreamReader(loop=self.loop) # Then build the protocol: protocol = asyncio.StreamReaderProtocol(self.reader, loop=self.loop) # With the just-built reader and protocol, create the connection and # get the transport stream: conn = { "protocol_factory": lambda: protocol, "host": self.hostname, "port": self.port, } if self.use_aioopenssl: conn.update( { "use_starttls": not self.ssl_context, "ssl_context_factory": lambda transport: self.ssl_context, "server_hostname": self.hostname, # For SSL } ) import aioopenssl # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await aioopenssl.create_starttls_connection( self.loop, **conn ) # HACK: aioopenssl transports don't implement is_closing, and thus drain() fails... self.transport.is_closing = lambda: False else: conn["ssl"] = self.ssl_context # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await self.loop.create_connection(**conn) # If the connection has been established, build the writer: self.writer = SMTPStreamWriter(self.transport, protocol, self.reader, self.loop) code, message = await self.reader.read_reply() if code != 220: raise ConnectionRefusedError(code, message) return code, message async def do_cmd(self, *args, success=None): """ Sends the given command to the server. Args: *args: Command and arguments to be sent to the server. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ if success is None: success = (250,) cmd = " ".join(args) await self.writer.send_command(cmd) code, message = await self.reader.read_reply() if code not in success: raise SMTPCommandFailedError(code, message, cmd) return code, message async def helo(self, from_host=None): """ Sends a SMTP 'HELO' command. - Identifies the client and starts the session. If given ``from_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our HELO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("HELO", from_host) self.last_helo_response = (code, message) return code, message async def ehlo(self, from_host=None): """ Sends a SMTP 'EHLO' command. - Identifies the client and starts the session. If given ``from`_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("EHLO", from_host) self.last_ehlo_response = (code, message) extns, auths = SMTP.parse_esmtp_extensions(message) self.esmtp_extensions = extns self.auth_mechanisms = auths self.supports_esmtp = True return code, message async def help(self, command_name=None): """ Sends a SMTP 'HELP' command. For further details please check out `RFC 5321 § 4.1.1.8`_. Args: command_name (str or None, optional): Name of a command for which you want help. For example, if you want to get help about the '*RSET*' command, you'd call ``help('RSET')``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the HELP command fails. Returns: Help text as given by the server. .. _`RFC 5321 § 4.1.1.8`: https://tools.ietf.org/html/rfc5321#section-4.1.1.8 """ if command_name is None: command_name = "" code, message = await self.do_cmd("HELP", command_name) return message async def rset(self): """ Sends a SMTP 'RSET' command. - Resets the session. For further details, please check out `RFC 5321 § 4.1.1.5`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RSET command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.5`: https://tools.ietf.org/html/rfc5321#section-4.1.1.5 """ return await self.do_cmd("RSET") async def noop(self): """ Sends a SMTP 'NOOP' command. - Doesn't do anything. For further details, please check out `RFC 5321 § 4.1.1.9`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the NOOP command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.9`: https://tools.ietf.org/html/rfc5321#section-4.1.1.9 """ return await self.do_cmd("NOOP") async def vrfy(self, address): """ Sends a SMTP 'VRFY' command. - Tests the validity of the given address. For further details, please check out `RFC 5321 § 4.1.1.6`_. Args: address (str): E-mail address to be checked. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the VRFY command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.6`: https://tools.ietf.org/html/rfc5321#section-4.1.1.6 """ return await self.do_cmd("VRFY", address) async def expn(self, address): """ Sends a SMTP 'EXPN' command. - Expands a mailing-list. For further details, please check out `RFC 5321 § 4.1.1.7`_. Args: address (str): E-mail address to expand. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the EXPN command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.7`: https://tools.ietf.org/html/rfc5321#section-4.1.1.7 """ return await self.do_cmd("EXPN", address) async def mail(self, sender, options=None): """ Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] from_addr = "FROM:{}".format(quoteaddr(sender)) code, message = await self.do_cmd("MAIL", from_addr, *options) return code, message async def quit(self): """ Sends a SMTP 'QUIT' command. - Ends the session. For further details, please check out `RFC 5321 § 4.1.1.10`_. Returns: (int, str): A (code, message) 2-tuple containing the server response. If the connection is already closed when calling this method, returns (-1, None). .. _`RFC 5321 § 4.1.1.10`: https://tools.ietf.org/html/rfc5321#section-4.1.1.10 """ code = -1 message = None try: code, message = await self.do_cmd("QUIT") except ConnectionError: # We voluntarily ignore this kind of exceptions since... the # connection seems already closed. pass except SMTPCommandFailedError: pass await self.close() return code, message async def data(self, email_message): """ Sends a SMTP 'DATA' command. - Transmits the message to the server. If ``email_message`` is a bytes object, sends it as it is. Else, makes all the required changes so it can be safely trasmitted to the SMTP server.` For further details, please check out `RFC 5321 § 4.1.1.4`_. Args: email_message (str or bytes): Message to be sent. Raises: ConnectionError subclass: If the connection to the server is unexpectedely lost. SMTPCommandFailedError: If the DATA command fails. Returns: (int, str): A (code, message) 2-tuple containing the server last response (the one the server sent after all data were sent by the client). .. seealso: :meth:`SMTP.prepare_message` .. _`RFC 5321 § 4.1.1.4`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 """ code, message = await self.do_cmd("DATA", success=(354,)) email_message = SMTP.prepare_message(email_message) self.writer.write(email_message) # write is non-blocking. await self.writer.drain() # don't forget to drain. code, message = await self.reader.read_reply() return code, message async def auth(self, username, password): """ Tries to authenticate user against the SMTP server. Args: username (str): Username to authenticate with. password (str): Password to use along with the given ``username``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPLoginError: If the authentication failed (either because all attempts failed or because there was no suitable authentication mechanism). Returns: (int, str): A (code, message) 2-tuple containing the last server response. """ # EHLO/HELO is required: await self.ehlo_or_helo_if_needed() errors = [] # To store SMTPAuthenticationErrors code = message = None # Try to authenticate using all mechanisms supported by both # server and client (and only these): for auth, meth in self.__class__._supported_auth_mechanisms.items(): if auth in self.auth_mechanisms: auth_func = getattr(self, meth) try: code, message = await auth_func(username, password) except SMTPAuthenticationError as e: errors.append(e) else: break else: if not errors: err = "Could not find any suitable authentication mechanism." errors.append(SMTPAuthenticationError(-1, err)) raise SMTPLoginError(errors) return code, message async def starttls(self, context=None): """ Upgrades the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports SSL/TLS, this will encrypt the rest of the SMTP session. Raises: SMTPCommandNotSupportedError: If the server does not support STARTTLS. SMTPCommandFailedError: If the STARTTLS command fails BadImplementationError: If the connection does not use aioopenssl. Args: context (:obj:`OpenSSL.SSL.Context`): SSL context Returns: (int, message): A (code, message) 2-tuple containing the server response. """ if not self.use_aioopenssl: raise BadImplementationError("This connection does not use aioopenssl") import aioopenssl import OpenSSL await self.ehlo_or_helo_if_needed() if "starttls" not in self.esmtp_extensions: raise SMTPCommandNotSupportedError("STARTTLS") code, message = await self.do_cmd("STARTTLS", success=(220,)) # Don't check for code, do_cmd did it if context is None: context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD) await self.transport.starttls(ssl_context=context) # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. # FIXME: wouldn't it be better to use reset_state here ? # And reset self.reader, self.writer and self.transport just after # Maybe also self.ssl_context ? self.last_ehlo_response = (None, None) self.last_helo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] return (code, message) async def sendmail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while sending message.") >>> else: >>> print("Result: {}.".format(r)) >>> except ConnectionError as e: >>> print(e) Result: {}. Args: sender (str): E-mail address of the sender. recipients (list of str or str): E-mail(s) address(es) of the recipient(s). message (str or bytes): Message body. mail_options (list of str): ESMTP options (such as *8BITMIME*) to send along the *MAIL* command. rcpt_options (list of str): ESMTP options (such as *DSN*) to send along all the *RCPT* commands. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPCommandFailedError: If the server refuses our MAIL command. SMTPCommandFailedError: If the server refuses our DATA command. SMTPNoRecipientError: If the server refuses all given recipients. Returns: dict: A dict containing an entry for each recipient that was refused. Each entry is associated with a (code, message) 2-tuple containing the error code and message, as returned by the server. When everythign runs smoothly, the returning dict is empty. .. note:: The connection remains open after. It's your responsibility to close it. A good practice is to use the asynchronous context manager instead. See :meth:`SMTP.__aenter__` for further details. """ # Make sure `recipients` is a list: if isinstance(recipients, str): recipients = [recipients] # Set some defaults values: if mail_options is None: mail_options = [] if rcpt_options is None: rcpt_options = [] # EHLO or HELO is required: await self.ehlo_or_helo_if_needed() if self.supports_esmtp: if "size" in self.esmtp_extensions: mail_options.append("size={}".format(len(message))) await self.mail(sender, mail_options) errors = [] for recipient in recipients: try: await self.rcpt(recipient, rcpt_options) except SMTPCommandFailedError as e: errors.append(e) if len(recipients) == len(errors): # The server refused all our recipients: raise SMTPNoRecipientError(errors) await self.data(message) # If we got here then somebody got our mail: return errors async def send_mail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Alias for :meth:`SMTP.sendmail`. """ return await self.sendmail( sender, recipients, message, mail_options, rcpt_options ) async def ehlo_or_helo_if_needed(self): """ Calls :meth:`SMTP.ehlo` and/or :meth:`SMTP.helo` if needed. If there hasn't been any previous *EHLO* or *HELO* command this session, tries to initiate the session. *EHLO* is tried first. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. """ no_helo = self.last_helo_response == (None, None) no_ehlo = self.last_ehlo_response == (None, None) if no_helo and no_ehlo: try: # First we try EHLO: await self.ehlo() except SMTPCommandFailedError: # EHLO failed, let's try HELO: await self.helo() async def close(self): """ Cleans up after the connection to the SMTP server has been closed (voluntarily or not). """ if self.writer is not None: # Close the transport: try: self.writer.close() except OSError as exc: if exc.errno != errno.ENOTCONN: raise self.reset_state() async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challenge is hashed using HMAC-MD5 and the user password as key (shared secret) ; 3) The hashed challenge is converted to a string of lowercase hexadecimal digits ; 4) The username and a space character are prepended to the hex digits ; 5) The concatenation is base64-encoded and sent to the server. 6) If the server replies with a return code of 235, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "CRAM-MD5" code, message = await self.do_cmd("AUTH", mechanism, success=(334,)) decoded_challenge = base64.b64decode(message) challenge_hash = hmac.new( key=password.encode("utf-8"), msg=decoded_challenge, digestmod="md5" ) hex_hash = challenge_hash.hexdigest() response = "{} {}".format(username, hex_hash) encoded_response = SMTP.b64enc(response) try: code, message = await self.do_cmd(encoded_response, success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_login(self, username, password): """ Performs an authentication attempt using the LOGIN mechanism. Protocol: 1. The username is base64-encoded ; 2. The string 'AUTH LOGIN' and a space character are prepended to the base64-encoded username and sent to the server ; 3. If the server replies with a 334 return code, we can go on: 1) The password is base64-encoded and sent to the server ; 2) If the server replies with a 235 return code, the user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "LOGIN" code, message = await self.do_cmd( "AUTH", mechanism, SMTP.b64enc(username), success=(334,) ) try: code, message = await self.do_cmd(SMTP.b64enc(password), success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_plain(self, username, password): """ Performs an authentication attempt using the PLAIN mechanism. Protocol: 1. Format the username and password in a suitable way ; 2. The formatted string is base64-encoded ; 3. The string 'AUTH PLAIN' and a space character are prepended to the base64-encoded username and password and sent to the server ; 4. If the server replies with a 235 return code, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "PLAIN" credentials = "\0{}\0{}".format(username, password) encoded_credentials = SMTP.b64enc(credentials) try: code, message = await self.do_cmd( "AUTH", mechanism, encoded_credentials, success=(235, 503) ) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message @staticmethod def parse_esmtp_extensions(message): """ Parses the response given by an ESMTP server after a *EHLO* command. The response is parsed to build: - A dict of supported ESMTP extensions (with parameters, if any). - A list of supported authentication methods. Returns: (dict, list): A (extensions, auth_mechanisms) 2-tuple containing the supported extensions and authentication methods. """ extns = {} auths = [] oldstyle_auth_regex = re.compile(r"auth=(?P<auth>.*)", re.IGNORECASE) extension_regex = re.compile( r"(?P<feature>[a-z0-9][a-z0-9\-]*) ?", re.IGNORECASE ) lines = message.splitlines() for line in lines[1:]: # To be able to communicate with as many SMTP servers as possible, # we have to take the old-style auth advertisement into account. match = oldstyle_auth_regex.match(line) if match: auth = match.group("auth")[0] auth = auth.lower().strip() if auth not in auths: auths.append(auth) # RFC 1869 requires a space between EHLO keyword and parameters. # It's actually stricter, in that only spaces are allowed between # parameters, but were not going to check for that here. # Note that the space isn't present if there are no parameters. match = extension_regex.match(line) if match: feature = match.group("feature").lower() params = match.string[match.end("feature") :].strip() extns[feature] = params if feature == "auth": auths.extend([param.strip().lower() for param in params.split()]) return extns, auths @staticmethod def prepare_message(message): """ Returns the given message encoded in ascii with a format suitable for SMTP transmission: - Makes sure the message is ASCII encoded ; - Normalizes line endings to '\r\n' ; - Adds a (second) period at the beginning of lines that start with a period ; - Makes sure the message ends with '\r\n.\r\n'. For further details, please check out RFC 5321 `§ 4.1.1.4`_ and `§ 4.5.2`_. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 .. _`§ 4.5.2`: https://tools.ietf.org/html/rfc5321#section-4.5.2 """ if isinstance(message, bytes): bytes_message = message else: bytes_message = message.encode("ascii") # The original algorithm uses regexes to do this stuff. # This one is -IMHO- more pythonic and it is slightly faster. # # Another version is even faster, but I chose to keep something # more pythonic and readable. # FYI, the fastest way to do all this stuff seems to be # (according to my benchmarks): # # bytes_message.replace(b"\r\n", b"\n") \ # .replace(b"\r", b"\n") \ # .replace(b"\n", b"\r\n") # # DOT_LINE_REGEX = re.compile(rb"^\.", re.MULTILINE) # bytes_message = DOT_LINE_REGEX.sub(b"..", bytes_message) # # if not bytes_message.endswith(b"\r\n"): # bytes_message += b"\r\n" # # bytes_message += b"\r\n.\r\n" lines = [] for line in bytes_message.splitlines(): if line.startswith(b"."): line = line.replace(b".", b"..", 1) lines.append(line) # Recompose the message with <CRLF> only: bytes_message = b"\r\n".join(lines) # Make sure message ends with <CRLF>.<CRLF>: bytes_message += b"\r\n.\r\n" return bytes_message @staticmethod def b64enc(s): """ Base64-encodes the given string and returns it as a :obj:`str`. This is a simple helper function that takes a str, base64-encodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: s (str): String to be converted to base64. Returns: str: A base64-encoded string. """ return base64.b64encode(s.encode("utf-8")).decode("utf-8") @staticmethod def b64dec(b): """ Base64-decodes the given :obj:`bytes` and converts it to a :obj:`str`. This is a simple helper function that takes a bytes, base64-decodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: b (bytes): A base64-encoded bytes. Returns: str: A base64-decoded string. """ return base64.b64decode(b).decode("utf-8")
hwmrocker/smtplibaio
smtplibaio/smtp.py
SMTP.quit
python
async def quit(self): code = -1 message = None try: code, message = await self.do_cmd("QUIT") except ConnectionError: # We voluntarily ignore this kind of exceptions since... the # connection seems already closed. pass except SMTPCommandFailedError: pass await self.close() return code, message
Sends a SMTP 'QUIT' command. - Ends the session. For further details, please check out `RFC 5321 § 4.1.1.10`_. Returns: (int, str): A (code, message) 2-tuple containing the server response. If the connection is already closed when calling this method, returns (-1, None). .. _`RFC 5321 § 4.1.1.10`: https://tools.ietf.org/html/rfc5321#section-4.1.1.10
train
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L551-L578
[ "async def do_cmd(self, *args, success=None):\n \"\"\"\n Sends the given command to the server.\n\n Args:\n *args: Command and arguments to be sent to the server.\n\n Raises:\n ConnectionResetError: If the connection with the server is\n unexpectedely lost.\n SMTPCommandF...
class SMTP: """ SMTP or ESMTP client. This should follow RFC 5321 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP Authentication) and RFC 2487 (Secure SMTP over TLS). Attributes: hostname (str): Hostname of the SMTP server we are connecting to. port (int): Port on which the SMTP server listens for connections. timeout (int): Not used. last_helo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *HELO* response. last_ehlo_response ((int or None, str or None)): A (code, message) 2-tuple containing the last *EHLO* response. supports_esmtp (bool): True if the server supports ESMTP (set after a *EHLO* command, False otherwise. esmtp_extensions (dict): ESMTP extensions and parameters supported by the SMTP server (set after a *EHLO* command). auth_mechanisms (list of str): Authentication mechanisms supported by the SMTP server. ssl_context (bool): Always False. (Used in SMTP_SSL subclass) reader (:class:`streams.SMTPStreamReader`): SMTP stream reader, used to read server responses. writer (:class:`streams.SMTPStreamWriter`): SMTP stream writer, used to send commands to the server. transport (:class:`asyncio.BaseTransport`): Communication channel abstraction between client and server. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): If True, the connection is made using the aioopenssl module. Defaults to False. _fqdn (str): Client FQDN. Used to identify the client to the server. Class Attributes: _default_port (int): Default port to use. Defaults to 25. _supported_auth_mechanisms (dict): Dict containing the information about supported authentication mechanisms, ordered by preference of use. The entries consist in : - The authentication mechanism name, in lowercase, as given by SMTP servers. - The name of the method to call to authenticate using the mechanism. """ _default_port = 25 _supported_auth_mechanisms = { "cram-md5": "_auth_cram_md5", "plain": "_auth_plain", "login": "_auth_login", } def __init__( self, hostname="localhost", port=_default_port, fqdn=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, loop=None, use_aioopenssl=False, ): """ Initializes a new :class:`SMTP` instance. Args: hostname (str): Hostname of the SMTP server to connect to. port (int): Port to use to connect to the SMTP server. fqdn (str or None): Client Fully Qualified Domain Name. This is used to identify the client to the server. timeout (int): Not used. loop (:class:`asyncio.BaseEventLoop`): Event loop to use. use_aioopenssl (bool): Use the aioopenssl module to open the connection. This is mandatory if you plan on using STARTTLS. """ self.hostname = hostname try: self.port = int(port) except ValueError: self.port = self.__class__._default_port self.timeout = timeout self._fqdn = fqdn self.loop = loop or asyncio.get_event_loop() self.use_aioopenssl = use_aioopenssl self.reset_state() @property def fqdn(self): """ Returns the string used to identify the client when initiating a SMTP session. RFC 5321 `§ 4.1.1.1`_ and `§ 4.1.3`_ tell us what to do: - Use the client FQDN ; - If it isn't available, we SHOULD fall back to an address literal. Returns: str: The value that should be used as the client FQDN. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 .. _`§ 4.1.3`: https//tools.ietf.org/html/rfc5321#section-4.1.3 """ if self._fqdn is None: # Let's try to retrieve it: self._fqdn = socket.getfqdn() if "." not in self._fqdn: try: info = socket.getaddrinfo( host="localhost", port=None, proto=socket.IPPROTO_TCP ) except socket.gaierror: addr = "127.0.0.1" else: # We only consider the first returned result and we're # only interested in getting the IP(v4 or v6) address: addr = info[0][4][0] self._fqdn = "[{}]".format(addr) return self._fqdn def reset_state(self): """ Resets some attributes to their default values. This is especially useful when initializing a newly created :class:`SMTP` instance and when closing an existing SMTP session. It allows us to use the same SMTP instance and connect several times. """ self.last_helo_response = (None, None) self.last_ehlo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] self.ssl_context = False self.reader = None self.writer = None self.transport = None async def __aenter__(self): """ Enters the asynchronous context manager. Also tries to connect to the server. Raises: SMTPConnectionRefusedError: If the connection between client and SMTP server can not be established. .. seealso:: :meth:`SMTP.connect` """ await self.connect() return self async def __aexit__(self, *args): """ Exits the asynchronous context manager. Closes the connection and resets instance attributes. .. seealso:: :meth:`SMTP.quit` """ await self.quit() async def connect(self): """ Connects to the server. .. note:: This method is automatically invoked by :meth:`SMTP.__aenter__`. The code is mostly borrowed from the :func:`asyncio.streams.open_connection` source code. Raises: ConnectionError subclass: If the connection between client and SMTP server can not be established. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ # First build the reader: self.reader = SMTPStreamReader(loop=self.loop) # Then build the protocol: protocol = asyncio.StreamReaderProtocol(self.reader, loop=self.loop) # With the just-built reader and protocol, create the connection and # get the transport stream: conn = { "protocol_factory": lambda: protocol, "host": self.hostname, "port": self.port, } if self.use_aioopenssl: conn.update( { "use_starttls": not self.ssl_context, "ssl_context_factory": lambda transport: self.ssl_context, "server_hostname": self.hostname, # For SSL } ) import aioopenssl # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await aioopenssl.create_starttls_connection( self.loop, **conn ) # HACK: aioopenssl transports don't implement is_closing, and thus drain() fails... self.transport.is_closing = lambda: False else: conn["ssl"] = self.ssl_context # This may raise a ConnectionError exception, which we let bubble up. self.transport, _ = await self.loop.create_connection(**conn) # If the connection has been established, build the writer: self.writer = SMTPStreamWriter(self.transport, protocol, self.reader, self.loop) code, message = await self.reader.read_reply() if code != 220: raise ConnectionRefusedError(code, message) return code, message async def do_cmd(self, *args, success=None): """ Sends the given command to the server. Args: *args: Command and arguments to be sent to the server. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ if success is None: success = (250,) cmd = " ".join(args) await self.writer.send_command(cmd) code, message = await self.reader.read_reply() if code not in success: raise SMTPCommandFailedError(code, message, cmd) return code, message async def helo(self, from_host=None): """ Sends a SMTP 'HELO' command. - Identifies the client and starts the session. If given ``from_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our HELO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("HELO", from_host) self.last_helo_response = (code, message) return code, message async def ehlo(self, from_host=None): """ Sends a SMTP 'EHLO' command. - Identifies the client and starts the session. If given ``from`_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host (str or None): Name to use to identify the client. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO greeting. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.1 """ if from_host is None: from_host = self.fqdn code, message = await self.do_cmd("EHLO", from_host) self.last_ehlo_response = (code, message) extns, auths = SMTP.parse_esmtp_extensions(message) self.esmtp_extensions = extns self.auth_mechanisms = auths self.supports_esmtp = True return code, message async def help(self, command_name=None): """ Sends a SMTP 'HELP' command. For further details please check out `RFC 5321 § 4.1.1.8`_. Args: command_name (str or None, optional): Name of a command for which you want help. For example, if you want to get help about the '*RSET*' command, you'd call ``help('RSET')``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the HELP command fails. Returns: Help text as given by the server. .. _`RFC 5321 § 4.1.1.8`: https://tools.ietf.org/html/rfc5321#section-4.1.1.8 """ if command_name is None: command_name = "" code, message = await self.do_cmd("HELP", command_name) return message async def rset(self): """ Sends a SMTP 'RSET' command. - Resets the session. For further details, please check out `RFC 5321 § 4.1.1.5`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RSET command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.5`: https://tools.ietf.org/html/rfc5321#section-4.1.1.5 """ return await self.do_cmd("RSET") async def noop(self): """ Sends a SMTP 'NOOP' command. - Doesn't do anything. For further details, please check out `RFC 5321 § 4.1.1.9`_. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the NOOP command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.9`: https://tools.ietf.org/html/rfc5321#section-4.1.1.9 """ return await self.do_cmd("NOOP") async def vrfy(self, address): """ Sends a SMTP 'VRFY' command. - Tests the validity of the given address. For further details, please check out `RFC 5321 § 4.1.1.6`_. Args: address (str): E-mail address to be checked. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the VRFY command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.6`: https://tools.ietf.org/html/rfc5321#section-4.1.1.6 """ return await self.do_cmd("VRFY", address) async def expn(self, address): """ Sends a SMTP 'EXPN' command. - Expands a mailing-list. For further details, please check out `RFC 5321 § 4.1.1.7`_. Args: address (str): E-mail address to expand. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the EXPN command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.7`: https://tools.ietf.org/html/rfc5321#section-4.1.1.7 """ return await self.do_cmd("EXPN", address) async def mail(self, sender, options=None): """ Sends a SMTP 'MAIL' command. - Starts the mail transfer session. For further details, please check out `RFC 5321 § 4.1.1.2`_ and `§ 3.3`_. Args: sender (str): Sender mailbox (used as reverse-path). options (list of str or None, optional): Additional options to send along with the *MAIL* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the MAIL command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.2`: https://tools.ietf.org/html/rfc5321#section-4.1.1.2 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] from_addr = "FROM:{}".format(quoteaddr(sender)) code, message = await self.do_cmd("MAIL", from_addr, *options) return code, message async def rcpt(self, recipient, options=None): """ Sends a SMTP 'RCPT' command. - Indicates a recipient for the e-mail. For further details, please check out `RFC 5321 § 4.1.1.3`_ and `§ 3.3`_. Args: recipient (str): E-mail address of one recipient. options (list of str or None, optional): Additional options to send along with the *RCPT* command. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the RCPT command fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. .. _`RFC 5321 § 4.1.1.3`: https://tools.ietf.org/html/rfc5321#section-4.1.1.3 .. _`§ 3.3`: https://tools.ietf.org/html/rfc5321#section-3.3 """ if options is None: options = [] to_addr = "TO:{}".format(quoteaddr(recipient)) code, message = await self.do_cmd("RCPT", to_addr, *options) return code, message async def data(self, email_message): """ Sends a SMTP 'DATA' command. - Transmits the message to the server. If ``email_message`` is a bytes object, sends it as it is. Else, makes all the required changes so it can be safely trasmitted to the SMTP server.` For further details, please check out `RFC 5321 § 4.1.1.4`_. Args: email_message (str or bytes): Message to be sent. Raises: ConnectionError subclass: If the connection to the server is unexpectedely lost. SMTPCommandFailedError: If the DATA command fails. Returns: (int, str): A (code, message) 2-tuple containing the server last response (the one the server sent after all data were sent by the client). .. seealso: :meth:`SMTP.prepare_message` .. _`RFC 5321 § 4.1.1.4`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 """ code, message = await self.do_cmd("DATA", success=(354,)) email_message = SMTP.prepare_message(email_message) self.writer.write(email_message) # write is non-blocking. await self.writer.drain() # don't forget to drain. code, message = await self.reader.read_reply() return code, message async def auth(self, username, password): """ Tries to authenticate user against the SMTP server. Args: username (str): Username to authenticate with. password (str): Password to use along with the given ``username``. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPLoginError: If the authentication failed (either because all attempts failed or because there was no suitable authentication mechanism). Returns: (int, str): A (code, message) 2-tuple containing the last server response. """ # EHLO/HELO is required: await self.ehlo_or_helo_if_needed() errors = [] # To store SMTPAuthenticationErrors code = message = None # Try to authenticate using all mechanisms supported by both # server and client (and only these): for auth, meth in self.__class__._supported_auth_mechanisms.items(): if auth in self.auth_mechanisms: auth_func = getattr(self, meth) try: code, message = await auth_func(username, password) except SMTPAuthenticationError as e: errors.append(e) else: break else: if not errors: err = "Could not find any suitable authentication mechanism." errors.append(SMTPAuthenticationError(-1, err)) raise SMTPLoginError(errors) return code, message async def starttls(self, context=None): """ Upgrades the connection to the SMTP server into TLS mode. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server supports SSL/TLS, this will encrypt the rest of the SMTP session. Raises: SMTPCommandNotSupportedError: If the server does not support STARTTLS. SMTPCommandFailedError: If the STARTTLS command fails BadImplementationError: If the connection does not use aioopenssl. Args: context (:obj:`OpenSSL.SSL.Context`): SSL context Returns: (int, message): A (code, message) 2-tuple containing the server response. """ if not self.use_aioopenssl: raise BadImplementationError("This connection does not use aioopenssl") import aioopenssl import OpenSSL await self.ehlo_or_helo_if_needed() if "starttls" not in self.esmtp_extensions: raise SMTPCommandNotSupportedError("STARTTLS") code, message = await self.do_cmd("STARTTLS", success=(220,)) # Don't check for code, do_cmd did it if context is None: context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_2_METHOD) await self.transport.starttls(ssl_context=context) # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. # FIXME: wouldn't it be better to use reset_state here ? # And reset self.reader, self.writer and self.transport just after # Maybe also self.ssl_context ? self.last_ehlo_response = (None, None) self.last_helo_response = (None, None) self.supports_esmtp = False self.esmtp_extensions = {} self.auth_mechanisms = [] return (code, message) async def sendmail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Performs an entire e-mail transaction. Example: >>> try: >>> with SMTP() as client: >>> try: >>> r = client.sendmail(sender, recipients, message) >>> except SMTPException: >>> print("Error while sending message.") >>> else: >>> print("Result: {}.".format(r)) >>> except ConnectionError as e: >>> print(e) Result: {}. Args: sender (str): E-mail address of the sender. recipients (list of str or str): E-mail(s) address(es) of the recipient(s). message (str or bytes): Message body. mail_options (list of str): ESMTP options (such as *8BITMIME*) to send along the *MAIL* command. rcpt_options (list of str): ESMTP options (such as *DSN*) to send along all the *RCPT* commands. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. SMTPCommandFailedError: If the server refuses our MAIL command. SMTPCommandFailedError: If the server refuses our DATA command. SMTPNoRecipientError: If the server refuses all given recipients. Returns: dict: A dict containing an entry for each recipient that was refused. Each entry is associated with a (code, message) 2-tuple containing the error code and message, as returned by the server. When everythign runs smoothly, the returning dict is empty. .. note:: The connection remains open after. It's your responsibility to close it. A good practice is to use the asynchronous context manager instead. See :meth:`SMTP.__aenter__` for further details. """ # Make sure `recipients` is a list: if isinstance(recipients, str): recipients = [recipients] # Set some defaults values: if mail_options is None: mail_options = [] if rcpt_options is None: rcpt_options = [] # EHLO or HELO is required: await self.ehlo_or_helo_if_needed() if self.supports_esmtp: if "size" in self.esmtp_extensions: mail_options.append("size={}".format(len(message))) await self.mail(sender, mail_options) errors = [] for recipient in recipients: try: await self.rcpt(recipient, rcpt_options) except SMTPCommandFailedError as e: errors.append(e) if len(recipients) == len(errors): # The server refused all our recipients: raise SMTPNoRecipientError(errors) await self.data(message) # If we got here then somebody got our mail: return errors async def send_mail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): """ Alias for :meth:`SMTP.sendmail`. """ return await self.sendmail( sender, recipients, message, mail_options, rcpt_options ) async def ehlo_or_helo_if_needed(self): """ Calls :meth:`SMTP.ehlo` and/or :meth:`SMTP.helo` if needed. If there hasn't been any previous *EHLO* or *HELO* command this session, tries to initiate the session. *EHLO* is tried first. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPCommandFailedError: If the server refuses our EHLO/HELO greeting. """ no_helo = self.last_helo_response == (None, None) no_ehlo = self.last_ehlo_response == (None, None) if no_helo and no_ehlo: try: # First we try EHLO: await self.ehlo() except SMTPCommandFailedError: # EHLO failed, let's try HELO: await self.helo() async def close(self): """ Cleans up after the connection to the SMTP server has been closed (voluntarily or not). """ if self.writer is not None: # Close the transport: try: self.writer.close() except OSError as exc: if exc.errno != errno.ENOTCONN: raise self.reset_state() async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent by the server) is base64-decoded ; 2) The decoded challenge is hashed using HMAC-MD5 and the user password as key (shared secret) ; 3) The hashed challenge is converted to a string of lowercase hexadecimal digits ; 4) The username and a space character are prepended to the hex digits ; 5) The concatenation is base64-encoded and sent to the server. 6) If the server replies with a return code of 235, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "CRAM-MD5" code, message = await self.do_cmd("AUTH", mechanism, success=(334,)) decoded_challenge = base64.b64decode(message) challenge_hash = hmac.new( key=password.encode("utf-8"), msg=decoded_challenge, digestmod="md5" ) hex_hash = challenge_hash.hexdigest() response = "{} {}".format(username, hex_hash) encoded_response = SMTP.b64enc(response) try: code, message = await self.do_cmd(encoded_response, success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_login(self, username, password): """ Performs an authentication attempt using the LOGIN mechanism. Protocol: 1. The username is base64-encoded ; 2. The string 'AUTH LOGIN' and a space character are prepended to the base64-encoded username and sent to the server ; 3. If the server replies with a 334 return code, we can go on: 1) The password is base64-encoded and sent to the server ; 2) If the server replies with a 235 return code, the user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "LOGIN" code, message = await self.do_cmd( "AUTH", mechanism, SMTP.b64enc(username), success=(334,) ) try: code, message = await self.do_cmd(SMTP.b64enc(password), success=(235, 503)) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message async def _auth_plain(self, username, password): """ Performs an authentication attempt using the PLAIN mechanism. Protocol: 1. Format the username and password in a suitable way ; 2. The formatted string is base64-encoded ; 3. The string 'AUTH PLAIN' and a space character are prepended to the base64-encoded username and password and sent to the server ; 4. If the server replies with a 235 return code, user is authenticated. Args: username (str): Identifier of the user trying to authenticate. password (str): Password for the user. Raises: ConnectionResetError: If the connection with the server is unexpectedely lost. SMTPAuthenticationError: If the authentication attempt fails. Returns: (int, str): A (code, message) 2-tuple containing the server response. """ mechanism = "PLAIN" credentials = "\0{}\0{}".format(username, password) encoded_credentials = SMTP.b64enc(credentials) try: code, message = await self.do_cmd( "AUTH", mechanism, encoded_credentials, success=(235, 503) ) except SMTPCommandFailedError as e: raise SMTPAuthenticationError(e.code, e.message, mechanism) return code, message @staticmethod def parse_esmtp_extensions(message): """ Parses the response given by an ESMTP server after a *EHLO* command. The response is parsed to build: - A dict of supported ESMTP extensions (with parameters, if any). - A list of supported authentication methods. Returns: (dict, list): A (extensions, auth_mechanisms) 2-tuple containing the supported extensions and authentication methods. """ extns = {} auths = [] oldstyle_auth_regex = re.compile(r"auth=(?P<auth>.*)", re.IGNORECASE) extension_regex = re.compile( r"(?P<feature>[a-z0-9][a-z0-9\-]*) ?", re.IGNORECASE ) lines = message.splitlines() for line in lines[1:]: # To be able to communicate with as many SMTP servers as possible, # we have to take the old-style auth advertisement into account. match = oldstyle_auth_regex.match(line) if match: auth = match.group("auth")[0] auth = auth.lower().strip() if auth not in auths: auths.append(auth) # RFC 1869 requires a space between EHLO keyword and parameters. # It's actually stricter, in that only spaces are allowed between # parameters, but were not going to check for that here. # Note that the space isn't present if there are no parameters. match = extension_regex.match(line) if match: feature = match.group("feature").lower() params = match.string[match.end("feature") :].strip() extns[feature] = params if feature == "auth": auths.extend([param.strip().lower() for param in params.split()]) return extns, auths @staticmethod def prepare_message(message): """ Returns the given message encoded in ascii with a format suitable for SMTP transmission: - Makes sure the message is ASCII encoded ; - Normalizes line endings to '\r\n' ; - Adds a (second) period at the beginning of lines that start with a period ; - Makes sure the message ends with '\r\n.\r\n'. For further details, please check out RFC 5321 `§ 4.1.1.4`_ and `§ 4.5.2`_. .. _`§ 4.1.1.1`: https://tools.ietf.org/html/rfc5321#section-4.1.1.4 .. _`§ 4.5.2`: https://tools.ietf.org/html/rfc5321#section-4.5.2 """ if isinstance(message, bytes): bytes_message = message else: bytes_message = message.encode("ascii") # The original algorithm uses regexes to do this stuff. # This one is -IMHO- more pythonic and it is slightly faster. # # Another version is even faster, but I chose to keep something # more pythonic and readable. # FYI, the fastest way to do all this stuff seems to be # (according to my benchmarks): # # bytes_message.replace(b"\r\n", b"\n") \ # .replace(b"\r", b"\n") \ # .replace(b"\n", b"\r\n") # # DOT_LINE_REGEX = re.compile(rb"^\.", re.MULTILINE) # bytes_message = DOT_LINE_REGEX.sub(b"..", bytes_message) # # if not bytes_message.endswith(b"\r\n"): # bytes_message += b"\r\n" # # bytes_message += b"\r\n.\r\n" lines = [] for line in bytes_message.splitlines(): if line.startswith(b"."): line = line.replace(b".", b"..", 1) lines.append(line) # Recompose the message with <CRLF> only: bytes_message = b"\r\n".join(lines) # Make sure message ends with <CRLF>.<CRLF>: bytes_message += b"\r\n.\r\n" return bytes_message @staticmethod def b64enc(s): """ Base64-encodes the given string and returns it as a :obj:`str`. This is a simple helper function that takes a str, base64-encodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: s (str): String to be converted to base64. Returns: str: A base64-encoded string. """ return base64.b64encode(s.encode("utf-8")).decode("utf-8") @staticmethod def b64dec(b): """ Base64-decodes the given :obj:`bytes` and converts it to a :obj:`str`. This is a simple helper function that takes a bytes, base64-decodes it and returns it as str. :mod:`base64` functions are working with :obj:`bytes`, hence this func. Args: b (bytes): A base64-encoded bytes. Returns: str: A base64-decoded string. """ return base64.b64decode(b).decode("utf-8")