Skip to content

Commit

Permalink
tiny changes for readability
Browse files Browse the repository at this point in the history
  • Loading branch information
Deric-W committed Jan 31, 2020
1 parent a0a98b2 commit d723266
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 34 deletions.
5 changes: 3 additions & 2 deletions cache_handlers/files_mtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from os import makedirs
from time import time


class Handler:
def __init__(self, cache_path, file_path, config):
self.cache_prefix = cache_path
Expand All @@ -23,7 +24,7 @@ def get_cachedir_size(self): # get size of cache directory (with all sub
filepath = os.path.join(dirpath, filename)
if not os.path.islink(filepath): # dont count symlinks
size += os.path.getsize(filepath)
return size/(1000**2) # bytes --> Mbytes
return size / (1000 ** 2) # bytes --> Mbytes

def is_available(self): # if cache directory has free space or the cached file is already existing or max_size < 0
return self.max_size < 0 or os.path.isfile(self.cache_path) or self.get_cachedir_size() < self.max_size
Expand All @@ -37,7 +38,7 @@ def is_outdated(self): # return True if cache is not created or needs refre
else:
return True # file is not existing --> age = infinite

def load(self): # load sections
def load(self): # load sections
with open(self.cache_path, "rb") as cache:
code = marshal.load(cache)
return code
Expand Down
2 changes: 1 addition & 1 deletion pyhp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
__author__ = "Eric Wolf"
__maintainer__ = "Eric Wolf"
__license__ = "MIT"
__email__ = "[email protected]" # please dont use for spam :(
__email__ = "[email protected]" # please dont use for spam :(
__contact__ = "https://github.com/Deric-W/PyHP"

# import all submodules
Expand Down
18 changes: 9 additions & 9 deletions pyhp/embed.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
from io import StringIO
from contextlib import redirect_stdout


# class for handling strings
class FromString:
# get string, regex to isolate code and optional flags for the regex (default for processing text files)
# the userdata is given to the processor function to allow state
def __init__(self, string, regex, flags=re.MULTILINE|re.DOTALL, userdata=None):
def __init__(self, string, regex, flags=re.MULTILINE | re.DOTALL, userdata=None):
self.sections = re.split(regex, string, flags=flags)
self.userdata = userdata

Expand Down Expand Up @@ -48,9 +49,8 @@ def __str__(self):
class FromIter(FromString):
# get presplit string as iterator
def __init__(self, iterator, userdata=None):
self.sections = list(iterator)
self.userdata = userdata

self.sections = list(iterator)
self.userdata = userdata

# function for executing python code
# userdata = [locals, section_number], init with [{}, 0]
Expand All @@ -66,7 +66,7 @@ def python_execute(code, userdata):
def python_compile(code, userdata):
userdata[1] += 1
try:
return compile(python_align(code), userdata[0], "exec")
return compile(python_align(code), userdata[0], "exec")
except Exception as e: # tell the user the section of the Exception
raise Exception("Exception during executing of section %d" % userdata[1]) from e

Expand All @@ -85,15 +85,15 @@ def python_align(code, indentation=None):
code = code.splitlines() # split to lines
for line in code:
line_num += 1
if not (not line or line.isspace() or python_is_comment(line)): # ignore non code lines
if indentation == None: # first line of code, get startindentation
if not (not line or line.isspace() or python_is_comment(line)): # ignore non code lines
if indentation is None: # first line of code, get startindentation
indentation = python_get_indentation(line)
if line.startswith(indentation): # if line starts with startindentation
if line.startswith(indentation): # if line starts with startindentation
code[line_num - 1] = line[len(indentation):] # remove startindentation
else:
raise IndentationError("indentation not matching", ("embedded code section", line_num, len(indentation), line)) # raise Exception on bad indentation
return "\n".join(code) # join the lines back together


# function for getting the indentation of a line of python code
def python_get_indentation(line):
Expand Down
25 changes: 13 additions & 12 deletions pyhp/libpyhp.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,16 @@
from http import HTTPStatus
from collections import defaultdict


