Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
html module in python 3.6.8
#1
I am new to Python and stuck in an issue, have researched in stackoverflow but couldnt get an answer. The problem statement is as below.

Problem: I was using html module in python 2.x version for displaying data in a dashboard. Due to regulatons we have upgraded to python 3.68 .Post upgradation html module is not working. The object instatntiated from the html module is used for displaying title,body,table etc.
The infrastructure details are as below
Output:
NAME="CentOS Linux" VERSION="7 (Core)" ID="centos" ID_LIKE="rhel fedora" VERSION_ID="7"
The error displayed in terminal is as below.
Error:
Traceback (most recent call last): File "dashbord.py", line 9, in <module> from html import HTML ImportError: cannot import name 'HTML'
Source code as below

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
import time
import sys
import os
import re
import pymongo
from  pymongo import MongoClient
import base64
from datetime import datetime,timedelta
from html import HTML
 
d = datetime.today() - timedelta(hours=0, minutes=180)
d1 = d.strftime("%d/%B/%Y,%H:%M:%S")
#threshholdLimitPriceLineProperties=320000
threshholdLimitPriceLineProperties=130000
 
h=HTML('html','')
title=h.title('Hotel DASHBOARD With PriceLine')
 
 
def saveFile():
        #print "here"
        conn = MongoClient("xx.xx.xx.xx:27017")
        #print conn
 
 
        TravelHotelsPricelineDb=conn.travelHotelsPriceline
        rawLocationsHotelsPricelineDatacount=TravelHotelsPricelineDb.rawLocationsData.count()
        finishedLocationHotelsPricelineValidDatacount=TravelHotelsPricelineDb.finishedLocationsData.find({"metaData.status" : "VALID"}).count()
 
 
        with open("/home/tomcat/scripts/HotelOutput_new_pricingDataLine_data.txt", "a") as text_file:
 
                 #text_file.write('{0} {1} {2} {3} {4} {5} {6} {7} {8}   \n'.format(d1,rawLocationsDatacount,rawPropertiesDatacount,validHotelCount,Hotel,vacationRental,validLocationCount,rawLocationsHotelsPricelineDatacount,finishedLocationHotelsPricelineValidDatacount))
                 text_file.write('{0} {1} {2}    \n'.format(d1,rawLocationsHotelsPricelineDatacount,finishedLocationHotelsPricelineValidDatacount))
                 text_file.close()
saveFile()
 
def sortFile():
 
        #print "in sort section"
 
        with open ('/home/tomcat/scripts/HotelOutput_new_pricingDataLine_data.txt') as fi, open('/home/tomcat/scripts/sortHotel_new_pricingDataLine_data.txt', 'w') as fo:
                fo.write('\n'.join(reversed(fi.read().splitlines())))
 
sortFile()
 
 
 
def readFile():
                #h1.br
                #h=HTML('html','')
                title=h.title('HOTEL DASHBOARD')
                h.BODY( bgcolor="FFFDE7" )
                h.b
                p=h.p('HOTEL  DETAILS WITH PRICELINE DATA',' ', align="center")
 
                h.b
                h.b
                h.b
                t=h.table(border='2',bgcolor='#B9CFFA',align="center")
                r=t.tr()
 
                r.td('Date & Time',style="font-weight:bold")
 
 
                r.td('Raw Hotel  Count - PriceLine',style="font-weight:bold")
 
                r.td('Valid Hotel Count - PriceLine',style="font-weight:bold")
                r.td('Threshold Limit for Hotel - PriceLine',style="font-weight:bold")
                contents = open("/home/tomcat/scripts/sortHotel_new_pricingDataLine_data.txt","r")
                for line in contents:
 
                 line = line.strip()
                 parts = line.split()
 
                 dateTime = parts[0]
                 rawLocationsHotelsPricelineDatacount = parts[1]
                 finishedLocationHotelsPricelineValidDatacount = parts[2]
 
 
                 r.tr()
                 r.td(dateTime)
 
                 r.td(rawLocationsHotelsPricelineDatacount)
                 if ( int(finishedLocationHotelsPricelineValidDatacount) <= int(threshholdLimitPriceLineProperties) ):
                        r.td(finishedLocationHotelsPricelineValidDatacount,bgcolor="red")
                 else:
                        r.td(finishedLocationHotelsPricelineValidDatacount)
 
                 r.td(str(threshholdLimitPriceLineProperties))
 
                 r.tr()
 
                 #r.td(bgcolor="grey")
                 #r.td(bgcolor="grey")
 
                contents.close()
 
