Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 13 additions & 31 deletions src/modules/python/picoweb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ def get_mime_type(fname):
def sendstream(writer, f):
buf = bytearray(64)
while True:
l = f.readinto(buf)
if not l:
if l := f.readinto(buf):
yield from writer.awrite(buf, 0, l)
else:
break
yield from writer.awrite(buf, 0, l)
Comment on lines -31 to -34
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function sendstream refactored with the following changes:



def jsonify(writer, dict):
Expand All @@ -47,7 +47,7 @@ def start_response(writer, content_type="text/html", status="200", headers=None)
yield from writer.awrite("\r\n\r\n")
return
yield from writer.awrite("\r\n")
if isinstance(headers, bytes) or isinstance(headers, str):
if isinstance(headers, (bytes, str)):
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function start_response refactored with the following changes:

yield from writer.awrite(headers)
else:
for k, v in headers.items():
Expand Down Expand Up @@ -81,14 +81,8 @@ def parse_qs(self):
class WebApp:

def __init__(self, pkg, routes=None, serve_static=True):
if routes:
self.url_map = routes
else:
self.url_map = []
if pkg and pkg != "__main__":
self.pkg = pkg.split(".", 1)[0]
else:
self.pkg = None
self.url_map = routes or []
self.pkg = pkg.split(".", 1)[0] if pkg and pkg != "__main__" else None
Comment on lines -84 to +85
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function WebApp.__init__ refactored with the following changes:

if serve_static:
self.url_map.append((re.compile("^/(static/.+)"), self.handle_static))
self.mounts = []
Expand Down Expand Up @@ -117,7 +111,7 @@ def _handle(self, reader, writer):
request_line = yield from reader.readline()
if request_line == b"":
if self.debug >= 0:
self.log.error("%s: EOF on request start" % reader)
self.log.error(f"{reader}: EOF on request start")
Comment on lines -120 to +114
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function WebApp._handle refactored with the following changes:

This removes the following comments ( why? ):

# pattern matcher, whose .match() method is called. (Note:
# Django uses .search() instead, but .match() is more
# Anything which is non-string assumed to be a ducktype
# URL matching anyway.)
# efficient and we're not exactly compatible with Django

yield from writer.aclose()
return
req = HTTPRequest()
Expand All @@ -127,9 +121,7 @@ def _handle(self, reader, writer):
if self.debug >= 0:
self.log.info('%.3f %s %s "%s %s"' % (utime.time(), req, writer, method, path))
path = path.split("?", 1)
qs = ""
if len(path) > 1:
qs = path[1]
qs = path[1] if len(path) > 1 else ""
path = path[0]

#print("================")
Expand All @@ -148,7 +140,7 @@ def _handle(self, reader, writer):
found = True
path = path[len(root):]
if not path.startswith("/"):
path = "/" + path
path = f"/{path}"
break
if not found:
break
Expand All @@ -170,22 +162,12 @@ def _handle(self, reader, writer):
found = True
break
elif not isinstance(pattern, str):
# Anything which is non-string assumed to be a ducktype
# pattern matcher, whose .match() method is called. (Note:
# Django uses .search() instead, but .match() is more
# efficient and we're not exactly compatible with Django
# URL matching anyway.)
m = pattern.match(path)
if m:
if m := pattern.match(path):
req.url_match = m
found = True
break

if not found:
headers_mode = "skip"
else:
headers_mode = extra.get("headers", self.headers_mode)

