Compare commits

..
36 Commits
Author SHA1 Message Date
admin 26c59c3b53 updated web edition 2026-10-23 17:41:27 -04:00
admin ef1b423edc excel records download on the about page 2026-10-23 17:41:07 -04:00
admin 0462af758d updated web edition 2026-10-22 21:03:38 -04:00
admin 7273dce8ad updated web edition 2026-10-22 21:03:19 -04:00
admin 8c760f680b about page update, removed old submodule ref and ignored rotated logs 2026-10-22 19:33:15 -04:00
adminandClaude Opus 5.5 57d615c28f Rebuild venv for python 3.14 (alpine 3.24)
- Venv rebuilt on Python 3.14; requirements.txt is its pip freeze.
  screen and the unused django-excel-* chain are left out (screen does
  not build on 3.14).
- .gitignore: old venvs kept on the server after a Python upgrade.
- Scrapers submodule: keep a growing record of every draw (records.py).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cw9sqyxD7yx2iFAcyMfxsV
2026-10-12 18:55:06 -04:00
admin b1668fa813 Merge server snapshot: whole-site tree with python 3.12 venv, keeping the quieter-logs/requirements commit 2026-10-10 15:17:43 -04:00
admin b41c070546 Rebuild venv for python 3.12 (alpine 3.20), gunicorn 25, quieter logs, ignore rotated logs
Whole-site snapshot so the repo works as a restorable backup of the server code and its virtualenv.
2026-10-10 15:16:53 -04:00
admin 876354fae6 Quieter gunicorn logs, requirements refreshed for python 3.12 and gunicorn 25 2026-10-10 15:02:33 -04:00
admin fb0a5207c9 removing unnecessary files 2026-09-27 15:59:25 -04:00
admin 9f3c26c0a6 Remove useless monitor scripts from repo 2026-09-27 15:52:28 -04:00
admin ebf799c3c4 Ignore staticfiles directory and zip archives 2026-09-27 15:47:37 -04:00
admin b4278d4023 Updating repo with submodule, removing .pyc files and fixing bugs 2026-09-27 15:04:15 -04:00
admin 5a09c272f0 Cleanup for repo 2026-09-27 13:19:56 -04:00
admin 3a1dc1f262 general sync 2022-06-19 21:31:03 -04:00
admin 3d11e66df7 CSRF ACTUALLY fixed, branches mixed up previously 2022-06-16 13:55:23 -04:00
admin 0c940f2616 CSRF Error Fixed 2022-06-16 13:24:49 -04:00
Linux User 65cdacf6a8 production ready 2022-06-15 00:15:05 +00:00
xi-pinmping fb290579c1 Refactored scripts 2022-06-13 11:45:48 -04:00
xi-pinmping 265bb31e27 Delete .directory 2022-06-11 16:36:53 -04:00
xi-pinmping 2c73f90285 final touches, paypal button, spelling errors, donate & twitter links, etc 2022-06-11 16:33:09 -04:00
xi-pinmping 4d688cab5e final touches, paypal button, spelling errors, donate & twitter links, etc 2022-06-11 16:33:08 -04:00
xi-pinmping c31f739395 final touches, paypal button, spelling errors, donate & twitter links, etc 2022-06-11 16:33:06 -04:00
xi-pinmping ed147b3ec8 gunicorn hosting works staticfiles rearranged 2022-06-11 16:33:05 -04:00
xi-pinmping 0e1a2681ea gunicorn hosting works staticfiles rearranged 2022-06-10 18:53:10 -04:00
matteo-id 977a3eeb82 Final touches before deployment, celery installed 2022-06-08 21:38:34 -04:00
matteo-id 827c6738a8 Restored CSS, added Whitenoise 2022-06-06 21:33:11 -04:00
matteo-id a9fd3900ae Fixed about, styling, and official link 2022-05-29 15:00:37 -04:00
matteo-id cf3dc3ee35 slight changes, redis impl 2022-05-28 14:10:38 -04:00
matteo-id e91ee1acbd styling, formatting in script 2022-05-23 19:34:08 -04:00
matteo-id 283e893438 formatting changes 2022-05-23 19:33:13 -04:00
matteo-id a0c172d11f requirements.txt 2022-01-16 11:32:46 -05:00
matteo-id 200063c4a4 script progress 2022-01-15 15:41:18 -05:00
matteo-id 9db090f9c7 lottopy web edition functioning 2021-12-29 13:59:44 -05:00
matteo-id 6d61b18f4e site actually works 2021-12-24 11:44:21 -05:00
matteo-id 3660710b23 Django lottery site 2021-12-21 10:46:09 -05:00
7687 changed files with 3017 additions and 4753 deletions

No files matched your search