readFile()
print(h)
Any help is highly appreciated
Reply
#2
There is no html module in python2 so I guess that was something installed from PyPI or local module created by you/your colleagues.
In python3 there is html module in the standard library, so there is html modulem but no HTML name/class in it.

So, you need to check what package was used in your old code and install it from PyPI. You may need to change some parts of the code - i.e. if its name was changed in python3 to avoid name collision or use different package to pretty format the output (there are plenty of available options).

Also, if this is module created by you, when you import/from html it first search in the standard library, thus in python3 your module is shadowed by the module in the standard library

Quote:When a module named spam is imported, the interpreter first searches for a built-in module with that name. These module names are listed in sys.builtin_module_names. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:
  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default (by convention including a site-packages directory, handled by the site module).

see https://docs.python.org/3/tutorial/modul...earch-path
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
html is part of the python distribution now, see: https://docs.python.org/3/library/html.html
It contains two submodues:
you may need to import these separately.

I would try importing the specific submodules and see if you can find your missing modules.

1
2
3
import html
import html.entities
import html.parser
Reply
#4
@Larz60+, given there was no html module in python2 they were using something else - installed from pypi or local module. html in python3 would not do for their needs/ I guess - the later and now it is shadowed by the module in the standard library
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Thanks all for the suggestions. Will try the same
Reply
#6
Sufira, take heed to Buran's post 4.
Reply
#7
The module was html 1.16.
I did test in Python 3.10 and did not work,module is from 2011.
So i started to look at code,and did a rewrite to make work in Python 3.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
λ python -i html2.py
........................
----------------------------------------------------------------------
Ran 24 tests in 0.004s
 
OK
Traceback (most recent call last):
  File "C:\Python310\Tools\scripts\html2.py", line 594, in <module>
    unittest.main()
  File "C:\python310\lib\unittest\main.py", line 101, in __init__
    self.runTests()
  File "C:\python310\lib\unittest\main.py", line 273, in runTests
    sys.exit(not self.result.wasSuccessful())
SystemExit: False
So now it pass all 24 tests,but Unittest give a internal error not related to the module.
Can just comment out Unittest as it dos not need to run every time.
Test.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
λ python -i html2.py
>>> from html2 import HTML
>>>
>>> h = HTML()
>>> h.p('Hello, world!')
<HTML p 0x1bedf9cfac0>
>>> print(h)
<p>Hello, world!</p>
>>>
>>> h.div('A test')
<HTML div 0x1bedf9cfa90>
>>> print(h)
<p>Hello, world!</p>
<div>A test</div>
 
