Skip to content

Commit 33f0d28

Browse files
committed
feat(Lib/urllib.request): sup js
1 parent cff9817 commit 33f0d28

2 files changed

Lines changed: 81 additions & 9 deletions

File tree

‎npython.nimble‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ pylib "intflags", " ^= 0.1.0"
5858
pylib "posixos", " ^= 0.1.0"
5959
pylib "pymath", " ^= 0.1.0"
6060
pylib "pyre", " ^= 0.1.0"
61+
pylib "pysubprocess", " ^= 0.1.0"
6162

6263
# copied from nimpylib.nimble
6364
# at 43378424222610f8ce4a10593bd719691fbb634b

‎npython/builtinModules/urllib/backend.nim‎

Lines changed: 80 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,100 @@ when defined(nimPreviewSlimSystem):
33
import std/assertions
44

55
when defined(js):
6-
import std/jsfetch
6+
import std/strutils
7+
import pysubprocess
78

8-
type ResponseTransport* = object
9+
type
10+
ResponseTransport* = object
11+
content: string
12+
offset: int
13+
14+
var transports: seq[ResponseTransport]
915

10-
proc retainTransport*(transport: var ResponseTransport): int = 0
16+
proc retainTransport*(transport: var ResponseTransport): int =
17+
transports.add move transport
18+
transports.len
1119

1220
proc readTransport*(id, amt: int, content: var string)
1321
{.raises: [OSError, IOError].} =
14-
raise newException(OSError,
15-
"urllib.request.urlopen is synchronous; use an async JS bridge for fetch")
22+
if id <= 0 or id > transports.len:
23+
return
24+
let index = id - 1
25+
if transports[index].offset >= transports[index].content.len:
26+
return
27+
let remaining = transports[index].content.len - transports[index].offset
28+
let length = if amt < 0: remaining else: min(amt, remaining)
29+
content = transports[index].content[transports[index].offset ..<
30+
transports[index].offset + length]
31+
transports[index].offset.inc length
1632

1733
proc closeTransport*(id: var int) {.raises: [LibraryError].} =
34+
if id > 0 and id <= transports.len:
35+
transports[id - 1] = default(ResponseTransport)
1836
id = 0
1937

38+
proc findHeaderEnd(response: string, start: int): int =
39+
let crlfEnd = response.find("\r\n\r\n", start)
40+
if crlfEnd >= 0: crlfEnd + 4
41+
else:
42+
let lfEnd = response.find("\n\n", start)
43+
if lfEnd < 0: -1 else: lfEnd + 2
44+
45+
proc parseCurlResponse(response: string, status: var int, reason: var string,
46+
responseHeaders: var seq[(string, string)], transport: var ResponseTransport)
47+
{.raises: [ValueError].} =
48+
var headerStart = 0
49+
var bodyStart = findHeaderEnd(response, headerStart)
50+
while bodyStart >= 0 and bodyStart + "HTTP/".len <= response.len and
51+
response[bodyStart ..< bodyStart + "HTTP/".len] == "HTTP/":
52+
headerStart = bodyStart
53+
bodyStart = findHeaderEnd(response, headerStart)
54+
if bodyStart < 0:
55+
raise newException(ValueError, "curl returned an invalid HTTP response")
56+
let lines = response[headerStart ..< bodyStart].splitLines()
57+
if lines.len == 0:
58+
raise newException(ValueError, "curl returned an empty HTTP response")
59+
let statusParts = lines[0].splitWhitespace()
60+
if statusParts.len < 2:
61+
raise newException(ValueError, "curl returned an invalid HTTP status")
62+
try:
63+
status = parseInt(statusParts[1])
64+
except ValueError:
65+
raise newException(ValueError, "curl returned an invalid HTTP status")
66+
reason = if statusParts.len > 2: statusParts[2 .. ^1].join(" ") else: ""
67+
if lines.len > 1:
68+
for line in lines[1 .. ^1]:
69+
let separator = line.find(':')
70+
if separator > 0:
71+
responseHeaders.add (line[0 ..< separator], line[separator + 1 .. ^1].strip())
72+
transport.content = response[bodyStart .. ^1]
73+
2074
proc requestHttp*(url, httpMethod, body: string,
2175
headers: openArray[(string, string)]; status: var int,
2276
reason: var string, responseUrl: var string,
2377
responseHeaders: var seq[(string, string)]; transport: var ResponseTransport
2478
) {.raises: [OSError, IOError, ValueError].} =
25-
## `std/jsfetch` is Promise-based and cannot implement synchronous `urlopen`.
26-
discard fetch(url.cstring)
27-
raise newException(OSError,
28-
"urllib.request.urlopen is synchronous; use an async JS bridge for fetch")
79+
var args = @["curl", "--silent", "--show-error", "--location",
80+
"--request", httpMethod, "--dump-header", "-", "--output", "-"]
81+
for (name, value) in headers:
82+
args.add "--header"
83+
args.add name & ": " & value
84+
if body.len > 0:
85+
args.add "--data-binary"
86+
args.add body
87+
args.add "--"
88+
args.add url
89+
var completed: CompletedProcess
90+
try:
91+
completed = run(args, captureOutput = true)
92+
except CalledProcessError as error:
93+
raise newException(OSError, error.msg)
94+
except TimeoutExpired as error:
95+
raise newException(OSError, error.msg)
96+
if completed.returncode != 0:
97+
raise newException(OSError, completed.stderr)
98+
parseCurlResponse(completed.stdout, status, reason, responseHeaders, transport)
99+
responseUrl = url
29100
else:
30101
{.define: ssl.}
31102
import std/[httpclient, httpcore, net, streams, tables]

0 commit comments

Comments
 (0)