source: sandbox/m2crypto_session.py @ 1485:20df4fdbedc9

Last change on this file since 1485:20df4fdbedc9 was 1485:20df4fdbedc9, checked in by Stefan Schwarzer <sschwarzer@…>, 5 years ago
M2Crypto session factory as workaround for ticket #78.
File size: 1.4 KB
Line 
1# encoding: utf-8
2# Copyright (C) 2014, 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
18from __future__ import unicode_literals
19
20import M2Crypto
21
22import ftputil.tool
23
24
25class M2CryptoSession(M2Crypto.ftpslib.FTP_TLS):
26
27    # Argument names as in `ftplib.FTP_TLS`.
28    def __init__(self, host, user, passwd):
29        # Can't use `super` because `M2Crypto.ftpslib.FTP_TLS` is a
30        # classic class.
31        M2Crypto.ftpslib.FTP_TLS.__init__(self)
32        self.connect(host, 21)
33        self.auth_tls()
34        self.login(user, passwd)
35        self.prot_p()
36        self._fix_socket()
37
38    def _fix_socket(self):
39        """
40        Change the socket object so that arguments to `sendall`
41        are converted to byte strings before being used.
42        """
43        original_sendall = self.sock.sendall
44        # Bound method, therefore no `self` argument.
45        def sendall(data):
46            data = ftputil.tool.as_bytes(data)
47            return original_sendall(data)
48        self.sock.sendall = sendall
Note: See TracBrowser for help on using the repository browser.