>>> h = HTML()
>>> h.p(u'Some Euro: €1.14')
<HTML p 0x29a8e76fe50>
>>> print(h)
<p>Some Euro: €1.14</p>
Test of some of your code.
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
λ python -i html2.py
>>> from html2 import HTML
>>>
>>> h = HTML()
>>> title=h.title('HOTEL DASHBOARD')
>>> h.BODY( bgcolor="FFFDE7" )
<HTML BODY 0x265dbf3fa60>
>>> h.b
<HTML b 0x265dbf3fa90>
>>> p=h.p('HOTEL  DETAILS WITH PRICELINE DATA',' ', align="center")
>>> h.b
<HTML b 0x265dbef0250>
>>> h.b
<HTML b 0x265dbef0220>
>>> h.b
<HTML b 0x265dbef1ae0>
>>> t=h.table(border='2',bgcolor='#B9CFFA',align="center")
>>> r=t.tr()
>>>
>>> print(h)
<title>HOTEL DASHBOARD</title>
<BODY bgcolor="FFFDE7">
<b>
<p align="center">HOTEL  DETAILS WITH PRICELINE DATA </p>
<b>
<b>
<b>
<table border="2" bgcolor="#B9CFFA" align="center">
<tr>
</table>
So it seems to work ok,here is code html2.py.
Do not name html.py as Python 3 use that name for own module.
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
# html2.py, Quick edit bye snippsat to make it work in Python 3
# -*- encoding: utf8 -*-
#
# $Id: html.py 5409 2011-06-29 07:07:25Z rjones $
#
'''Simple, elegant HTML, XHTML and XML generation.
 
Constructing your HTML
----------------------
 
To construct HTML start with an instance of ``html.HTML()``. Add
tags by accessing the tag's attribute on that object. For example:
 
>>> from html import HTML
>>> h = HTML()
>>> h.p('Hello, world!')
>>> print h                          # or print(h) in python 3+
<p>Hello, world!</p>
 
You may supply a tag name and some text contents when creating a HTML
instance:
 
>>> h = HTML('html', 'text')
>>> print h
<html>text</html>
 
You may also append text content later using the tag's ``.text()`` method
or using augmented addition ``+=``. Any HTML-specific characters (``<>&"``)
in the text will be escaped for HTML safety as appropriate unless
``escape=False`` is passed. Each of the following examples uses a new
``HTML`` instance:
 
>>> p = h.p('hello world!\\n')
>>> p.br
>>> p.text('more &rarr; text', escape=False)
>>> p += ' ... augmented'
>>> h.p
>>> print h
<p>hello, world!<br>more &rarr; text ... augmented</p>
<p>
 
Note also that the top-level ``HTML`` object adds newlines between tags by
default. Finally in the above you'll see an empty paragraph tag - tags with
no contents get no closing tag.
 
If the tag should have sub-tags you have two options. You may either add
the sub-tags directly on the tag:
 
>>> l = h.ol
>>> l.li('item 1')
>>> l.li.b('item 2 > 1')
>>> print h
<ol>
<li>item 1</li>
<li><b>item 2 &gt; 1</b></li>
</ol>
 
Note that the default behavior with lists (and tables) is to add newlines
between sub-tags to generate a nicer output. You can also see in that
example the chaining of tags in ``l.li.b``.
 
Tag attributes may be passed in as well:
 
>>> t = h.table(border='1')
>>> for i in range(2):
>>>   r = t.tr
>>>   r.td('column 1')
>>>   r.td('column 2')
>>> print t
<table border="1">
<tr><td>column 1</td><td>column 2</td></tr>
<tr><td>column 1</td><td>column 2</td></tr>
</table>
 
A variation on the above is to use a tag as a context variable. The
following is functionally identical to the first list construction but
with a slightly different sytax emphasising the HTML structure:
 
>>> with h.ol as l:
...   l.li('item 1')
...   l.li.b('item 2 > 1')
 
You may turn off/on adding newlines by passing ``newlines=False`` or
``True`` to the tag (or ``HTML`` instance) at creation time:
 
>>> l = h.ol(newlines=False)
>>> l.li('item 1')
>>> l.li('item 2')
>>> print h
<ol><li>item 1</li><li>item 2</li></ol>
 
Since we can't use ``class`` as a keyword, the library recognises ``klass``
as a substitute:
 
>>> print h.p(content, klass="styled")
<p class="styled">content</p>
 
 
Unicode
-------
 
``HTML`` will work with either regular strings **or** unicode strings, but
not **both at the same time**.
 
Obtain the final unicode string by calling ``unicode()`` on the ``HTML``
instance:
 
>>> h = HTML()
>>> h.p(u'Some Euro: €1.14')
>>> unicode(h)
u'<p>Some Euro: €1.14</p>'
 
If (under Python 2.x) you add non-unicode strings or attempt to get the
resultant HTML source through any means other than ``unicode()`` then you
will most likely get one of the following errors raised:
 
UnicodeDecodeError
   Probably means you've added non-unicode strings to your HTML.
UnicodeEncodeError
   Probably means you're trying to get the resultant HTML using ``print``
   or ``str()`` (or ``%s``).
 
 
How generation works
--------------------
 
The HTML document is generated when the ``HTML`` instance is "stringified".
This could be done either by invoking ``str()`` on it, or just printing it.
It may also be returned directly as the "iterable content" from a WSGI app
function.
 
You may also render any tag or sub-tag at any time by stringifying it.
 
Tags with no contents (either text or sub-tags) will have no closing tag.
There is no "special list" of tags that must always have closing tags, so
if you need to force a closing tag you'll need to provide some content,
even if it's just a single space character.
 
Rendering doesn't affect the HTML document's state, so you can add to or
otherwise manipulate the HTML after you've stringified it.
 
 
Creating XHTML
--------------
 
To construct XHTML start with an instance of ``html.XHTML()`` and use it
as you would an ``HTML`` instance. Empty elements will now be rendered
with the appropriate XHTML minimized tag syntax. For example:
 
>>> from html import XHTML
>>> h = XHTML()
>>> h.p
>>> h.br
>>> print h
<p></p>
<br />
 
 
Creating XML
------------
 
A slight tweak to the ``html.XHTML()`` implementation allows us to generate
arbitrary XML using ``html.XML()``:
 
>>> from html import XML
>>> h = XML('xml')
>>> h.p
>>> h.br('hi there')
>>> print h
<xml>
<p />
<br>hi there</br>
</xml>
 
 
Tags with difficult names
-------------------------
 
If your tag name isn't a valid Python identifier name, or if it's called
"text" or "raw_text" you can add your tag slightly more manually:
 
>>> from html import XML
>>> h = XML('xml')
>>> h += XML('some-tag', 'some text')
>>> h += XML('text', 'some text')
>>> print h
<xml>
<some-tag>some text</some-tag>
<text>some text</text>
</xml>
 
 
Version History (in Brief)
--------------------------
 
- 1.16 detect and raise a more useful error when some WSGI frameworks
  attempt to call HTML.read(). Also added ability to add new content using
  the += operator.
- 1.15 fix Python 3 compatibility (unit tests)
- 1.14 added plain XML support
- 1.13 allow adding (X)HTML instances (tags) as new document content
- 1.12 fix handling of XHTML empty tags when generating unicode
  output (thanks Carsten Eggers)
- 1.11 remove setuptools dependency
- 1.10 support plain ol' distutils again
- 1.9 added unicode support for Python 2.x
- 1.8 added Python 3 compatibility
- 1.7 added Python 2.5 compatibility and escape argument to tag
  construction
- 1.6 added .raw_text() and and WSGI compatibility
- 1.5 added XHTML support
- 1.3 added more documentation, more tests
- 1.2 added special-case klass / class attribute
- 1.1 added escaping control
- 1.0 was the initial release
 
----
 
I would be interested to know whether this module is useful - if you use it
please indicate so at https://www.ohloh.net/p/pyhtml
 
This code is copyright 2009-2011 eKit.com Inc (http://www.ekit.com/)
See the end of the source file for the license of use.
XHTML support was contributed by Michael Haubenwallner.
'''
 
