Files
@ 4ae4989cb7e7
Branch filter:
Location: rattail-project/rattail/rattail/labels.py
4ae4989cb7e7
10.7 KiB
text/x-python
Tweaked Fabric `release` command.
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 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# Rattail -- Retail Software Framework
# Copyright © 2010-2012 Lance Edgar
#
# This file is part of Rattail.
#
# Rattail is free software: you can redistribute it and/or modify it under the
# terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# Rattail is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Rattail. If not, see <http://www.gnu.org/licenses/>.
#
################################################################################
"""
``rattail.labels`` -- Label Printing
"""
import os
import os.path
import socket
import shutil
from cStringIO import StringIO
import edbob
from edbob.util import OrderedDict, requires_impl
from rattail.exceptions import LabelPrintingError
class LabelPrinter(edbob.Object):
"""
Base class for all label printers.
Label printing devices which are "natively" supported by Rattail will each
derive from this class in order to provide implementation details specific
to the device. You will typically instantiate one of those subclasses (or
one of your own design) in order to send labels to your physical printer.
"""
profile_name = None
formatter = None
required_settings = None
@requires_impl()
def print_labels(self, labels, *args, **kwargs):
"""
Prints labels found in ``labels``.
"""
pass
class CommandPrinter(LabelPrinter):
"""
Generic :class:`LabelPrinter` class which "prints" labels via native
printer (textual) commands. It does not directly implement any method for
sending the commands to a printer; a subclass must be used for that.
"""
def batch_header_commands(self):
"""
This method, if implemented, must return a sequence of string commands
to be interpreted by the printer. These commands will be the first
which are written to the file.
"""
return None
def batch_footer_commands(self):
"""
This method, if implemented, must return a sequence of string commands
to be interpreted by the printer. These commands will be the last
which are written to the file.
"""
return None
class CommandFilePrinter(CommandPrinter):
"""
Generic :class:`LabelPrinter` implementation which "prints" labels to a
file in the form of native printer (textual) commands. The output file is
then expected to be picked up by a file monitor, and finally sent to the
printer from there.
"""
required_settings = {'output_dir': "Output Folder"}
output_dir = None
def print_labels(self, labels, output_dir=None, progress=None):
"""
"Prints" ``labels`` by generating a command file in the output folder.
The full path of the output file to which commands are written will be
returned to the caller.
If ``output_dir`` is not specified, and the printer instance is
associated with a :class:`LabelProfile` instance, then config will be
consulted for the output path. If a path still is not found, the
current (working) directory will be assumed.
"""
if not output_dir:
output_dir = self.output_dir
if not output_dir:
raise LabelPrintingError("Printer does not have an output folder defined")
labels_path = edbob.temp_path(prefix='rattail.', suffix='.labels')
labels_file = open(labels_path, 'w')
header = self.batch_header_commands()
if header:
labels_file.write('%s\n' % '\n'.join(header))
commands = self.formatter.format_labels(labels, progress=progress)
if commands is None:
labels_file.close()
os.remove(labels_path)
return None
labels_file.write(commands)
footer = self.batch_footer_commands()
if footer:
labels_file.write('%s\n' % '\n'.join(footer))
labels_file.close()
fn = '%s_%s.labels' % (socket.gethostname(),
edbob.local_time().strftime('%Y-%m-%d_%H-%M-%S'))
final_path = os.path.join(output_dir, fn)
shutil.move(labels_path, final_path)
return final_path
# Force ordering for network printer required settings.
settings = OrderedDict()
settings['address'] = "IP Address"
settings['port'] = "Port"
settings['timeout'] = "Timeout"
class CommandNetworkPrinter(CommandPrinter):
"""
Generic :class:`LabelPrinter` implementation which "prints" labels to a
network socket in the form of native printer (textual) commands. The
socket is assumed to exist on a networked label printer.
"""
required_settings = settings
address = None
port = None
timeout = None
def print_labels(self, labels, progress=None):
"""
Prints ``labels`` by generating commands and sending directly to a
socket which exists on a networked printer.
"""
if not self.address:
raise LabelPrintingError("Printer does not have an IP address defined")
if not self.port:
raise LabelPrintingError("Printer does not have a port defined.")
data = StringIO()
header = self.batch_header_commands()
if header:
data.write('%s\n' % '\n'.join(header))
commands = self.formatter.format_labels(labels, progress=progress)
if commands is None: # process canceled?
data.close()
return None
data.write(commands)
footer = self.batch_footer_commands()
if footer:
data.write('%s\n' % '\n'.join(footer))
try:
timeout = int(self.timeout)
except ValueError:
timeout = socket.getdefaulttimeout()
try:
# Must pass byte-strings (not unicode) to this function.
sock = socket.create_connection((str(self.address), str(self.port)), timeout)
bytes = sock.send(data.getvalue())
sock.close()
return bytes
finally:
data.close()
class LabelFormatter(edbob.Object):
"""
Base class for all label formatters.
"""
format = None
@property
def default_format(self):
"""
Default format for labels. This should be defined by the derived
formatter class. It will be used if no format is defined within the
label profile.
"""
raise NotImplementedError
@requires_impl()
def format_labels(self, labels, progress=None, *args, **kwargs):
"""
Formats ``labels`` and returns the result.
"""
pass
class CommandFormatter(LabelFormatter):
"""
Generic subclass of :class:`LabelFormatter` which generates native printer
(textual) commands.
"""
def format_labels(self, labels, progress=None):
prog = None
if progress:
prog = progress("Formatting labels", len(labels))
fmt = StringIO()
cancel = False
for i, (product, quantity) in enumerate(labels, 1):
for j in range(quantity):
header = self.label_header_commands()
if header:
fmt.write('%s\n' % '\n'.join(header))
fmt.write('%s\n' % '\n'.join(self.label_body_commands(product)))
footer = self.label_footer_commands()
if footer:
fmt.write('%s\n' % '\n'.join(footer))
if prog and not prog.update(i):
cancel = True
break
if prog:
prog.destroy()
if cancel:
fmt.close()
return None
val = fmt.getvalue()
fmt.close()
return val
def label_header_commands(self):
"""
This method, if implemented, must return a sequence of string commands
to be interpreted by the printer. These commands will immediately
precede each *label* in one-up printing, and immediately precede each
*label pair* in two-up printing.
"""
return None
@requires_impl()
def label_body_commands(self):
pass
def label_footer_commands(self):
"""
This method, if implemented, must return a sequence of string commands
to be interpreted by the printer. These commands will immedately
follow each *label* in one-up printing, and immediately follow each
*label pair* in two-up printing.
"""
return None
class TwoUpCommandFormatter(CommandFormatter):
"""
Generic subclass of :class:`LabelFormatter` which generates native printer
(textual) commands.
This class contains logic to implement "two-up" label printing.
"""
@property
@requires_impl(is_property=True)
def half_offset(self):
"""
The X-coordinate value by which the second label should be offset, when
two labels are printed side-by-side.
"""
pass
def format_labels(self, labels, progress=None):
prog = None
if progress:
prog = progress("Formatting labels", len(labels))
fmt = StringIO()
cancel = False
half_started = False
for i, (product, quantity) in enumerate(labels, 1):
for j in range(quantity):
if half_started:
fmt.write('%s\n' % '\n'.join(
self.label_body_commands(product, x=self.half_offset)))
footer = self.label_footer_commands()
if footer:
fmt.write('%s\n' % '\n'.join(footer))
half_started = False
else:
header = self.label_header_commands()
if header:
fmt.write('%s\n' % '\n'.join(header))
fmt.write('%s\n' % '\n'.join(
self.label_body_commands(product, x=0)))
half_started = True
if prog and not prog.update(i):
cancel = True
break
if prog:
prog.destroy()
if cancel:
fmt.close()
return None
if half_started:
footer = self.label_footer_commands()
if footer:
fmt.write('%s\n' % '\n'.join(footer))
val = fmt.getvalue()
fmt.close()
return val
|