source: sandbox/m2crypto_session.py @ 1713:f146a1ea66aa

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