source: sandbox/m2crypto_session.py @ 1719:560867ae70f0

Last change on this file since 1719:560867ae70f0 was 1719:560867ae70f0, checked in by Stefan Schwarzer <sschwarzer@…>, 8 months ago
Remove `encoding: utf-8` lines These are no longer needed because we code for only Python 3 now and Python 3 uses UTF-8 encoding for source files by default.
File size: 1.3 KB
Line 
1# Copyright (C) 2014-2018, Stefan Schwarzer
2
3"""
4Session factory class for use with M2Crypto.
5
6Different from Python's `ftplib.FTP_TLS`, `M2Crypto.ftpslib.FTP_TLS`
7uses a special socket object. This object's `sendall` method doesn't
8work as expected for unicode arguments.
9
10This module provides a workaround by wrapping the socket object so
11that the argument to `sendall` is converted to a byte string before
12being used.
13
14See ticket #78 for details.
15"""
16
17import M2Crypto
18
19import ftputil.tool
20
21
22class M2CryptoSession(M2Crypto.ftpslib.FTP_TLS):
23
24    # Argument names as in `ftplib.FTP_TLS`.
25    def __init__(self, host, user, passwd):
26        # Can't use `super` because `M2Crypto.ftpslib.FTP_TLS` is a
27        # classic class.
28        M2Crypto.ftpslib.FTP_TLS.__init__(self)
29        self.connect(host, 21)
30        self.auth_tls()
31        self.login(user, passwd)
32        self.prot_p()
33        self._fix_socket()
34
35    def _fix_socket(self):
36        """
37        Change the socket object so that arguments to `sendall`
38        are converted to byte strings before being used.
39        """
40        original_sendall = self.sock.sendall
41        # Bound method, therefore no `self` argument.
42        def sendall(data):
43            data = ftputil.tool.as_bytes(data)
44            return original_sendall(data)
45        self.sock.sendall = sendall
Note: See TracBrowser for help on using the repository browser.