-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path__init__.py
206 lines (174 loc) · 6.13 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
from datasette import hookimpl
from datasette.utils.asgi import Response, Forbidden
from charset_normalizer import detect
from starlette.requests import Request
from urllib.parse import quote_plus
import csv as csv_std
import codecs
import datetime
import io
import os
import sqlite_utils
from sqlite_utils.utils import TypeTracker
import uuid
@hookimpl
def permission_allowed(actor, action):
if action == "upload-csvs" and actor and actor.get("id") == "root":
return True
@hookimpl
def register_routes():
return [
(r"^/-/upload-csvs$", upload_csvs),
(r"^/-/upload-csv$", lambda: Response.redirect("/-/upload-csvs")),
]
@hookimpl
def menu_links(datasette, actor):
async def inner():
if await datasette.permission_allowed(
actor, "upload-csvs", default=False
) and any(
db.is_mutable and db.name not in ("_memory", "_internal")
for db in datasette.databases.values()
):
return [
{"href": datasette.urls.path("/-/upload-csvs"), "label": "Upload CSVs"},
]
return inner
async def upload_csvs(scope, receive, datasette, request):
if not await datasette.permission_allowed(
request.actor, "upload-csvs", default=False
):
raise Forbidden("Permission denied for upload-csvs")
num_bytes_to_detect_with = 2048 * 1024
# ?_num_bytes= can over-ride this, used by the tests
if request.args.get("_num_bytes_to_detect_with"):
num_bytes_to_detect_with = int(request.args["_num_bytes_to_detect_with"])
# For the moment just use the first database that's not immutable
dbs = [
db
for db in datasette.databases.values()
if db.is_mutable and db.name not in ("_internal", "_memory")
]
if not dbs:
raise Forbidden("No mutable databases available")
db = dbs[0]
# We need the ds_request to pass to render_template for CSRF tokens
ds_request = request
# We use the Starlette request object to handle file uploads
starlette_request = Request(scope, receive)
if starlette_request.method != "POST":
return Response.html(
await datasette.render_template(
"upload_csv.html", {"database_name": db.name}, request=ds_request
)
)
formdata = await starlette_request.form()
csv = formdata["csv"]
# csv.file is a SpooledTemporaryFile. csv.filename is the filename
table_name = formdata.get("table")
if not table_name:
table_name = csv.filename
if table_name.endswith(".csv"):
table_name = table_name[:-4]
# If the table already exists, add a suffix
suffix = 2
base_table_name = table_name
while await db.table_exists(table_name):
table_name = "{}_{}".format(base_table_name, suffix)
suffix += 1
total_size = get_temporary_file_size(csv.file)
task_id = str(uuid.uuid4())
# Use the first 2MB to detect the character encoding
first_bytes = csv.file.read(num_bytes_to_detect_with)
csv.file.seek(0)
encoding = detect(first_bytes)["encoding"]
# latin-1 is a superset of ascii, and less likely to hit errors
# https://github.com/simonw/datasette-upload-csvs/issues/25
if encoding == "ascii":
encoding = "latin-1"
def insert_initial_record(conn):
database = sqlite_utils.Database(conn)
database["_csv_progress_"].insert(
{
"id": task_id,
"table_name": table_name,
"bytes_todo": total_size,
"bytes_done": 0,
"rows_done": 0,
"started": str(datetime.datetime.utcnow()),
"completed": None,
"error": None,
},
pk="id",
alter=True,
)
await db.execute_write_fn(insert_initial_record)
def insert_docs(database):
reader = csv_std.reader(codecs.iterdecode(csv.file, encoding))
headers = next(reader)
tracker = TypeTracker()
docs = tracker.wrap(dict(zip(headers, row)) for row in reader)
i = 0
def docs_with_progress():
nonlocal i
for doc in docs:
i += 1
yield doc
if i % 10 == 0:
database["_csv_progress_"].update(
task_id,
{
"rows_done": i,
"bytes_done": csv.file.tell(),
},
)
database[table_name].insert_all(
docs_with_progress(), alter=True, batch_size=100
)
database["_csv_progress_"].update(
task_id,
{
"rows_done": i,
"bytes_done": total_size,
"completed": str(datetime.datetime.utcnow()),
},
)
# Trasform columns to detected types
database[table_name].transform(types=tracker.types)
return database[table_name].count
def insert_docs_catch_errors(conn):
database = sqlite_utils.Database(conn)
try:
insert_docs(database)
except Exception as error:
database["_csv_progress_"].update(
task_id,
{"error": str(error)},
)
await db.execute_write_fn(insert_docs_catch_errors, block=False)
if formdata.get("xhr"):
return Response.json(
{
"url": datasette.urls.table(db.name, table_name),
"database_path": quote_plus(db.name),
"task_id": task_id,
"bytes_todo": total_size,
}
)
return Response.html(
await datasette.render_template(
"upload_csv_done.html",
{
"database": db.name,
"table": table_name,
"table_url": datasette.urls.table(db.name, table_name),
},
)
)
def get_temporary_file_size(file):
if isinstance(file._file, (io.BytesIO, io.StringIO)):
return len(file._file.getvalue())
try:
return os.fstat(file._file.fileno()).st_size
except Exception:
raise