cours-snt/test-python-ssh/python_app/main.py
2021-02-05 17:11:47 +01:00

74 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Dynamic import
import importlib
# Get function args
import inspect
# The directory where student work will be
# not a real path, do not use ./ or stuff like this
BASE_MODULE_PATH = 'modules'
if BASE_MODULE_PATH != '':
BASE_MODULE_PATH += '/'
def application(env, start_response):
# Some hard-coded paths
if env['PATH_INFO'] == '/favicon.ico':
return file_content('favicon.ico')
if env['PATH_INFO'] == '/':
return index()
# Find which python module and function will be called
elements = env['PATH_INFO'].split('/')[1:] # Removing the first empty element
path = ''
module = 'main'
function = 'index'
if len(elements) == 1:
module = elements[0]
elif len(elements) == 2:
module = elements[0]
function = elements[1]
elif len(elements) > 2:
path = '/'.join(elements[0:-2])
module = elements[-2]
function = elements[-1]
if path != '':
path += '/'
module_path = BASE_MODULE_PATH + path + module
module_path = module_path.replace('/', '.')
# Import the function
try:
m = importlib.import_module(module_path)
except ModuleNotFoundError:
print('Le fichier {} na pas été trouvé.'.format(module_path))
return htmlresp(404, 'Le fichier {} na pas été trouvé'.format(path + module), start_response)
# Find which parameters the function needs
params = {}
try:
f = getattr(m,function)
# TODO get http parameters and give them to the function
#print(inspect.signature(f))
except AttributeError:
return htmlresp(404, 'La fonction {} na pas été trouvée'.format(function), start_response)
# Call the function with the rigth attributes
return [bytes(str(f(*params)), 'utf8')]
def index ():
return file_content('passwords.txt')
def htmlresp(code, message, start_response):
html = '<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body>{}</body></html>'
return resp(code, [('Content-Type','text/html')], html.format(message), start_response)
def resp(code, headers, message, start_response):
start_response(str(code), headers)
return bytes(message, 'utf8')
def file_content (filename):
with open(filename, mode='rb') as file:
return file.read()