__version__ = '1.16'
 
import sys
import cgi
import unittest
import html
 
class HTML(object):
    '''Easily generate HTML.
 
    >>> print HTML('html', 'some text')
    <html>some text</html>
    >>> print HTML('html').p('some text')
    <html><p>some text</p></html>
 
    If a name is not passed in then the instance becomes a container for
    other tags that itself generates no tag:
 
    >>> h = HTML()
    >>> h.p('text')
    >>> h.p('text')
    print h
    <p>some text</p>
    <p>some text</p>
 
    '''
    newline_default_on = set('table ol ul dl'.split())
 
    def __init__(self, name=None, text=None, stack=None, newlines=True,
            escape=True):
        self._name = name
        self._content = []
        self._attrs = {}
        # insert newlines between content?
        if stack is None:
            stack = [self]
            self._top = True
            self._newlines = newlines
        else:
            self._top = False
            self._newlines = name in self.newline_default_on
        self._stack = stack
        if text is not None:
            self.text(text, escape)
 
    def __getattr__(self, name):
        # adding a new tag or newline
        if name == 'newline':
            e = '\n'
        else:
            e = self.__class__(name, stack=self._stack)
        if self._top:
            self._stack[-1]._content.append(e)
        else:
            self._content.append(e)
        return e
 
    def __iadd__(self, other):
        if self._top:
            self._stack[-1]._content.append(other)
        else:
            self._content.append(other)
        return self
 
    def text(self, text, escape=True):
        '''Add text to the document. If "escape" is True any characters
        special to HTML will be escaped.
        '''
        if escape:
            text = html.escape(text)
        # adding text
        if self._top:
            self._stack[-1]._content.append(text)
        else:
            self._content.append(text)
 
    def raw_text(self, text):
        '''Add raw, unescaped text to the document. This is useful for
        explicitly adding HTML code or entities.
        '''
        return self.text(text, escape=False)
 
    def __call__(self, *content, **kw):
        if self._name == 'read':
            if len(content) == 1 and isinstance(content[0], int):
                raise TypeError('you appear to be calling read(%d) on '
                    'a HTML instance' % content)
            elif len(content) == 0:
                raise TypeError('you appear to be calling read() on a '
                    'HTML instance')
 
        # customising a tag with content or attributes
        escape = kw.pop('escape', True)
        if content:
            if escape:
                self._content = list(map(html.escape, content))
            else:
                self._content = content
        if 'newlines' in kw:
            # special-case to allow control over newlines
            self._newlines = kw.pop('newlines')
        for k in kw:
            if k == 'klass':
                self._attrs['class'] = html.escape(kw[k], True)
            else:
                self._attrs[k] = html.escape(kw[k], True)
        return self
 
    def __enter__(self):
        # we're now adding tags to me!
        self._stack.append(self)
        return self
 
    def __exit__(self, exc_type, exc_value, exc_tb):
        # we're done adding tags to me!
        self._stack.pop()
 
    def __repr__(self):
        return '<HTML %s 0x%x>' % (self._name, id(self))
 
    def _stringify(self, str_type):
        # turn me and my content into text
        join = '\n' if self._newlines else ''
        if self._name is None:
            return join.join(map(str_type, self._content))
        a = ['%s="%s"' % i for i in list(self._attrs.items())]
        l = [self._name] + a
        s = '<%s>%s' % (' '.join(l), join)
        if self._content:
            s += join.join(map(str_type, self._content))
            s += join + '</%s>' % self._name
        return s
 
    def __str__(self):
        return self._stringify(str)
 
    def __unicode__(self):
        return self._stringify(str)
 
    def __iter__(self):
        return iter([str(self)])
 
 