headers_mode = extra.get("headers", self.headers_mode) if found else "skip"
if headers_mode == "skip":
while True:
l = yield from reader.readline()
Expand All @@ -205,7 +187,7 @@ def _handle(self, reader, writer):
else:
yield from start_response(writer, status="404")
yield from writer.awrite("404\r\n")
#print(req, "After response write")
#print(req, "After response write")
except Exception as e:
if self.debug >= 0:
self.log.exc(e, "%.3f %s %s %r" % (utime.time(), req, writer, e))
Expand Down Expand Up @@ -294,7 +276,7 @@ def run(self, host="127.0.0.1", port=8081, debug=False, lazy_init=False, log=Non
app.init()
loop = asyncio.get_event_loop()
if debug > 0:
print("* Running on http://%s:%s/" % (host, port))
print(f"* Running on http://{host}:{port}/")
Comment on lines -297 to +279
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function WebApp.run refactored with the following changes:

loop.create_task(asyncio.start_server(self._handle, host, port))
loop.run_forever()
loop.close()
4 changes: 2 additions & 2 deletions src/modules/python/pkg_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ def resource_stream(package, resource):
if package not in c:
try:
if package:
p = __import__(package + ".R", None, None, True)
p = __import__(f"{package}.R", None, None, True)
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function resource_stream refactored with the following changes:

else:
p = __import__("R")
c[package] = p.R
Expand All @@ -19,7 +19,7 @@ def resource_stream(package, resource):
# if d[0] != "/":
# import uos
# d = uos.getcwd() + "/" + d
c[package] = d + "/"
c[package] = f"{d}/"

p = c[package]
if isinstance(p, dict):
Expand Down
7 changes: 1 addition & 6 deletions src/modules/python/uasyncio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,7 @@ def remove_writer(self, sock):
def wait(self, delay):
if DEBUG and __debug__:
log.debug("poll.wait(%d)", delay)
# We need one-shot behavior (second arg of 1 to .poll())
res = self.poller.ipoll(delay, 1)
#log.debug("poll result: %s", res)
# Remove "if res" workaround after
# https://github.com/micropython/micropython/issues/2716 fixed.
if res:
if res := self.poller.ipoll(delay, 1):
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function PollEventLoop.wait refactored with the following changes:

This removes the following comments ( why? ):

# https://github.com/micropython/micropython/issues/2716 fixed.
#log.debug("poll result: %s", res)
# We need one-shot behavior (second arg of 1 to .poll())
# Remove "if res" workaround after

for sock, ev in res:
cb = self.objmap[id(sock)]
if ev & (select.POLLHUP | select.POLLERR):
Expand Down
8 changes: 2 additions & 6 deletions src/modules/python/uasyncio/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,7 @@ def run_forever(self):
self.cur_task = cb
delay = 0
try:
if args is ():
ret = next(cb)
else:
ret = cb.send(*args)
ret = next(cb) if args is () else cb.send(*args)
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function EventLoop.run_forever refactored with the following changes:

if __debug__ and DEBUG:
log.info("Coroutine %s yield result: %s", cb, ret)
if isinstance(ret, SysCall1):
Expand Down Expand Up @@ -168,8 +165,7 @@ def run_forever(self):
tnow = self.time()
t = self.waitq.peektime()
delay = time.ticks_diff(t, tnow)
if delay < 0:
delay = 0
delay = max(delay, 0)
self.wait(delay)

def run_until_complete(self, coro):
Expand Down
6 changes: 2 additions & 4 deletions src/modules/python/ulogging.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ def __init__(self, name):

def _level_str(self, level):
l = _level_dict.get(level)
if l is not None:
return l
return "LVL%s" % level
return l if l is not None else f"LVL{level}"
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Logger._level_str refactored with the following changes:


def setLevel(self, level):
self.level = level
Expand All @@ -38,7 +36,7 @@ def isEnabledFor(self, level):

def log(self, level, msg, *args):
if level >= (self.level or _level):
_stream.write("%s:%s:" % (self._level_str(level), self.name))
_stream.write(f"{self._level_str(level)}:{self.name}:")
Comment on lines -41 to +39
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Logger.log refactored with the following changes:

if not args:
print(msg, file=_stream)
else:
Expand Down
7 changes: 2 additions & 5 deletions src/modules/python/utemplate/compiled.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
class Loader:

def __init__(self, pkg, dir):
if dir == ".":
dir = ""
else:
dir = dir.replace("/", ".") + "."
dir = "" if dir == "." else dir.replace("/", ".") + "."
if pkg and pkg != "__main__":
dir = pkg + "." + dir
dir = f"{pkg}.{dir}"
Comment on lines -4 to +6
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Loader.__init__ refactored with the following changes:

self.p = dir

def load(self, name):
Expand Down
46 changes: 17 additions & 29 deletions src/modules/python/utemplate/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,12 @@ def close_literal(self):

def render_expr(self, e):
self.indent()
self.file_out.write('yield str(' + e + ')\n')
self.file_out.write(f'yield str({e}' + ')\n')
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Compiler.render_expr refactored with the following changes:


def parse_statement(self, stmt):
tokens = stmt.split(None, 1)
if tokens[0] == "args":
if len(tokens) > 1:
self.args = tokens[1]
else:
self.args = ""
self.args = tokens[1] if len(tokens) > 1 else ""
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Compiler.parse_statement refactored with the following changes:

elif tokens[0] == "set":
self.indent()
self.file_out.write(stmt[3:].strip() + "\n")
Expand All @@ -64,9 +61,7 @@ def parse_statement(self, stmt):
# If there was no other output, we still need a header now
self.indent()
tokens = tokens[1].split(None, 1)
args = ""
if len(tokens) > 1:
args = tokens[1]
args = tokens[1] if len(tokens) > 1 else ""
if tokens[0][0] == "{":
self.indent()
# "1" as fromlist param is uPy hack
Expand All @@ -91,16 +86,15 @@ def parse_statement(self, stmt):
self.indent()
self.file_out.write(stmt + ":\n")
self.stack.append(tokens[0])
elif stmt.startswith("end"):
assert self.stack[-1] == stmt[3:]
self.stack.pop(-1)
elif stmt == "else":
assert self.stack[-1] == "if"
self.indent(-1)
self.file_out.write("else:\n")
else:
if stmt.startswith("end"):
assert self.stack[-1] == stmt[3:]
self.stack.pop(-1)
elif stmt == "else":
assert self.stack[-1] == "if"
self.indent(-1)
self.file_out.write("else:\n")
else:
assert False
assert False

def parse_line(self, l):
while l:
Expand Down Expand Up @@ -158,20 +152,15 @@ def __init__(self, pkg, dir):
self.pkg_path = ""
if pkg:
p = __import__(pkg)
if isinstance(p.__path__, str):
# uPy
self.pkg_path = p.__path__
else:
# CPy
self.pkg_path = p.__path__[0]
self.pkg_path = p.__path__ if isinstance(p.__path__, str) else p.__path__[0]
Comment on lines -161 to +155
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Loader.__init__ refactored with the following changes:

This removes the following comments ( why? ):

# CPy
# uPy

self.pkg_path += "/"

def input_open(self, template):
path = self.pkg_path + self.dir + "/" + template
return open(path)

def compiled_path(self, template):
return self.dir + "/" + template.replace(".", "_") + ".py"
return f"{self.dir}/" + template.replace(".", "_") + ".py"
Comment on lines -174 to +163
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Loader.compiled_path refactored with the following changes:


def load(self, name):
try:
Expand All @@ -182,9 +171,8 @@ def load(self, name):
compiled_path = self.pkg_path + self.compiled_path(name)

f_in = self.input_open(name)
f_out = open(compiled_path, "w")
c = Compiler(f_in, f_out, loader=self)
c.compile()
f_in.close()
f_out.close()
with open(compiled_path, "w") as f_out:
c = Compiler(f_in, f_out, loader=self)
c.compile()
f_in.close()
Comment on lines -185 to +177
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Loader.load refactored with the following changes:

return super().load(name)