# class containing the implementations
class PyHP:
def __init__(self, # build GET, POST, COOKIE, SERVER, REQUEST
file_path = sys.argv[0], # override if not directly executed
request_order = ("GET", "POST", "COOKIE"), # order in wich REQUEST gets updated
keep_blank_values = True, # if to not remove "" values
fallback_value = None, # fallback value of GET, POST, REQUEST and COOKIE if not None
enable_post_data_reading = False, # if not to parse POST and consume stdin in the process
default_mimetype = "text/html" # Content-Type header if not been set
file_path=sys.argv[0], # override if not directly executed
request_order=("GET", "POST", "COOKIE"), # order in wich REQUEST gets updated
keep_blank_values=True, # if to not remove "" values
fallback_value=None, # fallback value of GET, POST, REQUEST and COOKIE if not None
enable_post_data_reading=False, # if not to parse POST and consume stdin in the process
default_mimetype="text/html" # Content-Type header if not been set
):
self.__FILE__ = os.path.abspath(file_path) # absolute path of script
self.response_code = 200
Expand Down Expand Up @@ -81,7 +82,7 @@ def __init__(self, # build GET, POST, COOKIE, SERVER, REQUEST
self.POST = dict2defaultdict({}, fallback_value)
else: # parse POST and consume stdin
self.POST = dict2defaultdict(parse_post(keep_blank_values), fallback_value)

# build REQUEST
self.REQUEST = dict2defaultdict({}, fallback_value) # empthy REQUEST
for request in request_order: # update REQUEST in the order given by request_order
Expand Down Expand Up @@ -113,12 +114,12 @@ def header(self, header, replace=True, http_response_code=None):
self.headers.append(header) # add header
if http_response_code is not None: # set response code if given (higher priority than location headers)
self.response_code = http_response_code
elif header[0].lower() == "location" and not check_redirect(self.response_code): # set matching response code if code is not 201 or 3xx
elif header[0].lower() == "location" and not check_redirect(self.response_code): # set matching response code if code is not 201 or 3xx
self.response_code = 302
else:
pass

# list set headers
# list set headers
def headers_list(self):
return [": ".join(header) for header in self.headers] # list headers like received by the client

Expand All @@ -127,7 +128,7 @@ def headers_list(self):
def header_remove(self, name=None):
if name is not None:
name = name.lower() # header names are case-insensitive
self.headers = [header for header in self.headers if header[0].lower() != name] # remove headers with same name
self.headers = [header for header in self.headers if header[0].lower() != name] # remove headers with same name
else:
self.headers = [] # remove all headers

Expand All @@ -150,7 +151,7 @@ def header_register_callback(self, callback):
def send_headers(self):
self.header_sent = True # prevent recursion if callback prints output
self.header_callback() # execute callback
print("Status:" , self.response_code, HTTPStatus(self.response_code).phrase)
print("Status:", self.response_code, HTTPStatus(self.response_code).phrase)
for header in self.headers:
print(": ".join(header))
print() # end of headers
Expand Down Expand Up @@ -189,7 +190,7 @@ def setrawcookie(self, name, value="", expires=0, path=None, domain=None, secure
cookie = "Set-Cookie: %s=%s" % (name, value) # initial header
if expires != 0:
cookie += "; " + "Expires=%s" % time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(time.time() + expires)) # add Expires and Max-Age just in case
cookie += "; " + "Max-Age=%d" % expires
cookie += "; " + "Max-Age=%d" % expires
if path is not None:
cookie += "; " + "Path=%s" % path
if domain is not None:
Expand Down
19 changes: 10 additions & 9 deletions pyhp/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from . import embed
from . import libpyhp


# get cli arguments for main as dict
def get_args():
parser = argparse.ArgumentParser(prog="pyhp", description="Interpreter for .pyhp Scripts (https://github.com/Deric-W/PyHP)")
Expand All @@ -38,7 +39,7 @@ def main(file_path, caching=False, config_file="/etc/pyhp.conf"):
enable_post_data_reading=config.getboolean("request", "enable_post_data_reading", fallback=False),
default_mimetype=config.get("request", "default_mimetype", fallback="text/html")
)
sys.stdout.write = PyHP.make_header_wrapper(sys.stdout.write) # wrap stdout
sys.stdout.write = PyHP.make_header_wrapper(sys.stdout.write) # wrap stdout
atexit.register(PyHP.run_shutdown_functions) # run shutdown functions even if a exception occured

# handle caching
Expand All @@ -47,33 +48,33 @@ def main(file_path, caching=False, config_file="/etc/pyhp.conf"):
caching_allowed = config.getboolean("caching", "auto", fallback=False)
# if file is not stdin and caching is enabled and wanted or auto_caching is enabled
if check_if_caching(file_path, caching, caching_enabled, caching_allowed):
handler_path = prepare_path(config.get("caching", "handler_path", fallback="/lib/pyhp/cache_handlers/files_mtime.py")) # get neccesary data
handler_path = prepare_path(config.get("caching", "handler_path", fallback="/lib/pyhp/cache_handlers/files_mtime.py")) # get neccesary data
cache_path = prepare_path(config.get("caching", "path", fallback="~/.pyhp/cache"))
handler = import_path(handler_path)
handler = handler.Handler(cache_path, os.path.abspath(file_path), config["caching"]) # init handler
if handler.is_available(): # check if caching is possible
cached = True
if handler.is_outdated(): # update cache
code = embed.FromString(prepare_file(file_path), regex, userdata=[file_path, 0]) # set userdata for python_compile
code = embed.FromString(prepare_file(file_path), regex, userdata=[file_path, 0]) # set userdata for python_compile
code.process(embed.python_compile) # compile python sections
code.userdata = [{"PyHP": PyHP}, 0] # set userdata for python_execute_compiled
code.userdata = [{"PyHP": PyHP}, 0] # set userdata for python_execute_compiled
handler.save(code.sections) # just save the code sections
else: # load cache
code = embed.FromIter(handler.load(), userdata=[{"PyHP": PyHP}, 0])
else: # generate FromString Object
cached = False
code = embed.FromString(prepare_file(file_path), regex, userdata=[{"PyHP": PyHP}, 0])
handler.close()
code = embed.FromString(prepare_file(file_path), regex, userdata=[{"PyHP": PyHP}, 0])
handler.close()
else: # same as above
cached = False
code = embed.FromString(prepare_file(file_path), regex, userdata=[{"PyHP": PyHP}, 0])
code = embed.FromString(prepare_file(file_path), regex, userdata=[{"PyHP": PyHP}, 0])

if cached: # run compiled code
code.execute(embed.python_execute_compiled)
else: # run normal code
code.execute(embed.python_execute)

if not PyHP.headers_sent(): # prevent error if no output occured, but not if an exception occured
if not PyHP.headers_sent(): # prevent error if no output occured, but not if an exception occured
PyHP.send_headers()
return 0 # return 0 on success

Expand All @@ -92,7 +93,7 @@ def import_path(path):
# check we should cache
def check_if_caching(file_path, caching, enabled, auto):
possible = file_path != "" # file is not stdin
allowed = (caching or auto) and enabled # if caching is wanted and enabled
allowed = (caching or auto) and enabled # if caching is wanted and enabled
return possible and allowed

# get code and remove shebang
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@
"License :: OSI Approved :: MIT License",
],
python_requires='>=3.5',
)
)

0 comments on commit d723266

Please sign in to comment.