class XHTML(HTML):
    '''Easily generate XHTML.
    '''
    empty_elements = set('base meta link hr br param img area input col \
        colgroup basefont isindex frame'.split())
 
    def _stringify(self, str_type):
        # turn me and my content into text
        # honor empty and non-empty elements
        join = '\n' if self._newlines else ''
        if self._name is None:
            return join.join(map(str_type, self._content))
        a = ['%s="%s"' % i for i in list(self._attrs.items())]
        l = [self._name] + a
        s = '<%s>%s' % (' '.join(l), join)
        if self._content or not(self._name.lower() in self.empty_elements):
            s += join.join(map(str_type, self._content))
            s += join + '</%s>' % self._name
        else:
            s = '<%s />%s' % (' '.join(l), join)
        return s
 
 
class XML(XHTML):
    '''Easily generate XML.
 
    All tags with no contents are reduced to self-terminating tags.
    '''
    newline_default_on = set()          # no tags are special
 
    def _stringify(self, str_type):
        # turn me and my content into text
        # honor empty and non-empty elements
        join = '\n' if self._newlines else ''
        if self._name is None:
            return join.join(map(str_type, self._content))
        a = ['%s="%s"' % i for i in list(self._attrs.items())]
        l = [self._name] + a
        s = '<%s>%s' % (' '.join(l), join)
        if self._content:
            s += join.join(map(str_type, self._content))
            s += join + '</%s>' % self._name
        else:
            s = '<%s />%s' % (' '.join(l), join)
        return s
 
