-
Notifications
You must be signed in to change notification settings - Fork 1
/
misc.py
1919 lines (1623 loc) · 58 KB
/
misc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
@author: Fabio Erculiani <lxnay@sabayon.org>
@contact: lxnay@sabayon.org
@copyright: Fabio Erculiani
@license: GPL-2
B{Entropy Framework miscellaneous module}.
This module contains miscellaneous classes, not directly
related with the "Entropy metaphor".
"""
import os
import sys
import time
import fcntl
import signal
import errno
import codecs
import contextlib
from entropy.const import const_is_python3
if const_is_python3():
import urllib.request, urllib.error, urllib.parse
UrllibBaseHandler = urllib.request.BaseHandler
else:
import urllib
import urllib2
UrllibBaseHandler = urllib2.BaseHandler
import logging
import threading
from collections import deque
from entropy.const import etpConst, const_isunicode, \
const_isfileobj, const_convert_log_level, const_setup_file
from entropy.exceptions import EntropyException
import entropy.tools
class Lifo(object):
"""
This class can be used to build LIFO buffers, also commonly
known as "stacks". I{Lifo} allows you to store and retrieve
Python objects from its stack, in a very smart way.
This implementation is much faster than the one provided
by Python (queue module) and more sofisticated.
Sample code:
>>> # load Lifo
>>> from entropy.misc import Lifo
>>> stack = Lifo()
>>> item1 = set([1,2,3])
>>> item2 = ["a","b", "c"]
>>> item3 = None
>>> item4 = 1
>>> stack.push(item4)
>>> stack.push(item3)
>>> stack.push(item2)
>>> stack.push(item1)
>>> stack.is_filled()
True
# discarding all the item matching int(1) in the stack
>>> stack.discard(1)
>>> item3 is stack.pop()
True
>>> item2 is stack.pop()
True
>>> item1 is stack.pop()
True
>>> stack.pop()
ValueError exception (stack is empty)
>>> stack.is_filled()
False
>>> del stack
"""
def __init__(self):
""" Lifo class constructor """
object.__init__(self)
self.__buf = deque()
def __nonzero__(self):
"""
Return if stack is empty.
"""
return len(self.__buf) != 0
def __len__(self):
"""
Return stack size.
"""
return len(self.__buf)
def push(self, item):
"""
Push an object into the stack.
@param item: any Python object
@type item: Python object
@return: None
@rtype: None
"""
self.__buf.append(item)
def insert(self, item):
"""
Insert item at the bottom of the stack.
@param item: any Python object
@type item: Python object
@return: None
@rtype: None
"""
self.__buf.appendleft(item)
def clear(self):
"""
Clear the stack.
@return: None
@rtype: None
"""
self.__buf.clear()
def is_filled(self):
"""
Tell whether Lifo contains data that can be popped out.
@return: fill status
@rtype: bool
"""
if self.__buf:
return True
return False
def discard(self, entry):
"""
Remove given object from stack. Any matching object,
through identity and == comparison will be removed.
@param entry: object in stack
@type entry: any Python object
@return: None
@rtype: None
"""
indexes = []
while True:
try:
self.__buf.remove(entry)
except ValueError:
break
def pop(self):
"""
Pop the uppermost item of the stack out of it.
@return: object stored in the stack
@rtype: any Python object
@raise ValueError: if stack is empty
"""
try:
return self.__buf.pop()
except IndexError:
raise ValueError("Lifo is empty")
class TimeScheduled(threading.Thread):
"""
Multithreading class that wraps Python threading.Thread.
Specifically, this class implements the timed function execution
concept. It means that you can run timed functions (say every N
seconds) and control its execution through another (main?) thread.
It is possible to set arbitrary, variable, delays and decide if to delay
before or after the execution of the function provided at construction
time.
Timed function can be stopped by calling TimeScheduled.kill() method.
You may find the example below more exhaustive:
>>> from entropy.misc import TimeScheduled
>>> time_sched = TimeSheduled(5, print, "hello world", 123)
>>> time_sched.start()
hello world 123 # every 5 seconds
hello world 123 # every 5 seconds
hello world 123 # every 5 seconds
>>> time_sched.kill()
"""
def __init__(self, delay, *args, **kwargs):
"""
TimeScheduled constructor.
@param delay: delay in seconds between a function call and another.
@type delay: float
@param *args: function as first magic arg and its arguments
@keyword *kwargs: keyword arguments of the function passed
@return: None
@rtype: None
"""
threading.Thread.__init__(self)
self.__f = args[0]
self.__delay = delay
self.__args = args[1:][:]
self.__kwargs = kwargs.copy()
# never enable this by default
# otherwise kill() and thread
# check will hang until
# time.sleep() is done
self.__accurate = False
self.__delay_before = False
self.__alive = 0
self.__paused = False
self.__paused_delay = 2
self.__state_sem = threading.Semaphore(0)
self.__killed = False
self.__kill_status = threading.Lock()
def start(self):
"""
Override Thread.start() to handle the internal
state semaphore.
"""
self.__alive = 1
# send the signal to kill, now it can reliably change
# self.__alive
self.__state_sem.release()
return super(TimeScheduled, self).start()
def pause(self, pause):
"""
Pause current internal timer countdown.
@param pause: True to pause timer
@type pause: bool
"""
self.__paused = pause
def set_delay(self, delay):
"""
Change current delay in seconds.
@param delay: new delay
@type delay: float
@return: None
@rtype: None
"""
self.__delay = delay
def set_delay_before(self, delay_before):
"""
Set whether delay before the execution of the function or not.
@param delay_before: delay before boolean
@type delay_before: bool
@return: None
@rtype: None
"""
self.__delay_before = bool(delay_before)
def set_accuracy(self, accuracy):
"""
Set whether delay function must be accurate or not.
@param accuracy: accuracy boolean
@type accuracy: bool
@return: None
@rtype: None
"""
self.__accurate = bool(accuracy)
def run(self):
"""
This method is called automatically when start() is called.
Don't call this directly!!!
"""
while self.__alive:
if self.__delay_before:
do_break = self.__do_delay()
if do_break:
break
if self.__f == None:
break
try:
self.__f(*self.__args, **self.__kwargs)
except KeyboardInterrupt:
break
if not self.__delay_before:
do_break = self.__do_delay()
if do_break:
break
def __do_delay(self):
""" Executes the delay """
while self.__paused:
if time == None:
return True
time.sleep(self.__paused_delay)
if not self.__accurate:
if float == None:
return True
mydelay = float(self.__delay)
t_frac = 0.3
while mydelay > 0.0:
if not self.__alive:
return True
if time == None:
return True # shut down?
time.sleep(t_frac)
mydelay -= t_frac
else:
if time == None:
return True # shut down?
time.sleep(self.__delay)
return False
def kill(self):
""" Stop the execution of the timed function """
if self.__alive == 0:
# never started?
return
with self.__kill_status:
if self.__killed:
# kill already called
return
self.__killed = True
self.__state_sem.acquire()
# at this point run() is called or start() hasn't been called
# we're allowed to kill
self.__alive = 0
class DirectoryMonitor:
"""
DirectoryMonitor uses Linux dnotify facility to signal
file change events for the monitored directory.
However, this class attaches the event callback to SIGIO,
thus it is not safe to have multiple instances of it around
because there is no real event dispatching.
"""
# A File in the dir has been read
DN_ACCESS = fcntl.DN_ACCESS
# A File has been modified (w, t)
DN_MODIFY = fcntl.DN_MODIFY
# A File has been created
DN_CREATE = fcntl.DN_CREATE
# A File has been deleted
DN_DELETE = fcntl.DN_DELETE
# A File has been renamed
DN_RENAME = fcntl.DN_RENAME
# A file has got its attrs changed (perms, ownership)
DN_ATTRIB = fcntl.DN_ATTRIB
# Keep signaling until the handler is explicitly removed
DN_MULTISHOT = fcntl.DN_MULTISHOT
def __init__(self, directory_paths, callback, event_flags=None):
"""
DirectoryMonitor constructor.
@param directory_paths: list of paths of the directories to monitor
@type directory_paths: list
@param callback: function called on events. The signature is:
void function()
@type callback: function
@keyword event_flags: specify an alternative flag mask, default is:
DN_ACCESS | DN_MODIFY | DN_CREATE | DN_DELETE | DN_RENAME
| DN_ATTRIB
@type event_flags: int
"""
self._directory_paths = directory_paths
self._signal_id = signal.SIGIO
self._callback = callback
if event_flags:
self._flags = event_flags
else:
self._flags = self.DN_ACCESS | self.DN_MODIFY | \
self.DN_CREATE | self.DN_DELETE | self.DN_RENAME | \
self.DN_ATTRIB
self._fds = []
for directory_path in self._directory_paths:
fd = os.open(directory_path, os.O_RDONLY)
fcntl.fcntl(fd, fcntl.F_NOTIFY, self._flags)
self._fds.append(fd)
def _forward(signum, frame):
self._callback()
signal.signal(self._signal_id, _forward)
def close(self):
"""
Terminate the listeners and release all the allocated resources.
"""
if self._fds:
signal.signal(self._signal_id, signal.SIG_DFL)
for fd in self._fds:
os.close(fd)
class ParallelTask(threading.Thread):
"""
Multithreading class that wraps Python threading.Thread.
Specifically, this class makes possible to easily execute a function
on a separate thread.
Python threads can't be stopped, paused or more generically arbitrarily
controlled.
>>> from entropy.misc import ParallelTask
>>> parallel = ParallelTask(print, "hello world", 123)
>>> parallel.start()
hello world 123
>>> parallel.kill()
"""
def __init__(self, *args, **kwargs):
"""
ParallelTask constructor
Provide a function and its arguments as arguments of this constructor.
"""
super(ParallelTask, self).__init__()
self.__function, self.__args = args[0], args[1:]
self.__kwargs = kwargs.copy()
self.__rc = None
def run(self):
"""
This method is called automatically when start() is called.
Don't call this directly!!!
"""
self.__rc = self.__function(*self.__args, **self.__kwargs)
def get_function(self):
"""
Return the function passed to constructor that is going to be executed.
@return: parallel function
@rtype: Python callable object
"""
return self.__function
def get_rc(self):
"""
Return result of the last parallel function call passed to constructor.
@return: parallel function result
@rtype: Python object
"""
return self.__rc
class ReadersWritersSemaphore(object):
"""
A simple Readers Writers Lock object.
Inspired by:
http://code.activestate.com/recipes/\
577803-reader-writer-lock-with-priority-for-writers/
and by: Mateusz Kobos
"""
class SemaphoreWrapper(object):
def __init__(self):
self.__counter = 0
self.__mutex = threading.Lock()
def acquire(self, lock):
with self.__mutex:
self.__counter += 1
if self.__counter == 1:
lock.acquire()
def try_acquire(self, lock):
with self.__mutex:
self.__counter += 1
acquired = True
if self.__counter == 1:
acquired = lock.acquire(False)
if not acquired:
self.__counter -= 1
return acquired
def release(self, lock):
with self.__mutex:
self.__counter -= 1
if self.__counter == 0:
lock.release()
def __init__(self):
self.__read_switch = self.SemaphoreWrapper()
self.__write_switch = self.SemaphoreWrapper()
self.__no_readers = threading.Semaphore()
self.__no_writers = threading.Semaphore()
self.__readers_queue = threading.Semaphore()
def reader_acquire(self):
"""
Acquire the Reader end.
"""
with self.__readers_queue:
with self.__no_readers:
self.__read_switch.acquire(self.__no_writers)
def try_reader_acquire(self):
"""
Acquire the Reader end in non-blocking mode.
"""
with self.__readers_queue:
acquired = self.__no_readers.acquire(False)
if acquired:
acquired = self.__read_switch.try_acquire(
self.__no_writers)
self.__no_readers.release()
return acquired
def reader_release(self):
"""
Release the Reader end.
"""
self.__read_switch.release(self.__no_writers)
def writer_acquire(self):
"""
Acquire the Writer end.
"""
self.__write_switch.acquire(self.__no_readers)
self.__no_writers.acquire()
def try_writer_acquire(self):
"""
Acquire the Writer end in non-blocking mode.
"""
acquired = self.__write_switch.try_acquire(self.__no_readers)
if acquired:
acquired = self.__no_writers.acquire(False)
if not acquired:
self.__write_switch.release(self.__no_readers)
return acquired
def writer_release(self):
"""
Release Writer end.
"""
self.__no_writers.release()
self.__write_switch.release(self.__no_readers)
@contextlib.contextmanager
def reader(self):
"""
Acquire the Reader end.
"""
self.reader_acquire()
try:
yield
finally:
self.reader_release()
@contextlib.contextmanager
def writer(self):
"""
Acquire the Writer end.
"""
self.writer_acquire()
try:
yield
finally:
self.writer_release()
class FlockFile(object):
"""
Of flock() operations on a file.
"""
class FlockFileInitFailure(EntropyException):
"""
FlockFile initialization failure exception.
Can be raised either because file path does
not exist (missing directory) or permissions
are not sufficient.
"""
def __init__(self, file_path, fd = None, fobj = None):
self._wait_msg_cb = None
self._acquired_msg_cb = None
self._path = file_path
if fobj:
self._f = fobj
elif fd:
self._f = os.fdopen(fd)
else:
try:
self._f = open(self._path, "a+")
except IOError as err:
if err.errno in (errno.ENOENT, errno.EACCES):
raise FlockFile.FlockFileInitFailure(err)
raise
@contextlib.contextmanager
def shared(self):
"""
Acquire the lock in shared mode (context manager).
"""
acquired = False
try:
acquired = self.try_acquire_shared()
if not acquired:
if self._wait_msg_cb:
self._wait_msg_cb(self, False)
self.acquire_shared()
acquired = True
if self._acquired_msg_cb:
self._acquired_msg_cb(self, False)
yield
finally:
if acquired:
self.release()
@contextlib.contextmanager
def exclusive(self):
"""
Acquire the lock in exclusive mode.
"""
acquired = False
try:
acquired = self.try_acquire_exclusive()
if not acquired:
if self._wait_msg_cb:
self._wait_msg_cb(self, True)
self.acquire_exclusive()
acquired = True
if self._acquired_msg_cb:
self._acquired_msg_cb(self, True)
yield
finally:
if acquired:
self.release()
def acquire_shared(self):
"""
Acquire the lock in shared mode.
"""
flags = fcntl.LOCK_SH
while True:
try:
fcntl.flock(self._f.fileno(), flags)
except (IOError, OSError) as err:
if err.errno == errno.EINTR:
# interrupted system call
continue
self.close()
raise
break
def try_acquire_shared(self):
"""
Acquire the lock in shared mode, non blocking.
@return: True, if lock acquired.
@rtype: bool
"""
flags = fcntl.LOCK_SH | fcntl.LOCK_NB
try:
fcntl.flock(self._f.fileno(), flags)
except (IOError, OSError) as err:
if err.errno == errno.EINTR:
return False
if err.errno not in (errno.EACCES, errno.EAGAIN,):
# ouch, wtf?
self.close()
raise
return False
return True
def acquire_exclusive(self):
"""
Acquire the lock in exclusive mode.
"""
flags = fcntl.LOCK_EX
while True:
try:
fcntl.flock(self._f.fileno(), flags)
except (IOError, OSError) as err:
if err.errno == errno.EINTR:
# interrupted system call
continue
self.close()
raise
break
def try_acquire_exclusive(self):
"""
Acquire the lock in exclusive mode, non blocking.
@return: True, if lock acquired.
@rtype: bool
"""
flags = fcntl.LOCK_EX | fcntl.LOCK_NB
try:
fcntl.flock(self._f.fileno(), flags)
except (IOError, OSError) as err:
if err.errno == errno.EINTR:
return False
if err.errno not in (errno.EACCES, errno.EAGAIN,):
# ouch, wtf?
self.close()
raise
return False
return True
def promote(self):
"""
Promote a lock acquired in shared mode to exclusive mode.
"""
self.acquire_shared()
self.acquire_exclusive()
def try_promote(self):
"""
Promote a lock acquired in shared mode to exclusive mode,
non blocking.
"""
acquired = self.try_acquire_shared()
if not acquired:
return False
acquired = self.try_acquire_exclusive()
if not acquired:
return False
return True
def demote(self):
"""
Demote a lock acquired in exclusive mode to shared mode.
"""
self.release()
self.acquire_shared()
def release(self):
"""
Release the lock previously acquired.
"""
fcntl.flock(self._f.fileno(), fcntl.LOCK_UN)
def get_path(self):
"""
Return the file path associated with this instance.
"""
return self._path
def get_file(self):
"""
Get the underlying File Object.
Use at your own risk.
"""
return self._f
def close(self):
"""
Close the underlying file object.
"""
self._f.close()
class EmailSender:
"""
This class implements a very simple e-mail (through SMTP) sender.
It is used by the User Generated Content interface and something more.
You can swap the sender function at runtime, by redefining
EmailSender.default_sender. By default, default_sender is set to
EmailSender.smtp_send.
Sample code:
>>> sender = EmailSender()
>>> sender.send_text_email("me@test.com", ["him@test.com"], "hello!",
"this is the content")
...
>>> sender = EmailSender()
>>> sender.send_mime_email("me@test.com", ["him@test.com"], "hello!",
"this is the content", ["/path/to/file1", "/path/to/file2"])
"""
def __init__(self):
""" EmailSender constructor """
import smtplib
self.smtplib = smtplib
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
import mimetypes
self.smtpuser = None
self.smtppassword = None
self.smtphost = 'localhost'
self.smtpport = 25
self.text = MIMEText
self.mimefile = MIMEBase
self.audio = MIMEAudio
self.image = MIMEImage
self.multipart = MIMEMultipart
self.default_sender = self.smtp_send
self.mimetypes = mimetypes
self.encoders = encoders
self.message = Message
def smtp_send(self, sender, destinations, message):
"""
This is the default method for sending emails.
It uses Python's smtplib module.
You should not use this function directly.
@param sender: sender email address
@type sender: string
@param destinations: list of recipients
@type destinations: list of string
@param message: message to send
@type message: string
@return: None
@rtype: None
"""
s_srv = self.smtplib.SMTP(self.smtphost, self.smtpport)
if self.smtpuser and self.smtppassword:
s_srv.login(self.smtpuser, self.smtppassword)
s_srv.sendmail(sender, destinations, message)
s_srv.quit()
def send_text_email(self, sender_email, destination_emails, subject,
content):
"""
This method exposes an easy way to send textual emails.
@param sender_email: sender email address
@type sender_email: string
@param destination_emails: list of recipients
@type destination_emails: list
@param subject: email subject
@type subject: string
@param content: email content
@type content: string
@return: None
@rtype: None
"""
# Create a text/plain message
if not const_is_python3():
if const_isunicode(content):
content = content.encode('utf-8')
if const_isunicode(subject):
subject = subject.encode('utf-8')
else:
if not const_isunicode(content):
raise AttributeError("content must be unicode (str)")
if not const_isunicode(subject):
raise AttributeError("subject must be unicode (str)")
msg = self.text(content)
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = ', '.join(destination_emails)
return self.default_sender(sender_email, destination_emails,
msg.as_string())
def send_mime_email(self, sender_email, destination_emails, subject,
content, files):
"""
This method exposes an easy way to send complex emails (with
attachments).
@param sender_email: sender email address
@type sender_email: string
@param destination_emails: list of recipients
@type destination_emails: list of string
@param subject: email subject
@type subject: string
@param content: email content
@type content: string
@param files: list of valid file paths
@type files: list
@return: None
@rtype: None
"""
outer = self.multipart()
outer['Subject'] = subject
outer['From'] = sender_email
outer['To'] = ', '.join(destination_emails)
outer.preamble = subject
# Create a text/plain message
if not const_is_python3():
if const_isunicode(content):
content = content.encode('utf-8')
if const_isunicode(subject):
subject = subject.encode('utf-8')
else:
if not const_isunicode(content):
raise AttributeError("content must be unicode (str)")
if not const_isunicode(subject):
raise AttributeError("subject must be unicode (str)")
mymsg = self.text(content)
outer.attach(mymsg)
# attach files
for myfile in files:
try:
with open(myfile, "r") as my_f:
pass
except (OSError, IOError):
continue
ctype, encoding = self.mimetypes.guess_type(myfile)
if ctype is None or encoding is not None:
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
if maintype == 'image':
img_f = open(myfile, "rb")
msg = self.image(img_f.read(), _subtype = subtype)
img_f.close()
elif maintype == 'audio':
audio_f = open(myfile, "rb")
msg = self.audio(audio_f.read(), _subtype = subtype)
audio_f.close()
else:
gen_f = open(myfile, "rb")
msg = self.mimefile(maintype, subtype)
msg.set_payload(gen_f.read())
gen_f.close()
self.encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment',
filename = os.path.basename(myfile))
outer.attach(msg)
composed = outer.as_string()
return self.default_sender(sender_email, destination_emails, composed)
class RSS:
"""
This is a base class for handling RSS (XML) files through Python's
xml.dom.minidom module. It produces 100% W3C-complaint code.
This class is meant to be used inside the Entropy world, it's not meant
for other tasks outside this codebase.
"""
def __init__(self, filename, title, description, maxentries = 100):
"""
RSS constructor
@param filename: RSS file path (a new file will be created if not found)