+8
View File
@@ -42,3 +42,11 @@ log/
lottopy_site/lottopy_site/settings.py
lottopy_site/db.sqlite3
lottopy_site/dump.rdb
# Old venv kept on the server after a Python upgrade
*.venv-old/
# old local copy of lottopy_web_edition, not part of the site
lottopy_site/lottopy/old/
# rotated gunicorn logs
*.log-*
+2 -1
View File
@@ -219,6 +219,8 @@ deactivate -nondestructive
# that there is an activated venv.
$env:VIRTUAL_ENV = $VenvDir
$env:VIRTUAL_ENV_PROMPT = $Prompt
if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
Write-Verbose "Setting prompt to '$Prompt'"
@@ -233,7 +235,6 @@ if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
_OLD_VIRTUAL_PROMPT
}
$env:VIRTUAL_ENV_PROMPT = $Prompt
}
# Clear PYTHONHOME
+4 -4
View File
@@ -17,7 +17,7 @@ deactivate () {
# Call hash to forget past locations. Without forgetting
# past locations the $PATH changes we made may not be respected.
# See "man bash" for more details. hash is usually a builtin of your shell
hash -r 2> /dev/null
hash -r 2> /dev/null || true
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
PS1="${_OLD_VIRTUAL_PS1:-}"
@@ -54,7 +54,7 @@ _OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/"bin":$PATH"
export PATH
VIRTUAL_ENV_PROMPT='(django_lottopy) '
VIRTUAL_ENV_PROMPT=django_lottopy
export VIRTUAL_ENV_PROMPT
# unset PYTHONHOME if set
@@ -67,10 +67,10 @@ fi
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
_OLD_VIRTUAL_PS1="${PS1:-}"
PS1="("'(django_lottopy) '") ${PS1:-}"
PS1="("django_lottopy") ${PS1:-}"
export PS1
fi
# Call hash to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
hash -r 2> /dev/null
hash -r 2> /dev/null || true
+4 -2
View File
@@ -13,13 +13,15 @@ setenv VIRTUAL_ENV /home/williedynamite/django_lottopy/django_lottopy
set _OLD_VIRTUAL_PATH="$PATH"
setenv PATH "$VIRTUAL_ENV/"bin":$PATH"
setenv VIRTUAL_ENV_PROMPT django_lottopy
if ($?prompt) then
set _OLD_VIRTUAL_PROMPT="$prompt"
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
set prompt = '(django_lottopy) '"$prompt"
setenv VIRTUAL_ENV_PROMPT '(django_lottopy) '
set prompt = "("django_lottopy") $prompt:q"
endif
endif
alias pydoc python -m pydoc
+2 -2
View File
@@ -37,6 +37,7 @@ set -gx VIRTUAL_ENV /home/williedynamite/django_lottopy/django_lottopy
set -gx _OLD_VIRTUAL_PATH $PATH
set -gx PATH "$VIRTUAL_ENV/"bin $PATH
set -gx VIRTUAL_ENV_PROMPT django_lottopy
# Unset PYTHONHOME if set.
if set -q PYTHONHOME
@@ -56,7 +57,7 @@ if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
set -l old_status $status
# Output the venv prompt; color taken from the blue of the Python logo.
printf "%s%s%s" (set_color 4B8BBE) '(django_lottopy) ' (set_color normal)
printf "%s(%s)%s " (set_color 4B8BBE) django_lottopy (set_color normal)
# Restore the return status of the previous command.
echo "exit $old_status" | .
@@ -65,5 +66,4 @@ if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
end
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
set -gx VIRTUAL_ENV_PROMPT '(django_lottopy) '
end
+1 -3
View File
@@ -1,8 +1,6 @@
#!/home/williedynamite/django_lottopy/django_lottopy/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.argv[0] = sys.argv[0].removesuffix('.exe')
sys.exit(main())
+1 -3
View File
@@ -1,8 +1,6 @@
#!/home/williedynamite/django_lottopy/django_lottopy/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.argv[0] = sys.argv[0].removesuffix('.exe')
sys.exit(main())
@@ -1,8 +1,6 @@
#!/home/williedynamite/django_lottopy/django_lottopy/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.argv[0] = sys.argv[0].removesuffix('.exe')
sys.exit(main())
File renamed without changes.
+1 -3
View File
@@ -1,8 +1,6 @@
#!/home/williedynamite/django_lottopy/django_lottopy/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from wheel._commands import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.argv[0] = sys.argv[0].removesuffix('.exe')
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
python3
@@ -1,32 +0,0 @@
Metadata-Version: 2.1
Name: django-excel-base
Version: 1.0.7
Summary: Django Excel Base
Home-page: https://github.com/django-xxx/django-excel-base
Author: Hackathon
Author-email: kimi.huang@brightcells.com
Keywords: Django Excel Base
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Framework :: Django
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Office/Business :: Financial :: Spreadsheet
Description-Content-Type: text/markdown
Requires-Dist: xlwt
Requires-Dist: pytz
Requires-Dist: screen
# django-excel-base
Django Excel Base
## Installation
```shell
pip install django-excel-base
```
## Usage
```python
from django_excel_base import as_csv, as_dict_row_merge_xls, as_list_row_merge_xls, as_row_merge_xls, as_xls
```
@@ -1,12 +0,0 @@
django_excel_base-1.0.7.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
django_excel_base-1.0.7.dist-info/METADATA,sha256=nC8xDKxavFf7Xbkb_DTMtEcDBvaWvXb713d50JNvR60,924
django_excel_base-1.0.7.dist-info/RECORD,,
django_excel_base-1.0.7.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
django_excel_base-1.0.7.dist-info/WHEEL,sha256=bb2Ot9scclHKMOLDEHY6B2sicWOgugjFKaJsT7vwMQo,110
django_excel_base-1.0.7.dist-info/top_level.txt,sha256=Ztmf43jC6C_2Y7-gYnoM81uuOK2jjPBk5qP_DURwaN4,18
django_excel_base/__init__.py,sha256=3WEUJyQLan0jPOLLh6HNcWLIsGVQunK9bTkEUw6aCe4,273
django_excel_base/__pycache__/__init__.cpython-312.pyc,,
django_excel_base/__pycache__/compat.cpython-312.pyc,,
django_excel_base/__pycache__/excel.cpython-312.pyc,,
django_excel_base/compat.py,sha256=8KEjD2L-a7fo0izIpRdeIWTktWwMKCbvPT2gV3ga2Qg,760
django_excel_base/excel.py,sha256=lO8kJCblcl3HHPwXRQajGDoRed1HuVSvVbqc0PbmWEo,12578
@@ -1,5 +0,0 @@
# -*- coding: utf-8 -*-
from django_excel_base.compat import *
from django_excel_base.excel import (LeftMergeCell, MergeCell, UpMergeCell, as_csv, as_dict_row_merge_xls,
as_list_row_merge_xls, as_row_merge_xls, as_xls, use_xls_or_not)
@@ -1,46 +0,0 @@
# -*- coding: utf-8 -*-
"""
pythoncompat
"""
import sys
# -------
# Pythons
# -------
# Syntax sugar.
_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)
#: Python 3.x?
is_py3 = (_ver[0] == 3)
# ---------
# Specifics
# ---------
if is_py2:
builtin_str = str
str = unicode
bytes = str
basestring = basestring
numeric_types = (int, long, float)
try:
from cStringIO import StringIO
from cStringIO import StringIO as BytesIO
except ImportError:
from StringIO import StringIO
from StringIO import StringIO as BytesIO
elif is_py3:
builtin_str = str
str = str
bytes = bytes
basestring = (str, bytes)
numeric_types = (int, float)
from io import BytesIO, StringIO
@@ -1,375 +0,0 @@
# -*- coding:utf-8 -*-
import codecs
import copy
import datetime
import json
from collections import deque
import pytz
import screen
import xlwt
from django.conf import settings
from django.utils import timezone
from .compat import basestring, str
class LeftMergeCell(object):
pass
class UpMergeCell(object):
pass
class MergeCell(object):
LeftMerge = LeftMergeCell()
UpMerge = UpMergeCell()
@property
def use_xls_or_not(self):
if len(self.data) > 1:
return True
if self.force_csv:
return False
for sheet_info in self.data.values():
if len(sheet_info.get('data') or []) > self.EXCEL_MAXIMUM_ALLOWED_ROWS:
return False
return True
def get_merged_rows_num(data):
return max(sum(get_merged_rows_num(d) if isinstance(d, list) else 0 for d in data), 1)
def row_preprocessing(data, mapping):
field_key = mapping.get('field_key')
field_key = field_key if isinstance(field_key, list) else [field_key]
data_key = mapping.get('data_key')
nextmapping = mapping.get('next')
field_value = [data.get(key) for key in field_key]
return field_value + [data_preprocessing(data.get(data_key), nextmapping)] if nextmapping else field_value
def data_preprocessing(data, mapping):
data = data if isinstance(data, list) else [data]
return [row_preprocessing(item, mapping) for item in data]
def get_header_cell_styles(self):
al = xlwt.Alignment()
al.horz = self.hhorz
al.vert = self.hvert
font = xlwt.Font()
if self.font:
font.name = self.font
font.bold = True
datetime_style = xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss')
datetime_style.alignment = al
datetime_style.font = font
date_style = xlwt.easyxf(num_format_str='yyyy-mm-dd')
date_style.alignment = al
date_style.font = font
time_style = xlwt.easyxf(num_format_str='hh:mm:ss')
time_style.alignment = al
time_style.font = font
dafault_style = xlwt.Style.default_style
dafault_style.alignment = al
dafault_style.font = font
return copy.deepcopy({
'datetime': datetime_style,
'date': date_style,
'time': time_style,
'default': dafault_style,
})
def get_cell_styles(self):
al = xlwt.Alignment()
al.horz = self.horz
al.vert = self.vert
font = xlwt.Font()
if self.font:
font.name = self.font
datetime_style = xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss')
datetime_style.alignment = al
datetime_style.font = font
date_style = xlwt.easyxf(num_format_str='yyyy-mm-dd')
date_style.alignment = al
date_style.font = font
time_style = xlwt.easyxf(num_format_str='hh:mm:ss')
time_style.alignment = al
time_style.font = font
dafault_style = xlwt.Style.default_style
dafault_style.alignment = al
dafault_style.font = font
return copy.deepcopy({
'datetime': datetime_style,
'date': date_style,
'time': time_style,
'default': dafault_style,
})
def get_cell_info(self, value, cell_styles):
if value is None and self.blanks_for_none:
value = ''
if isinstance(value, datetime.datetime):
if timezone.is_aware(value):
value = timezone.make_naive(value, pytz.timezone(settings.TIME_ZONE))
cell_style = cell_styles['datetime']
elif isinstance(value, datetime.date):
cell_style = cell_styles['date']
elif isinstance(value, datetime.time):
cell_style = cell_styles['time']
else:
cell_style = cell_styles['default']
return value, cell_style
def auto_adjust_width(self, sheet, colx, value, widths):
# Columns have a property for setting the width.
# The value is an integer specifying the size measured in 1/256
# of the width of the character '0' as it appears in the sheet's default font.
# xlwt creates columns with a default width of 2962, roughly equivalent to 11 characters wide.
#
# https://github.com/python-excel/xlwt/blob/master/xlwt/BIFFRecords.py#L1675
# Offset Size Contents
# 4 2 Width of the columns in 1/256 of the width of the zero character, using default font
# (first FONT record in the file)
#
# Default Width: https://github.com/python-excel/xlwt/blob/master/xlwt/Column.py#L14
# self.width = 0x0B92
if not self.auto_adjust_width:
return
width = screen.calc_width(value) * 256 if isinstance(value, basestring) else screen.calc_width(str(value)) * 256
if width <= widths.get(colx, 0):
return
width = min(width, self.EXCEL_MAXIMUM_ALLOWED_COLUMN_WIDTH)
widths[colx] = width
sheet.col(colx).width = max(width, self.min_cell_width)
def generate_headers(headers):
if not headers:
return []
if isinstance(headers, list) and isinstance(headers[0], list):
return headers
return [headers]
def generate_sheet_info(sheet_info):
sheet_data = sheet_info.get('data')
sheet_mapping = sheet_info.get('mapping')
sheet_info['data'] = data_preprocessing(sheet_data, sheet_mapping)
return sheet_info
def write_header_cells(self, sheet, headers, widths):
if not headers or not isinstance(headers, list):
return
if not headers[0] or not isinstance(headers[0], list):
return
rlen, clen = len(headers), len(headers[0])
ignore_header_cells = set()
header_cell_styles = get_header_cell_styles(self)
for i in range(rlen):
for j in range(clen):
# If cell is MergeCell, direct continue
if isinstance(headers[i][j], (LeftMergeCell, UpMergeCell)):
continue
# If cell is IgnoreCell, direct continue
if (i, j) in ignore_header_cells:
continue
# Set r1/r2/c1/c2 for sheet.write_merge
r1, r2, c1, c2 = i, i, j, j
# Down for merge cells
for r2 in range(r1 + 1, rlen):
if (r2, c1) in ignore_header_cells:
break
if not isinstance(headers[r2][c1], UpMergeCell):
r2 -= 1
break
# Right for merge cells
for c2 in range(c1 + 1, clen):
if (r1, c2) in ignore_header_cells:
break
if not isinstance(headers[r1][c2], LeftMergeCell):
c2 -= 1
break
# Ignore cells
for k in range(r1, r2 + 1):
for m in range(c1, c2 + 1):
ignore_header_cells.add((k, m))
value = headers[r1][c1]
value, cell_style = get_cell_info(self, value, header_cell_styles)
sheet.write_merge(r1, r2, c1, c2, value, style=cell_style)
if c1 == c2:
auto_adjust_width(self, sheet, c1, value, widths)
@property
def as_xls(self):
if not isinstance(self.data, dict):
self.data = {self.sheet_name: {'data': self.data, 'headers': self.headers}}
cell_styles = get_cell_styles(self)
book = xlwt.Workbook(encoding=self.encoding)
for sheet_name, sheet_info in self.data.items():
sheet_data = sheet_info.get('data') or []
sheet_headers = generate_headers(sheet_info.get('headers'))
sheet = book.add_sheet(sheet_name)
widths = {}
# Write header cells
write_header_cells(self, sheet, sheet_headers, widths)
rowx = len(sheet_headers) # Data start row index
for row in sheet_data:
for colx, value in enumerate(row):
if value is None and self.blanks_for_none:
value = ''
value, cell_style = get_cell_info(self, value, cell_styles)
sheet.write(rowx, colx, value, style=cell_style)
auto_adjust_width(self, sheet, colx, value, widths)
rowx += 1 # Update row index
book.save(self.output)
@property
def as_row_merge_xls(self):
if not isinstance(self.data, dict):
self.data = {self.sheet_name: {'data': self.data, 'headers': self.headers}}
cell_styles = get_cell_styles(self)
book = xlwt.Workbook(encoding=self.encoding)
for sheet_name, sheet_info in self.data.items():
sheet_data = sheet_info.get('data') or []
sheet_headers = generate_headers(sheet_info.get('headers'))
sheet = book.add_sheet(sheet_name)
widths = {}
# Write header cells
write_header_cells(self, sheet, sheet_headers, widths)
rowx = len(sheet_headers) # Data start row index
for row in sheet_data:
# Max row number for current row
rowmax = max([(len(r) if isinstance(r, list) else 1) for r in row])
for colx, value in enumerate(row):
if isinstance(value, list):
for vx, val in enumerate(value):
val, cell_style = get_cell_info(self, val, cell_styles)
sheet.write(rowx + vx, colx, val, style=cell_style)
auto_adjust_width(self, sheet, colx, val, widths)
else:
value, cell_style = get_cell_info(self, value, cell_styles)
sheet.write_merge(rowx, rowx + rowmax - 1, colx, colx, value, style=cell_style)
auto_adjust_width(self, sheet, colx, value, widths)
rowx += rowmax # Update row index
book.save(self.output)
@property
def as_list_row_merge_xls(self):
if not isinstance(self.data, dict):
self.data = {self.sheet_name: {'data': self.data, 'headers': self.headers}}
cell_styles = get_cell_styles(self)
book = xlwt.Workbook(encoding=self.encoding)
q = deque()
for sheet_name, sheet_info in self.data.items():
sheet_data = sheet_info.get('data') or []
sheet_headers = generate_headers(sheet_info.get('headers'))
sheet = book.add_sheet(sheet_name)
widths = {}
# Write header cells
write_header_cells(self, sheet, sheet_headers, widths)
rowx = len(sheet_headers) # Data start row index
colx = 0
for row in sheet_data:
rowmax = 1
_rowx = rowx
_rowxd = {}
q.append(json.dumps([colx, row], ensure_ascii=False))
while q:
colx, rowdata = json.loads(q.popleft())
mergedrowsnum = get_merged_rows_num(rowdata)
rowmax = max(rowmax, mergedrowsnum)
for idx, value in enumerate(rowdata):
_colx = colx + idx
if isinstance(value, list):
for d in value:
q.append(json.dumps([_colx, d], ensure_ascii=False))
else:
_rowx = _rowxd.get(_colx, rowx)
_rowxd[_colx] = _rowx + mergedrowsnum
value, cell_style = get_cell_info(self, value, cell_styles)
sheet.write_merge(_rowx, _rowx + mergedrowsnum - 1, _colx, _colx, value, style=cell_style)
auto_adjust_width(self, sheet, _colx, value, widths)
rowx += rowmax # Update row index
colx = 0
book.save(self.output)
@property
def as_dict_row_merge_xls(self):
if not isinstance(self.data, dict):
self.data = {self.sheet_name: {'data': self.data, 'mapping': self.mapping, 'headers': self.headers}}
self.data = {sheet_name: generate_sheet_info(sheet_info) for sheet_name, sheet_info in self.data.items()}
self.as_list_row_merge_xls
@property
def as_csv(self):
# https://stackoverflow.com/questions/4348802/how-can-i-output-a-utf-8-csv-in-php-that-excel-will-read-properly?answertab=votes
# https://stackoverflow.com/questions/155097/microsoft-excel-mangles-diacritics-in-csv-files/1648671#1648671
# https://wiki.scn.sap.com/wiki/display/ABAP/CSV+tests+of+encoding+and+column+separator?original_fqdn=wiki.sdn.sap.com
if self.encoding == 'utf-8-sig':
self.output.write(codecs.BOM_UTF8)
if not self.data:
return
for row in list(self.data.values())[0].get('data') or []:
out_row = []
for value in row:
if value is None and self.blanks_for_none:
value = ''
if not isinstance(value, basestring):
value = str(value)
out_row.append(value.replace('"', '""').encode(self.encoding))
self.output.write(b'"%s"\n' % b'","'.join(out_row))
@@ -1,5 +0,0 @@
# -*- coding: utf-8 -*-
from excel_base import LeftMergeCell, MergeCell, UpMergeCell
from django_excel_response.excel_response import ExcelResponse
@@ -1,116 +0,0 @@
# -*- coding:utf-8 -*-
import datetime
from django import http
from django.conf import settings
from django.db.models.query import QuerySet
from django_six import Support_ValuesQuerySet, ValuesQuerySet
from excel_base import (BytesIO, StringIO, as_csv, as_dict_row_merge_xls, as_list_row_merge_xls, as_row_merge_xls,
as_xls, is_py2)
# Min (Max. Rows) for Widely Used Excel
# http://superuser.com/questions/366468/what-is-the-maximum-allowed-rows-in-a-microsoft-excel-xls-or-xlsx
EXCEL_MAXIMUM_ALLOWED_ROWS = 65536
# Column Width Limit For ``xlwt``
# https://github.com/python-excel/xlwt/blob/master/xlwt/Column.py#L22
EXCEL_MAXIMUM_ALLOWED_COLUMN_WIDTH = 65535
def __init__(self, data, output_name='excel_data', format='%Y%m%d%H%M%S', headers=None, force_csv=False, encoding='utf-8-sig', font=None, sheet_name='Sheet 1', blanks_for_none=True, auto_adjust_width=True, min_cell_width=1000, vert=0x01, horz=0x01, hvert=0x01, hhorz=0x02, merge_type=None, mapping=None, timezone=None):
self.data = data
self.output_name = output_name
self.format = format
self.headers = headers
self.force_csv = force_csv
self.encoding = encoding
self.font = font
self.sheet_name = sheet_name
self.blanks_for_none = blanks_for_none
self.auto_adjust_width = auto_adjust_width
self.min_cell_width = min_cell_width
# VERT_TOP     = 0x00    顶端对齐
# VERT_CENTER  = 0x01    居中对齐(垂直方向上)
# VERT_BOTTOM  = 0x02    底端对齐
# HORZ_LEFT    = 0x01    左端对齐
# HORZ_CENTER  = 0x02    居中对齐(水平方向上)
# HORZ_RIGHT   = 0x03    右端对齐
self.vert = vert
self.horz = horz
self.hvert = hvert
self.hhorz = hhorz
self.mapping = mapping
self.timezone = timezone or settings.TIME_ZONE
if merge_type != 'dict_row_merge':
if not isinstance(self.data, dict):
self.data = {self.sheet_name: {'data': self.data, 'headers': self.headers}}
# Make sure we've got the right type of data to work with
# ``list index out of range`` if data is ``[]``
valid_data = True
for sheet_name, sheet_info in self.data.items():
sheet_data = sheet_info.get('data') or []
sheet_headers = sheet_info.get('headers')
if Support_ValuesQuerySet and isinstance(sheet_data, ValuesQuerySet):
sheet_data = list(sheet_data)
elif isinstance(sheet_data, QuerySet):
sheet_data = list(sheet_data.values())
if not hasattr(sheet_data, '__getitem__'):
valid_data = False
break
if sheet_data:
if isinstance(sheet_data[0], dict):
if sheet_headers is None:
sheet_headers = list(sheet_data[0].keys())
sheet_data = [[row[col] for col in sheet_headers] for row in sheet_data]
if not hasattr(sheet_data[0], '__getitem__'):
valid_data = False
break
if sheet_headers and not hasattr(sheet_headers[0], '__getitem__'):
valid_data = False
break
sheet_info['data'] = sheet_data
sheet_info['headers'] = sheet_headers
self.data[sheet_name] = sheet_info
assert valid_data is True, 'ExcelStorage requires a sequence of sequences'
self.output = StringIO() if is_py2 else BytesIO()
if merge_type == 'row_merge':
_, content_type, file_ext = (self.as_row_merge_xls, 'application/vnd.ms-excel', 'xls')
elif merge_type == 'list_row_merge':
_, content_type, file_ext = (self.as_list_row_merge_xls, 'application/vnd.ms-excel', 'xls')
elif merge_type == 'dict_row_merge':
_, content_type, file_ext = (self.as_dict_row_merge_xls, 'application/vnd.ms-excel', 'xls')
else:
# Excel has a limit on number of rows; if we have more than that, make a csv
use_xls = True if len(self.data) <= self.EXCEL_MAXIMUM_ALLOWED_ROWS and not self.force_csv else False
_, content_type, file_ext = (self.as_xls, 'application/vnd.ms-excel', 'xls') if use_xls else (self.as_csv, 'text/csv', 'csv')
self.output.seek(0)
super(ExcelResponse, self).__init__(self.output, content_type=content_type)
file_name_ext = '_{0}'.format(datetime.datetime.now().strftime(self.format)) if self.format else ''
self['Content-Disposition'] = 'attachment;filename="%s.%s"' % ('{0}{1}'.format(self.output_name, file_name_ext).replace('"', '\"'), file_ext)
names = dir(http)
clsdict = {
'EXCEL_MAXIMUM_ALLOWED_ROWS': EXCEL_MAXIMUM_ALLOWED_ROWS,
'EXCEL_MAXIMUM_ALLOWED_COLUMN_WIDTH': EXCEL_MAXIMUM_ALLOWED_COLUMN_WIDTH,
'__init__': __init__,
'as_xls': as_xls,
'as_row_merge_xls': as_row_merge_xls,
'as_list_row_merge_xls': as_list_row_merge_xls,
'as_dict_row_merge_xls': as_dict_row_merge_xls,
'as_csv': as_csv,
}
if 'FileResponse' in names:
ExcelResponse = type('ExcelResponse', (http.FileResponse, ), clsdict)
elif 'StreamingHttpResponse' in names:
ExcelResponse = type('StreamingHttpResponse', (http.StreamingHttpResponse, ), clsdict)
else:
ExcelResponse = type('HttpResponse', (http.HttpResponse, ), clsdict)
@@ -1,138 +0,0 @@
Metadata-Version: 2.1
Name: django-excel-response2
Version: 3.0.6
Summary: A function extends of Tarken's django-excel-response
Home-page: https://github.com/django-xxx/django-excel-response2
Author: Hackathon
Author-email: kimi.huang@brightcells.com
Keywords: django-excel-response django-excel-response2
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Framework :: Django
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Office/Business :: Financial :: Spreadsheet
Description-Content-Type: text/markdown
Requires-Dist: django-six (>=1.0.4)
Requires-Dist: excel-base (>=1.0.3)
# django-excel-response2
A function extends of Tarken's django-excel-response
## django-excel-response
A subclass of HttpResponse which will transform a QuerySet,
or sequence of sequences, into either an Excel spreadsheet or
CSV file formatted for Excel, depending on the amount of data.
All of this is done in-memory and on-the-fly, with no disk writes,
thanks to the StringIO library.
* DjangoSnippets - http://djangosnippets.org/snippets/1151/
* PyPI - https://pypi.python.org/pypi/django-excel-response/1.0
## django-excel-response2
When using Tarken’s django-excel-response.
We find that Chinese is messed code when we open .xls in Mac OS.
As discussed in http://segmentfault.com/q/1010000000095546.
We realize django-excel-response2 Based on Tarken’s django-excel-response
to solve this problem By adding a Param named font to set font.
At The Same Time:
* Fix Bug
* can't subtract offset-naive and offset-aware datetimes
## Inherit
# Since Version 2.0.2
if 'FileResponse' in names:
ExcelResponse = type('ExcelResponse', (http.FileResponse, ), dict(__init__=__init__))
elif 'StreamingHttpResponse' in names:
ExcelResponse = type('StreamingHttpResponse', (http.StreamingHttpResponse, ), dict(__init__=__init__))
else:
ExcelResponse = type('HttpResponse', (http.HttpResponse, ), dict(__init__=__init__))
## Installation
pip install django-excel-response2
## Usage
from django_excel_response import ExcelResponse
def excelview(request):
objs = SomeModel.objects.all()
return ExcelResponse(objs)
or
from django_excel_response import ExcelResponse
def excelview(request):
data = [
{
'Column 1': 1,
'Column 2': 2,
},
{
'Column 1': 3,
'Column 2': 4,
}
]
return ExcelResponse(data, 'my_data', font='name SimSum')
or
from django_excel_response import ExcelResponse
def excelview(request):
data = [
['Column 1', 'Column 2'],
[1, 2],
[3, 4]
]
return ExcelResponse(data, 'my_data', font='name SimSum')
or
from django_excel_response import ExcelResponse
def excelview(request):
data = [
['Column 1', 'Column 2'],
[1, [2, 3]],
[3, 4]
]
return ExcelResponse(data, 'my_data', font='name SimSum', merge_type='row_merge')
## Params
* font='name SimSum'
* Set Font as SimSum(宋体)
* force_csv=True
* CSV Format? True for Yes, False for No, Default is False
## CSV
```python
datas = [
[u'中文', ]
]
```
| | Win Excel 2013 | Mac Excel 2011 | Mac Excel 2016 | Mac Numbers |
| --------------- | :------------: | :------------: | :------------: | :---------: |
| UTF8 | Messy | Messy | Messy | Normal |
| GB18030 | Normal | Normal | Normal | Messy |
| UTF8 + BOM_UTF8 | Normal | Messy | Normal | Normal |
| UTF16LE + BOM | | | | |
@@ -1,10 +0,0 @@
django_excel_response/__init__.py,sha256=j9HFW5J7Tk7hpDWEWgu_5RJ3tBEKjxoSsL90QetuTqI,150
django_excel_response/__pycache__/__init__.cpython-312.pyc,,
django_excel_response/__pycache__/excel_response.cpython-312.pyc,,
django_excel_response/excel_response.py,sha256=jt46q1ekSPIyomVEFrVnwtZF10Az3JdzLzguz5V3kLw,5312
django_excel_response2-3.0.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
django_excel_response2-3.0.6.dist-info/METADATA,sha256=RMFJVB3RusjCgEKUu9GpagC_SrFF6r8n6QNS5jSC8XA,3996
django_excel_response2-3.0.6.dist-info/RECORD,,
django_excel_response2-3.0.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
django_excel_response2-3.0.6.dist-info/WHEEL,sha256=bb2Ot9scclHKMOLDEHY6B2sicWOgugjFKaJsT7vwMQo,110
django_excel_response2-3.0.6.dist-info/top_level.txt,sha256=Ii30k4HTp1jPyPH1a_gw_il02gb7wLnK0KtBaAmPDnY,22
@@ -1,6 +0,0 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.38.4)
Root-Is-Purelib: true
Tag: py2-none-any
Tag: py3-none-any
@@ -1,6 +0,0 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.38.4)
Root-Is-Purelib: true
Tag: py2-none-any
Tag: py3-none-any
@@ -1,36 +0,0 @@
Metadata-Version: 2.1
Name: excel-base
Version: 1.0.4
Summary: Excel Base
Home-page: https://github.com/Brightcells/excel-base
Author: Hackathon
Author-email: kimi.huang@brightcells.com
Keywords: Excel Base
Classifier: License :: OSI Approved :: BSD License
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.5
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.2
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: 3.4
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Description-Content-Type: text/markdown
Requires-Dist: xlwt
Requires-Dist: screen
Requires-Dist: TimeConvert (>=1.5.3)
# excel-base
Excel Base
## Installation
```shell
pip install excel-base
```
## Usage
```python
from excel_base import as_csv, as_dict_row_merge_xls, as_list_row_merge_xls, as_row_merge_xls, as_xls
```
@@ -1,12 +0,0 @@
excel_base-1.0.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
excel_base-1.0.4.dist-info/METADATA,sha256=YDQ30H8DCtvBtgumZq0rXb488ch2qhQWZd5J6bGB7yE,1093
excel_base-1.0.4.dist-info/RECORD,,
excel_base-1.0.4.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
excel_base-1.0.4.dist-info/WHEEL,sha256=bb2Ot9scclHKMOLDEHY6B2sicWOgugjFKaJsT7vwMQo,110
excel_base-1.0.4.dist-info/top_level.txt,sha256=Agur3OGDtLquCVy-xnQutcIKdZ6D0jYZZk8R5hxC1F0,11
excel_base/__init__.py,sha256=WMdZNtublXOGVDsL8D_ze0_fYm-JxveqIgcK61gAlZg,252
excel_base/__pycache__/__init__.cpython-312.pyc,,
excel_base/__pycache__/compat.cpython-312.pyc,,
excel_base/__pycache__/excel.cpython-312.pyc,,
excel_base/compat.py,sha256=8KEjD2L-a7fo0izIpRdeIWTktWwMKCbvPT2gV3ga2Qg,760
excel_base/excel.py,sha256=Zy-ua-lHeUaN5P8eFG6kLHRTP5Mj-opsTDK5dEahZbk,12517
@@ -1,6 +0,0 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.38.4)
Root-Is-Purelib: true
Tag: py2-none-any
Tag: py3-none-any
@@ -1,5 +0,0 @@
# -*- coding: utf-8 -*-
from excel_base.compat import *
from excel_base.excel import (LeftMergeCell, MergeCell, UpMergeCell, as_csv, as_dict_row_merge_xls,
as_list_row_merge_xls, as_row_merge_xls, as_xls, use_xls_or_not)
@@ -1,46 +0,0 @@
# -*- coding: utf-8 -*-
"""
pythoncompat
"""
import sys
# -------
# Pythons
# -------
# Syntax sugar.
_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)
#: Python 3.x?
is_py3 = (_ver[0] == 3)
# ---------
# Specifics
# ---------
if is_py2:
builtin_str = str
str = unicode
bytes = str
basestring = basestring
numeric_types = (int, long, float)
try:
from cStringIO import StringIO
from cStringIO import StringIO as BytesIO
except ImportError:
from StringIO import StringIO
from StringIO import StringIO as BytesIO
elif is_py3:
builtin_str = str
str = str
bytes = bytes
basestring = (str, bytes)
numeric_types = (int, float)
from io import BytesIO, StringIO
@@ -1,373 +0,0 @@
# -*- coding:utf-8 -*-
import codecs
import copy
import datetime
import json
from collections import deque
import screen
import xlwt
from TimeConvert import TimeConvert as tc
from .compat import basestring, str
class LeftMergeCell(object):
pass
class UpMergeCell(object):
pass
class MergeCell(object):
LeftMerge = LeftMergeCell()
UpMerge = UpMergeCell()
@property
def use_xls_or_not(self):
if len(self.data) > 1:
return True
if self.force_csv:
return False
for sheet_info in self.data.values():
if len(sheet_info.get('data') or []) > self.EXCEL_MAXIMUM_ALLOWED_ROWS:
return False
return True
def get_merged_rows_num(data):
return max(sum(get_merged_rows_num(d) if isinstance(d, list) else 0 for d in data), 1)
def row_preprocessing(data, mapping):
field_key = mapping.get('field_key')
field_key = field_key if isinstance(field_key, list) else [field_key]
data_key = mapping.get('data_key')
nextmapping = mapping.get('next')
field_value = [data.get(key) for key in field_key]
return field_value + [data_preprocessing(data.get(data_key), nextmapping)] if nextmapping else field_value
def data_preprocessing(data, mapping):
data = data if isinstance(data, list) else [data]
return [row_preprocessing(item, mapping) for item in data or [{}]]
def get_header_cell_styles(self):
al = xlwt.Alignment()
al.horz = self.hhorz
al.vert = self.hvert
font = xlwt.Font()
if self.font:
font.name = self.font
font.bold = True
datetime_style = xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss')
datetime_style.alignment = al
datetime_style.font = font
date_style = xlwt.easyxf(num_format_str='yyyy-mm-dd')
date_style.alignment = al
date_style.font = font
time_style = xlwt.easyxf(num_format_str='hh:mm:ss')
time_style.alignment = al
time_style.font = font
dafault_style = xlwt.Style.default_style
dafault_style.alignment = al
dafault_style.font = font
return copy.deepcopy({
'datetime': datetime_style,
'date': date_style,
'time': time_style,
'default': dafault_style,
})
def get_cell_styles(self):
al = xlwt.Alignment()
al.horz = self.horz
al.vert = self.vert
font = xlwt.Font()
if self.font:
font.name = self.font
datetime_style = xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss')
datetime_style.alignment = al
datetime_style.font = font
date_style = xlwt.easyxf(num_format_str='yyyy-mm-dd')
date_style.alignment = al
date_style.font = font
time_style = xlwt.easyxf(num_format_str='hh:mm:ss')
time_style.alignment = al
time_style.font = font
dafault_style = xlwt.Style.default_style
dafault_style.alignment = al
dafault_style.font = font
return copy.deepcopy({
'datetime': datetime_style,
'date': date_style,
'time': time_style,
'default': dafault_style,
})
def get_cell_info(self, value, cell_styles):
if value is None and self.blanks_for_none:
value = ''
if isinstance(value, datetime.datetime):
if tc.is_aware(value):
value = tc.make_naive(value, self.timezone)
cell_style = cell_styles['datetime']
elif isinstance(value, datetime.date):
cell_style = cell_styles['date']
elif isinstance(value, datetime.time):
cell_style = cell_styles['time']
else:
cell_style = cell_styles['default']
return value, cell_style
def auto_adjust_width(self, sheet, colx, value, widths):
# Columns have a property for setting the width.
# The value is an integer specifying the size measured in 1/256
# of the width of the character '0' as it appears in the sheet's default font.
# xlwt creates columns with a default width of 2962, roughly equivalent to 11 characters wide.
#
# https://github.com/python-excel/xlwt/blob/master/xlwt/BIFFRecords.py#L1675
# Offset Size Contents
# 4 2 Width of the columns in 1/256 of the width of the zero character, using default font
# (first FONT record in the file)
#
# Default Width: https://github.com/python-excel/xlwt/blob/master/xlwt/Column.py#L14
# self.width = 0x0B92
if not self.auto_adjust_width:
return
width = screen.calc_width(value) * 256 if isinstance(value, basestring) else screen.calc_width(str(value)) * 256
if width <= widths.get(colx, 0):
return
width = min(width, self.EXCEL_MAXIMUM_ALLOWED_COLUMN_WIDTH)
widths[colx] = width
sheet.col(colx).width = max(width, self.min_cell_width)
def generate_headers(headers):
if not headers:
return []
if isinstance(headers, list) and isinstance(headers[0], list):
return headers
return [headers]
def generate_sheet_info(sheet_info):
sheet_data = sheet_info.get('data')
sheet_mapping = sheet_info.get('mapping')
sheet_info['data'] = data_preprocessing(sheet_data, sheet_mapping)
return sheet_info
def write_header_cells(self, sheet, headers, widths):
if not headers or not isinstance(headers, list):
return
if not headers[0] or not isinstance(headers[0], list):
return
rlen, clen = len(headers), len(headers[0])
ignore_header_cells = set()
header_cell_styles = get_header_cell_styles(self)
for i in range(rlen):
for j in range(clen):
# If cell is MergeCell, direct continue
if isinstance(headers[i][j], (LeftMergeCell, UpMergeCell)):
continue
# If cell is IgnoreCell, direct continue
if (i, j) in ignore_header_cells:
continue
# Set r1/r2/c1/c2 for sheet.write_merge
r1, r2, c1, c2 = i, i, j, j
# Down for merge cells
for r2 in range(r1 + 1, rlen):
if (r2, c1) in ignore_header_cells:
break
if not isinstance(headers[r2][c1], UpMergeCell):
r2 -= 1
break
# Right for merge cells
for c2 in range(c1 + 1, clen):
if (r1, c2) in ignore_header_cells:
break
if not isinstance(headers[r1][c2], LeftMergeCell):
c2 -= 1
break
# Ignore cells
for k in range(r1, r2 + 1):
for m in range(c1, c2 + 1):
ignore_header_cells.add((k, m))
value = headers[r1][c1]
value, cell_style = get_cell_info(self, value, header_cell_styles)
sheet.write_merge(r1, r2, c1, c2, value, style=cell_style)
if c1 == c2:
auto_adjust_width(self, sheet, c1, value, widths)
@property
def as_xls(self):
if not isinstance(self.data, dict):
self.data = {self.sheet_name: {'data': self.data, 'headers': self.headers}}
cell_styles = get_cell_styles(self)
book = xlwt.Workbook(encoding=self.encoding)
for sheet_name, sheet_info in self.data.items():
sheet_data = sheet_info.get('data') or []
sheet_headers = generate_headers(sheet_info.get('headers'))
sheet = book.add_sheet(sheet_name)
widths = {}
# Write header cells
write_header_cells(self, sheet, sheet_headers, widths)
rowx = len(sheet_headers) # Data start row index
for row in sheet_data:
for colx, value in enumerate(row):
if value is None and self.blanks_for_none:
value = ''
value, cell_style = get_cell_info(self, value, cell_styles)
sheet.write(rowx, colx, value, style=cell_style)
auto_adjust_width(self, sheet, colx, value, widths)
rowx += 1 # Update row index
book.save(self.output)
@property
def as_row_merge_xls(self):
if not isinstance(self.data, dict):
self.data = {self.sheet_name: {'data': self.data, 'headers': self.headers}}
cell_styles = get_cell_styles(self)
book = xlwt.Workbook(encoding=self.encoding)
for sheet_name, sheet_info in self.data.items():
sheet_data = sheet_info.get('data') or []
sheet_headers = generate_headers(sheet_info.get('headers'))
sheet = book.add_sheet(sheet_name)
widths = {}
# Write header cells
write_header_cells(self, sheet, sheet_headers, widths)
rowx = len(sheet_headers) # Data start row index
for row in sheet_data:
# Max row number for current row
rowmax = max([(len(r) if isinstance(r, list) else 1) for r in row])
for colx, value in enumerate(row):
if isinstance(value, list):
for vx, val in enumerate(value):
val, cell_style = get_cell_info(self, val, cell_styles)
sheet.write(rowx + vx, colx, val, style=cell_style)
auto_adjust_width(self, sheet, colx, val, widths)
else:
value, cell_style = get_cell_info(self, value, cell_styles)
sheet.write_merge(rowx, rowx + rowmax - 1, colx, colx, value, style=cell_style)
auto_adjust_width(self, sheet, colx, value, widths)
rowx += rowmax # Update row index
book.save(self.output)
@property
def as_list_row_merge_xls(self):
if not isinstance(self.data, dict):
self.data = {self.sheet_name: {'data': self.data, 'headers': self.headers}}
cell_styles = get_cell_styles(self)
book = xlwt.Workbook(encoding=self.encoding)
q = deque()
for sheet_name, sheet_info in self.data.items():
sheet_data = sheet_info.get('data') or []
sheet_headers = generate_headers(sheet_info.get('headers'))
sheet = book.add_sheet(sheet_name)
widths = {}
# Write header cells
write_header_cells(self, sheet, sheet_headers, widths)
rowx = len(sheet_headers) # Data start row index
colx = 0
for row in sheet_data:
rowmax = 1
_rowx = rowx
_rowxd = {}
q.append(json.dumps([colx, row], ensure_ascii=False))
while q:
colx, rowdata = json.loads(q.popleft())
mergedrowsnum = get_merged_rows_num(rowdata)
rowmax = max(rowmax, mergedrowsnum)
for idx, value in enumerate(rowdata):
_colx = colx + idx
if isinstance(value, list):
for d in value:
q.append(json.dumps([_colx, d], ensure_ascii=False))
else:
_rowx = _rowxd.get(_colx, rowx)
_rowxd[_colx] = _rowx + mergedrowsnum
value, cell_style = get_cell_info(self, value, cell_styles)
sheet.write_merge(_rowx, _rowx + mergedrowsnum - 1, _colx, _colx, value, style=cell_style)
auto_adjust_width(self, sheet, _colx, value, widths)
rowx += rowmax # Update row index
colx = 0
book.save(self.output)
@property
def as_dict_row_merge_xls(self):
if not isinstance(self.data, dict):
self.data = {self.sheet_name: {'data': self.data, 'mapping': self.mapping, 'headers': self.headers}}
self.data = {sheet_name: generate_sheet_info(sheet_info) for sheet_name, sheet_info in self.data.items()}
self.as_list_row_merge_xls
@property
def as_csv(self):
# https://stackoverflow.com/questions/4348802/how-can-i-output-a-utf-8-csv-in-php-that-excel-will-read-properly?answertab=votes
# https://stackoverflow.com/questions/155097/microsoft-excel-mangles-diacritics-in-csv-files/1648671#1648671
# https://wiki.scn.sap.com/wiki/display/ABAP/CSV+tests+of+encoding+and+column+separator?original_fqdn=wiki.sdn.sap.com
if self.encoding == 'utf-8-sig':
self.output.write(codecs.BOM_UTF8)
if not self.data:
return
for row in list(self.data.values())[0].get('data') or []:
out_row = []
for value in row:
if value is None and self.blanks_for_none:
value = ''
if not isinstance(value, basestring):
value = str(value)
out_row.append(value.replace('"', '""').encode(self.encoding))
self.output.write(b'"%s"\n' % b'","'.join(out_row))
@@ -1,49 +0,0 @@
Metadata-Version: 2.4
Name: screen
Version: 1.0.1
Summary: Screen width and so on
Home-page: https://github.com/Brightcells/screen
Author: Hackathon
Author-email: kimi.huang@brightcells.com
Classifier: License :: OSI Approved :: BSD License
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.5
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.2
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: 3.4
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: home-page
Dynamic: summary
======
screen
======
Screen width and so on
Installation
============
::
pip install screen
Usage
=====
::
import screen
screen.calc_width(u'测试',0, 2)
@@ -1,13 +0,0 @@
screen-1.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
screen-1.0.1.dist-info/METADATA,sha256=h-AgBJKNTSYSD3bmbsgxfAzX6H3wQjxj0Ft6uG37Yx4,1047
screen-1.0.1.dist-info/RECORD,,
screen-1.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
screen-1.0.1.dist-info/WHEEL,sha256=UKM62ksD4jd3M6k5acFAaw8CHnQfpjto_KljRXbypP0,104
screen-1.0.1.dist-info/top_level.txt,sha256=vnY9AHK-PF6HjM7STYkeahHXwJ4-OLDHyYJtbXijbgI,7
screen/__init__.py,sha256=XzG5jMc7x8OF6i29Y8HJ5DBKYolJdfe5y_dmoj3J1U4,97
screen/__pycache__/__init__.cpython-312.pyc,,
screen/__pycache__/compat.cpython-312.pyc,,
screen/__pycache__/old_str_util.cpython-312.pyc,,
screen/compat.py,sha256=vULU7_P9xuGfvEJanLC_hx3MFvgDHBAYG9uVVCJFLI4,1546
screen/old_str_util.py,sha256=9v7ixZJSuhTSftdWRPrQ0CuVDbaFiEkbgVNW1rMX8Ww,10253
screen/str_util.cpython-312-x86_64-linux-musl.so,sha256=1JNrwlRyrh2YByK6NceaG9yMi_GFT1e_3NdqaLhKmTQ,53416
@@ -1,4 +0,0 @@
try:
from screen.str_util import *
except ImportError:
from screen.old_str_util import *
@@ -1,47 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Urwid python compatibility definitions
# Copyright (C) 2011 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: http://excess.org/urwid/
import sys
try: # python 2.4 and 2.5 compat
bytes = bytes
except NameError:
bytes = str
PYTHON3 = sys.version_info > (3, 0)
# for iterating over byte strings:
# ord2 calls ord in python2 only
# chr2 converts an ordinal value to a length-1 byte string
# B returns a byte string in all supported python versions
# bytes3 creates a byte string from a list of ordinal values
if PYTHON3:
ord2 = lambda x: x
chr2 = lambda x: bytes([x])
B = lambda x: x.encode('iso8859-1')
bytes3 = bytes
else:
ord2 = ord
chr2 = chr
B = lambda x: x
bytes3 = lambda x: bytes().join([chr(c) for c in x])
@@ -1,386 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Urwid unicode character processing tables
# Copyright (C) 2004-2011 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: http://excess.org/urwid/
from __future__ import print_function
import re
from .compat import B, bytes, ord2
SAFE_ASCII_RE = re.compile(u"^[ -~]*$")
SAFE_ASCII_BYTES_RE = re.compile(B("^[ -~]*$"))
_byte_encoding = None
# GENERATED DATA
# generated from
# http://www.unicode.org/Public/4.0-Update/EastAsianWidth-4.0.0.txt
widths = [
(126, 1),
(159, 0),
(687, 1),
(710, 0),
(711, 1),
(727, 0),
(733, 1),
(879, 0),
(1154, 1),
(1161, 0),
(4347, 1),
(4447, 2),
(7467, 1),
(7521, 0),
(8369, 1),
(8426, 0),
(9000, 1),
(9002, 2),
(11021, 1),
(12350, 2),
(12351, 1),
(12438, 2),
(12442, 0),
(19893, 2),
(19967, 1),
(55203, 2),
(63743, 1),
(64106, 2),
(65039, 1),
(65059, 0),
(65131, 2),
(65279, 1),
(65376, 2),
(65500, 1),
(65510, 2),
(120831, 1),
(262141, 2),
(1114109, 1),
]
# ACCESSOR FUNCTIONS
def get_width(o):
"""Return the screen column width for unicode ordinal o."""
global widths
if o == 0xe or o == 0xf:
return 0
for num, wid in widths:
if o <= num:
return wid
return 1
def decode_one(text, pos):
"""
Return (ordinal at pos, next position) for UTF-8 encoded text.
"""
assert isinstance(text, bytes), text
b1 = ord2(text[pos])
if not b1 & 0x80:
return b1, pos + 1
error = ord("?"), pos + 1
lt = len(text) - pos
if lt < 2:
return error
if b1 & 0xe0 == 0xc0:
b2 = ord2(text[pos + 1])
if b2 & 0xc0 != 0x80:
return error
o = ((b1 & 0x1f) << 6) | (b2 & 0x3f)
if o < 0x80:
return error
return o, pos + 2
if lt < 3:
return error
if b1 & 0xf0 == 0xe0:
b2 = ord2(text[pos + 1])
if b2 & 0xc0 != 0x80:
return error
b3 = ord2(text[pos + 2])
if b3 & 0xc0 != 0x80:
return error
o = ((b1 & 0x0f) << 12) | ((b2 & 0x3f) << 6) | (b3 & 0x3f)
if o < 0x800:
return error
return o, pos + 3
if lt < 4:
return error
if b1 & 0xf8 == 0xf0:
b2 = ord2(text[pos + 1])
if b2 & 0xc0 != 0x80:
return error
b3 = ord2(text[pos + 2])
if b3 & 0xc0 != 0x80:
return error
b4 = ord2(text[pos + 2])
if b4 & 0xc0 != 0x80:
return error
o = ((b1 & 0x07) << 18) | ((b2 & 0x3f) << 12) | ((b3 & 0x3f) << 6) | (b4 & 0x3f)
if o < 0x10000:
return error
return o, pos + 4
return error
def decode_one_uni(text, i):
"""
decode_one implementation for unicode strings
"""
return ord(text[i]), i + 1
def decode_one_right(text, pos):
"""
Return (ordinal at pos, next position) for UTF-8 encoded text.
pos is assumed to be on the trailing byte of a utf-8 sequence.
"""
assert isinstance(text, bytes), text
error = ord("?"), pos - 1
p = pos
while p >= 0:
if ord2(text[p]) & 0xc0 != 0x80:
o, next = decode_one(text, p)
return o, p - 1
p -= 1
if p == p - 4:
return error
def set_byte_encoding(enc):
assert enc in ('utf8', 'narrow', 'wide')
global _byte_encoding
_byte_encoding = enc
def get_byte_encoding():
return _byte_encoding
def calc_text_pos(text, start_offs, end_offs, pref_col):
"""
Calculate the closest position to the screen column pref_col in text
where start_offs is the offset into text assumed to be screen column 0
and end_offs is the end of the range to search.
text may be unicode or a byte string in the target _byte_encoding
Returns (position, actual_col).
"""
assert start_offs <= end_offs, repr((start_offs, end_offs))
utfs = isinstance(text, bytes) and _byte_encoding == "utf8"
unis = not isinstance(text, bytes)
if unis or utfs:
decode = [decode_one, decode_one_uni][unis]
i = start_offs
sc = 0
n = 1 # number to advance by
while i < end_offs:
o, n = decode(text, i)
w = get_width(o)
if w + sc > pref_col:
return i, sc
i = n
sc += w
return i, sc
assert type(text) == bytes, repr(text)
# "wide" and "narrow"
i = start_offs + pref_col
if i >= end_offs:
return end_offs, end_offs - start_offs
if _byte_encoding == "wide":
if within_double_byte(text, start_offs, i) == 2:
i -= 1
return i, i - start_offs
def calc_width(text, start_offs=0, end_offs=0):
"""
Return the screen column width of text between start_offs and end_offs.
text may be unicode or a byte string in the target _byte_encoding
Some characters are wide (take two columns) and others affect the
previous character (take zero columns). Use the widths table above
to calculate the screen column width of text[start_offs:end_offs]
"""
lt = len(text)
if (end_offs == 0) or (end_offs == -1) or (end_offs > lt):
end_offs = lt
assert start_offs <= end_offs, repr((start_offs, end_offs))
utfs = isinstance(text, bytes) and _byte_encoding == "utf8"
unis = not isinstance(text, bytes)
if (unis and not SAFE_ASCII_RE.match(text)) or (utfs and not SAFE_ASCII_BYTES_RE.match(text)):
decode = [decode_one, decode_one_uni][unis]
i = start_offs
sc = 0
n = 1 # number to advance by
while i < end_offs:
o, n = decode(text, i)
w = get_width(o)
i = n
sc += w
return sc
# "wide", "narrow" or all printable ASCII, just return the character count
return end_offs - start_offs
def is_wide_char(text, offs):
"""
Test if the character at offs within text is wide.
text may be unicode or a byte string in the target _byte_encoding
"""
if isinstance(text, unicode):
o = ord(text[offs])
return get_width(o) == 2
assert isinstance(text, bytes)
if _byte_encoding == "utf8":
o, n = decode_one(text, offs)
return get_width(o) == 2
if _byte_encoding == "wide":
return within_double_byte(text, offs, offs) == 1
return False
def move_prev_char(text, start_offs, end_offs):
"""
Return the position of the character before end_offs.
"""
assert start_offs < end_offs
if isinstance(text, unicode):
return end_offs - 1
assert isinstance(text, bytes)
if _byte_encoding == "utf8":
o = end_offs - 1
while ord2(text[o]) & 0xc0 == 0x80:
o -= 1
return o
if _byte_encoding == "wide" and within_double_byte(text, start_offs, end_offs - 1) == 2:
return end_offs - 2
return end_offs - 1
def move_next_char(text, start_offs, end_offs):
"""
Return the position of the character after start_offs.
"""
assert start_offs < end_offs
if isinstance(text, unicode):
return start_offs + 1
assert isinstance(text, bytes)
if _byte_encoding == "utf8":
o = start_offs + 1
while o < end_offs and ord2(text[o]) & 0xc0 == 0x80:
o += 1
return o
if _byte_encoding == "wide" and within_double_byte(text, start_offs, start_offs) == 1:
return start_offs + 2
return start_offs + 1
def within_double_byte(text, line_start, pos):
"""Return whether pos is within a double-byte encoded character.
text -- byte string in question
line_start -- offset of beginning of line (< pos)
pos -- offset in question
Return values:
0 -- not within dbe char, or double_byte_encoding == False
1 -- pos is on the 1st half of a dbe char
2 -- pos is on the 2nd half of a dbe char
"""
assert isinstance(text, bytes)
v = ord2(text[pos])
if 0x40 <= v < 0x7f:
# might be second half of big5, uhc or gbk encoding
if pos == line_start:
return 0
if ord2(text[pos - 1]) >= 0x81:
if within_double_byte(text, line_start, pos - 1) == 1:
return 2
return 0
if v < 0x80:
return 0
i = pos - 1
while i >= line_start:
if ord2(text[i]) < 0x80:
break
i -= 1
if (pos - i) & 1:
return 1
return 2
# TABLE GENERATION CODE
def process_east_asian_width():
import sys
out = []
last = None
for line in sys.stdin.readlines():
if line[:1] == "#":
continue
line = line.strip()
hex, rest = line.split(";", 1)
wid, rest = rest.split(" # ", 1)
word1 = rest.split(" ", 1)[0]
if "." in hex:
hex = hex.split("..")[1]
num = int(hex, 16)
if word1 in ("COMBINING", "MODIFIER", "<control>"):
l = 0
elif wid in ("W", "F"):
l = 2
else:
l = 1
if last is None:
out.append((0, l))
last = l
if last == l:
out[-1] = (num, l)
else:
out.append((num, l))
last = l
print("widths = [")
for o in out[1:]: # treat control characters same as ascii
print("\t%r," % (o,))
print("]")
if __name__ == "__main__":
process_east_asian_width()
@@ -1,5 +0,0 @@
Wheel-Version: 1.0
Generator: setuptools (84.0.0)
Root-Is-Purelib: false
Tag: cp312-cp312-musllinux_1_2_x86_64
@@ -5,13 +5,13 @@ TimeConvert-3.0.13.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJ
TimeConvert-3.0.13.dist-info/WHEEL,sha256=kGT74LWyRUZrL4VgLh6_g12IeVl_9u9ZVhadrgXZUEY,110
TimeConvert-3.0.13.dist-info/top_level.txt,sha256=tSqgh7_R-u6Jq-dHLEqEEdmuHwgYU7sOHVCpEA9IWbk,12
TimeConvert/__init__.py,sha256=MC8k8GuaeAYRp3NxWd5p26geh22cowqlmcZd0CBrl98,398
TimeConvert/__pycache__/__init__.cpython-312.pyc,,
TimeConvert/__pycache__/convert.cpython-312.pyc,,
TimeConvert/__pycache__/isoweek.cpython-312.pyc,,
TimeConvert/__pycache__/month.cpython-312.pyc,,
TimeConvert/__pycache__/quarter.cpython-312.pyc,,
TimeConvert/__pycache__/stopwatch.cpython-312.pyc,,
TimeConvert/__pycache__/week.cpython-312.pyc,,
TimeConvert/__pycache__/__init__.cpython-314.pyc,,
TimeConvert/__pycache__/convert.cpython-314.pyc,,
TimeConvert/__pycache__/isoweek.cpython-314.pyc,,
TimeConvert/__pycache__/month.cpython-314.pyc,,
TimeConvert/__pycache__/quarter.cpython-314.pyc,,
TimeConvert/__pycache__/stopwatch.cpython-314.pyc,,
TimeConvert/__pycache__/week.cpython-314.pyc,,
TimeConvert/convert.py,sha256=0HazKnPWkleBN5RHJCGPNFwJRvyiSX8ThPODfQ73mic,70042
TimeConvert/isoweek.py,sha256=7jZ2OWxDEAQY1Rhynjg96mWSB2IjjSbKC2HhxEqiJcw,6423
TimeConvert/month.py,sha256=n4SnpKFE51ewPtiWxqjDwMJPFh605Crp59_LaNEcVZ4,10946
@@ -6,20 +6,20 @@ amqp-5.4.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
amqp-5.4.1.dist-info/licenses/LICENSE,sha256=9e9fEoLq4ZMcdGRfhxm2xps9aizyd7_aJJqCcM1HOvM,2372
amqp-5.4.1.dist-info/top_level.txt,sha256=tWQNmFVhU4UtDgB6Yy2lKqRz7LtOrRcN8_bPFVcVVR8,5
amqp/__init__.py,sha256=YtyjArlR795PloXjGIjzAU2FboPzCYa9mpFRyKHvDzI,2345
amqp/__pycache__/__init__.cpython-312.pyc,,
amqp/__pycache__/abstract_channel.cpython-312.pyc,,
amqp/__pycache__/basic_message.cpython-312.pyc,,
amqp/__pycache__/channel.cpython-312.pyc,,
amqp/__pycache__/connection.cpython-312.pyc,,
amqp/__pycache__/exceptions.cpython-312.pyc,,
amqp/__pycache__/method_framing.cpython-312.pyc,,
amqp/__pycache__/platform.cpython-312.pyc,,
amqp/__pycache__/protocol.cpython-312.pyc,,
amqp/__pycache__/sasl.cpython-312.pyc,,
amqp/__pycache__/serialization.cpython-312.pyc,,
amqp/__pycache__/spec.cpython-312.pyc,,
amqp/__pycache__/transport.cpython-312.pyc,,
amqp/__pycache__/utils.cpython-312.pyc,,
amqp/__pycache__/__init__.cpython-314.pyc,,
amqp/__pycache__/abstract_channel.cpython-314.pyc,,
amqp/__pycache__/basic_message.cpython-314.pyc,,
amqp/__pycache__/channel.cpython-314.pyc,,
amqp/__pycache__/connection.cpython-314.pyc,,
amqp/__pycache__/exceptions.cpython-314.pyc,,
amqp/__pycache__/method_framing.cpython-314.pyc,,
amqp/__pycache__/platform.cpython-314.pyc,,
amqp/__pycache__/protocol.cpython-314.pyc,,
amqp/__pycache__/sasl.cpython-314.pyc,,
amqp/__pycache__/serialization.cpython-314.pyc,,
amqp/__pycache__/spec.cpython-314.pyc,,
amqp/__pycache__/transport.cpython-314.pyc,,
amqp/__pycache__/utils.cpython-314.pyc,,
amqp/abstract_channel.py,sha256=npzr6eqDgMey0bnBMzj_sgO9v2Vlv0J5aq-7TuA8ULQ,5084
amqp/basic_message.py,sha256=Q8DV31tuuphloTETPHiJFwNg6b5M6pccJ0InJ4MZUz8,3357
amqp/channel.py,sha256=1JI62ylREhS2x86jyRLbq1It8eCnz7Yapl0JMC5Rjtg,74694
@@ -1,4 +1,4 @@
__pycache__/appdirs.cpython-312.pyc,,
__pycache__/appdirs.cpython-314.pyc,,
appdirs-1.4.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
appdirs-1.4.4.dist-info/LICENSE.txt,sha256=Nt200KdFqTqyAyA9cZCBSxuJcn0lTK_0jHp6-71HAAs,1097
appdirs-1.4.4.dist-info/METADATA,sha256=k5TVfXMNKGHTfp2wm6EJKTuGwGNuoQR5TqQgH8iwG8M,8981
Loaded 100 of 7687 files, more files were not shown because too many files have changed in this diff. Show more