"""
class TestCase(unittest.TestCase):
    def test_empty_tag(self):
        'generation of an empty HTML tag'
        self.assertEqual(str(HTML().br), '<br>')
 
    def test_empty_tag_xml(self):
        'generation of an empty XHTML tag'
        self.assertEqual(str(XHTML().br), '<br />')
 
    def test_tag_add(self):
        'test top-level tag creation'
        self.assertEqual(str(HTML('html', 'text')), '<html>\ntext\n</html>')
 
    def test_tag_add_no_newline(self):
        'test top-level tag creation'
        self.assertEqual(str(HTML('html', 'text', newlines=False)),
            '<html>text</html>')
 
    def test_iadd_tag(self):
        "test iadd'ing a tag"
        h = XML('xml')
        h += XML('some-tag', 'spam', newlines=False)
        h += XML('text', 'spam', newlines=False)
        self.assertEqual(str(h),
            '<xml>\n<some-tag>spam</some-tag>\n<text>spam</text>\n</xml>')
 
    def test_iadd_text(self):
        "test iadd'ing text"
        h = HTML('html', newlines=False)
        h += 'text'
        h += 'text'
        self.assertEqual(str(h), '<html>texttext</html>')
 
    def test_xhtml_match_tag(self):
        'check forced generation of matching tag when empty'
        self.assertEqual(str(XHTML().p), '<p></p>')
 
    if sys.version_info[0] == 2:
        def test_empty_tag_unicode(self):
            'generation of an empty HTML tag'
            self.assertEqual(str(HTML().br), str('<br>'))
 
        def test_empty_tag_xml_unicode(self):
            'generation of an empty XHTML tag'
            self.assertEqual(str(XHTML().br), str('<br />'))
 
        def test_xhtml_match_tag_unicode(self):
            'check forced generation of matching tag when empty'
            self.assertEqual(str(XHTML().p), str('<p></p>'))
 
    def test_just_tag(self):
        'generate HTML for just one tag'
        self.assertEqual(str(HTML().br), '<br>')
 
    def test_just_tag_xhtml(self):
        'generate XHTML for just one tag'
        self.assertEqual(str(XHTML().br), '<br />')
 
    def test_xml(self):
        'generate XML'
        self.assertEqual(str(XML().br), '<br />')
        self.assertEqual(str(XML().p), '<p />')
        self.assertEqual(str(XML().br('text')), '<br>text</br>')
 
    def test_para_tag(self):
        'generation of a tag with contents'
        h = HTML()
        h.p('hello')
        self.assertEqual(str(h), '<p>hello</p>')
 
    def test_escape(self):
        'escaping of special HTML characters in text'
        h = HTML()
        h.text('<>&')
        self.assertEqual(str(h), '&lt;&gt;&amp;')
 
    def test_no_escape(self):
        'no escaping of special HTML characters in text'
        h = HTML()
        h.text('<>&', False)
        self.assertEqual(str(h), '<>&')
 
    def test_escape_attr(self):
        'escaping of special HTML characters in attributes'
        h = HTML()
        h.br(id='<>&"')
        self.assertEqual(str(h), '<br id="&lt;&gt;&amp;&quot;">')
 
    def test_subtag_context(self):
        'generation of sub-tags using "with" context'
        h = HTML()
        with h.ol:
            h.li('foo')
            h.li('bar')
        self.assertEqual(str(h), '<ol>\n<li>foo</li>\n<li>bar</li>\n</ol>')
 
    def test_subtag_direct(self):
        'generation of sub-tags directly on the parent tag'
        h = HTML()
        l = h.ol
        l.li('foo')
        l.li.b('bar')
        self.assertEqual(str(h),
            '<ol>\n<li>foo</li>\n<li><b>bar</b></li>\n</ol>')
 
    def test_subtag_direct_context(self):
        'generation of sub-tags directly on the parent tag in "with" context'
        h = HTML()
        with h.ol as l:
            l.li('foo')
            l.li.b('bar')
        self.assertEqual(str(h),
            '<ol>\n<li>foo</li>\n<li><b>bar</b></li>\n</ol>')
 
    def test_subtag_no_newlines(self):
        'prevent generation of newlines against default'
        h = HTML()
        l = h.ol(newlines=False)
        l.li('foo')
        l.li('bar')
        self.assertEqual(str(h), '<ol><li>foo</li><li>bar</li></ol>')
 
    def test_add_text(self):
        'add text to a tag'
        h = HTML()
        p = h.p('hello, world!\n')
        p.text('more text')
        self.assertEqual(str(h), '<p>hello, world!\nmore text</p>')
 
    def test_add_text_newlines(self):
        'add text to a tag with newlines for prettiness'
        h = HTML()
        p = h.p('hello, world!', newlines=True)
        p.text('more text')
        self.assertEqual(str(h), '<p>\nhello, world!\nmore text\n</p>')
 
    def test_doc_newlines(self):
        'default document adding newlines between tags'
        h = HTML()
        h.br
        h.br
        self.assertEqual(str(h), '<br>\n<br>')
 
    def test_doc_no_newlines(self):
        'prevent document adding newlines between tags'
        h = HTML(newlines=False)
        h.br
        h.br
        self.assertEqual(str(h), '<br><br>')
 
    def test_unicode(self):
        'make sure unicode input works and results in unicode output'
        h = HTML(newlines=False)
        # Python 3 compat
        try:
            #str = str
            TEST = 'euro \xe2\x82\xac'.decode('utf8')
        except:
            #str = str
            TEST = 'euro €'
        h.p(TEST)
        self.assertEqual(str(h), '<p>%s</p>' % TEST)
 
    def test_table(self):
        'multiple "with" context blocks'
        h = HTML()
        with h.table(border='1'):
            for i in range(2):
                with h.tr:
                    h.td('column 1')
                    h.td('column 2')
        self.assertEqual(str(h), '''<table border="1">
<tr><td>column 1</td><td>column 2</td></tr>
<tr><td>column 1</td><td>column 2</td></tr>
</table>''')
 
if __name__ == '__main__':
    unittest.main()"""
 
 
# Copyright (c) 2009 eKit.com Inc (http://www.ekit.com/)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
 
# vim: set filetype=python ts=4 sw=4 et si
Larz60+, buran, perfringo like this post
Reply
#8
Thanks Snippsat. The html related error is gone. Working to resolve the pymongo related errros .

Error:
rawLocationsHotelsPricelineDatacount=TravelHotelsPricelineDb.rawLocationsData.count() File "/usr/local/lib64/python3.6/site-packages/pymongo/collection.py", line 3169, in __call__ "failing because no such method exists." % self.__name.split(".")[-1] TypeError: 'Collection' object is not callable. If you meant to call the 'count' method on a 'Collection' object it is failing because no such method exists.
Reply
#9
Pymongo Wrote:The count() method was deprecated in pymongo version 3.7 and removed in version 4.0. Instead,
you can use the count_documents() method to achieve the same functionality.

So can try this:
1
2
3
4
5
6
7
8
9
def saveFile():
    conn = MongoClient("xx.xx.xx.xx:27017")
    TravelHotelsPricelineDb = conn.travelHotelsPriceline
    rawLocationsHotelsPricelineDatacount = TravelHotelsPricelineDb.rawLocationsData.count_documents({})
    finishedLocationHotelsPricelineValidDatacount = TravelHotelsPricelineDb.finishedLocationsData.count_documents({"metaData.status": "VALID"})
 
    with open("/home/tomcat/scripts/HotelOutput_new_pricingDataLine_data.txt", "a") as text_file:
        text_file.write('{0} {1} {2}\n'.format(d1, rawLocationsHotelsPricelineDatacount, finishedLocationHotelsPricelineValidDatacount))
saveFile()
Ahh those longđź‘€ names.
Reply
#10
(May-11-2023, 03:49 PM)snippsat Wrote:
Pymongo Wrote:The count() method was deprecated in pymongo version 3.7 and removed in version 4.0. Instead,
you can use the count_documents() method to achieve the same functionality.

So can try this:
1
2
3
4
5
6
7
8
9
def saveFile():
    conn = MongoClient("xx.xx.xx.xx:27017")
    TravelHotelsPricelineDb = conn.travelHotelsPriceline
    rawLocationsHotelsPricelineDatacount = TravelHotelsPricelineDb.rawLocationsData.count_documents({})
    finishedLocationHotelsPricelineValidDatacount = TravelHotelsPricelineDb.finishedLocationsData.count_documents({"metaData.status": "VALID"})
 
    with open("/home/tomcat/scripts/HotelOutput_new_pricingDataLine_data.txt", "a") as text_file:
        text_file.write('{0} {1} {2}\n'.format(d1, rawLocationsHotelsPricelineDatacount, finishedLocationHotelsPricelineValidDatacount))
saveFile()
Ahh those longđź‘€ names.

Thanks Snippsat.All the issues resolved . Much appreciated.
snippsat likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Tkinterweb (Browser Module) Appending/Adding Additional HTML to a HTML Table Row AaronCatolico1 0 1,947 Dec-25-2022, 06:28 PM
Last Post: AaronCatolico1
  reading html and edit chekcbox to html jacklee26 5 4,526 Jul-01-2021, 10:31 AM
Last Post: snippsat
  HTML to Python to Windows .bat and back to HTML perfectservice33 0 2,561 Aug-22-2019, 06:31 AM
Last Post: perfectservice33

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020