Skip to content

Commit

Permalink
fixed minor bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
theonlyamos committed Sep 10, 2023
1 parent 7cedc97 commit 5991c26
Show file tree
Hide file tree
Showing 5 changed files with 75 additions and 85 deletions.
66 changes: 32 additions & 34 deletions runit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import shelve
import getpass
import argparse
import asyncio
from typing import Type, Optional
from threading import Thread

Expand All @@ -16,11 +17,11 @@
from .runit import RunIt

from .constants import VERSION, CURRENT_PROJECT, CURRENT_PROJECT_DIR, EXT_TO_RUNTIME, \
LANGUAGE_TO_RUNTIME, RUNIT_HOMEDIR
LANGUAGE_TO_RUNTIME, RUNIT_HOMEDIR, SERVER_HOST, SERVER_PORT

load_dotenv()

def StartWebserver(project: Type[RunIt], host: str = '127.0.0.1', port: int = 5000):
def StartWebserver(project: RunIt, host: str = SERVER_HOST, port: int = SERVER_PORT):
app = FastAPI()
app.secret_key = "fdakfjlfdsaflfkjbasdoiefanckdareafasdfkowadbfakidfadfkj"

Expand All @@ -30,39 +31,36 @@ def StartWebserver(project: Type[RunIt], host: str = '127.0.0.1', port: int = 50
@app.api_route('/{func}/{output_format}', methods=["GET", "POST"])
@app.api_route('/{func}/{output_format}/', methods=["GET", "POST"])
async def serve(func: str = 'index', output_format: str = 'json', request: Request = None):
response = {'status': True, 'data': {}}
result = ''
try:
response = {'status': True, 'data': {}}
result = ''

if request.method.lower() in ['get', 'post']:
parameters = request.query_params._dict
if 'content-type' in request.headers.keys() and request.headers['content-type'] == "application/json":
data = await request.json()
parameters = {**parameters, **data}

if 'output_format' in parameters.keys():
del parameters['output_format']

params = list(parameters.values()) if request else request
result = project.serve(func, params) \
if len(params) else project.serve(func)

if output_format == 'html':
return HTMLResponse(result)
else:
response['data'] = json.loads(result.replace("'", '"'))
return response

response['status': False]
response['message'] = 'Method Not Allowed'
return 'MethodNodAllowed' if output_format == 'html' \
else response
parameters = request.query_params._dict
if 'content-type' in request.headers.keys() and request.headers['content-type'] == "application/json":
data = await request.json()
parameters = {**parameters, **data}

if 'output_format' in parameters.keys():
del parameters['output_format']

params = list(parameters.values()) if request else request
result = project.serve(func, params) \
if len(params) else project.serve(func)

if result.startswith('404'):
raise RuntimeError('Not Found')
if output_format == 'html':
return HTMLResponse(result)
else:
response['data'] = json.loads(result.replace("'", '"'))
return response

except json.decoder.JSONDecodeError:
return result
except:
response['status': False]
response['message'] = 'Not Found'
return HTMLResponse(RunIt.notfound()) if \
response['data'] = result
return response
except Exception:
response['status'] = False
response['message'] = RunIt.notfound(output_format)
return HTMLResponse(RunIt.notfound(output_format)) if \
output_format == 'html' else response

try:
Expand Down Expand Up @@ -134,7 +132,7 @@ def run_project(args):
project = RunIt(**RunIt.load_config())

if args.shell:
print(project.serve(args.function, args.arguments, args.file))
print(project.serve(args.function, args.arguments))
else:
StartWebserver(project, args.host, args.port)

Expand Down
6 changes: 5 additions & 1 deletion runit/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

load_dotenv()

VERSION = "0.2.3"
VERSION = "0.2.4"
CURRENT_PROJECT = ""
NOT_FOUND_FILE = '404.html'
DOT_RUNIT_IGNORE = '.runitignore'
Expand All @@ -15,6 +15,8 @@
TOOLS_DIR = os.path.join(RUNIT_HOMEDIR, 'tools')
PROJECTS_DIR = os.path.join(RUNIT_HOMEDIR, 'projects')
TEMPLATES_FOLDER = os.path.join(RUNIT_HOMEDIR, 'templates')
SERVER_HOST = '0.0.0.0'
SERVER_PORT = 9000

EXT_TO_LOADER = {
'.py': os.path.join(TOOLS_DIR, 'python', 'loader.py'),
Expand Down Expand Up @@ -47,3 +49,5 @@
BASE_HEADERS = {
'Content-Type': 'application/json'
}

INSTALL_MODULE_LATER_MESSAGE = '[~] Try again manually later.'
63 changes: 35 additions & 28 deletions runit/runit.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@
from .languages import LanguageParser
from .constants import TEMPLATES_FOLDER, STARTER_FILES, NOT_FOUND_FILE, \
CONFIG_FILE, STARTER_CONFIG_FILE, IS_RUNNING, PROJECTS_DIR, \
CURRENT_PROJECT_DIR, DOT_RUNIT_IGNORE
CURRENT_PROJECT_DIR, DOT_RUNIT_IGNORE, INSTALL_MODULE_LATER_MESSAGE

load_dotenv()
class RunIt:
DOCKER = False
KUBERNETES = False

def __init__(self, name, _id="", version="0.0.1", description="", homepage="",
language="", runtime="", start_file="", private=False, author={}, is_file: bool = False):
language="", runtime="", start_file="", private=False, author=None, is_file: bool = False):
global STARTER_FILES

self._id = _id
Expand Down Expand Up @@ -102,16 +102,19 @@ def set_project_name(name: str =None)-> str:
sys.exit(1)

@staticmethod
def notfound():
def notfound(format='json'):
global TEMPLATES_FOLDER
global NOT_FOUND_FILE

if format == 'json':
return '404 - Not Found'

with open(os.path.join(os.curdir, TEMPLATES_FOLDER, NOT_FOUND_FILE),'rt') as file:
return file.read()

@staticmethod
def extract_project(filepath):
directory, filename = os.path.split(filepath)
directory = os.path.split(filepath)[0]

with ZipFile(filepath, 'r') as file:
file.extractall(directory)
Expand Down Expand Up @@ -200,15 +203,14 @@ def start(cls, project_id: str, func='index', projects_folder: str = PROJECTS_DI
try:
return getattr(lang_parser, func)(*args_list)
except AttributeError as e:
# return f"Function with name '{func}' not defined!"
return RunIt.notfound()
except TypeError as e:
try:
return getattr(lang_parser, func)()
except TypeError as e:
return str(e)

def serve(self, func: str = 'index', args: Optional[Union[dict,list]]=None, filename: str = ''):
def serve(self, func: str = 'index', args: Optional[Union[dict,list]]=None):
global NOT_FOUND_FILE

lang_parser = LanguageParser.detect_language(self.start_file, self.runtime)
Expand All @@ -223,7 +225,6 @@ def serve(self, func: str = 'index', args: Optional[Union[dict,list]]=None, file
return getattr(lang_parser, func)(*args_list)
except AttributeError as e:
return RunIt.notfound()
# return f"Function with name '{func}' not defined!"
except TypeError as e:
try:
return getattr(lang_parser, func)()
Expand Down Expand Up @@ -286,13 +287,12 @@ def compress(self):

with ZipFile(zipname, 'w') as zipobj:
print('[!] Compressing Project Files...')
for folderName, subfolders, filenames in os.walk(os.curdir):

for folder_name, subfolders, filenames in os.walk(os.curdir):
for filename in filenames:
if not os.path.normpath(os.path.dirname(folderName)).split(os.path.sep)[0] in exclude_list:
filepath = os.path.join(folderName, filename)
if os.path.normpath(os.path.dirname(folder_name)).split(os.path.sep)[0] not in exclude_list:
filepath = os.path.join(folder_name, filename)

if not os.path.basename(filepath) in exclude_list and not '__pycache__' in folderName:
if os.path.basename(filepath) not in exclude_list and '__pycache__' not in folder_name:
zipobj.write(filepath, filepath)
print(f'[{filepath}] Compressed!')
print(f'[!] Filename: {zipname}')
Expand All @@ -303,7 +303,7 @@ def create_config(self):
self.config['name'] = self.name
self.config['version'] = self.version
self.config['description'] = self.description
self.config['homepage'] = 'https://example.com/project_id/'
self.config['homepage'] = 'http://example.com/project_id/'
self.config['language'] = self.language
self.config['runtime'] = self.runtime
self.config['private'] = self.private
Expand All @@ -319,21 +319,26 @@ def create_starter_files(self):
self.LANGUAGE_TEMPLATE_FILES = os.listdir(self.LANGUAGE_TEMPLATE_FOLDER)

for template_file in self.LANGUAGE_TEMPLATE_FILES:
with open(os.path.join(self.LANGUAGE_TEMPLATE_FOLDER,
template_file),'rt') as file:
with open(os.path.join(os.curdir, self.name, template_file), 'wt') as starter:
starter.write(file.read())
if os.path.isfile(os.path.join(self.LANGUAGE_TEMPLATE_FOLDER,template_file)):
with open(os.path.join(self.LANGUAGE_TEMPLATE_FOLDER,
template_file),'rt') as file:
with open(os.path.join(os.curdir,
self.name,
template_file), 'wt') as starter:
starter.write(file.read())

with open(os.path.join(TEMPLATES_FOLDER, NOT_FOUND_FILE),'rt') as file:
with open(os.path.join(os.curdir, self.name, NOT_FOUND_FILE), 'wt') as error:
error.write(file.read())
with open(os.path.join(os.curdir, self.name, NOT_FOUND_FILE), 'wt') as error_404:
error_404.write(file.read())

with open(os.path.join(TEMPLATES_FOLDER, DOT_RUNIT_IGNORE),'rt') as file:
with open(os.path.join(os.curdir, self.name, DOT_RUNIT_IGNORE), 'wt') as dotrunitignore:
dotrunitignore.write(file.read())

def install_dependency_packages(self):
# os.chdir(os.path.join(os.curdir, self.name))
project_path = os.path.realpath(os.path.join(os.curdir, self.name))
if project_path != os.path.realpath(os.curdir):
os.chdir(project_path)
packaging_functions = {}
packaging_functions['javascript'] = self.update_and_install_package_json
packaging_functions['php'] = self.update_and_install_composer_json
Expand All @@ -347,9 +352,9 @@ def install_all_language_packages(self):
self.update_and_install_package_json()
self.update_and_install_composer_json()
self.install_python_packages()
except:
except Exception:
print("[!] Couldn't install packages")
print("[~] Try again manually later.")
print(INSTALL_MODULE_LATER_MESSAGE)

def update_and_install_package_json(self):
print("[-] Creating and updating package.json")
Expand All @@ -369,7 +374,7 @@ def update_and_install_package_json(self):
except Exception as e:
print(str(e))
print("[!] Couldn't install modules")
print("[~] Try again manually later.")
print(INSTALL_MODULE_LATER_MESSAGE)


def update_and_install_composer_json(self):
Expand All @@ -390,23 +395,25 @@ def update_and_install_composer_json(self):
# except Exception as e:
# print(str(e))
# print("[!] Couldn't install packages")
# print("[~] Try again manually later.")
# print(INSTALL_MODULE_LATER_MESSAGE)

def install_python_packages(self):
print("[-] Creating virtual environment")
os.system(f"python -m venv venv")
print("[-] Creating virtual environment...", end='\r')
os.system("python -m venv venv")
print("[+] Creating virtual environment - done", end='\n')
pip_path = os.path.join(os.curdir, 'venv', 'Scripts', 'pip.exe')
if sys.platform != 'win32':
pip_path = f".\{os.path.join(os.curdir, 'venv', 'bin', 'pip')}"
try:
print("[-] Installing python packages")
print("[-] Installing python packages...", end="\r")
activate_install_instructions = f"""
{pip_path} install -r requirements.txt
""".strip()
os.system(activate_install_instructions)
print("[+] Installing python packages - done", end="\n")
except Exception as e:
print(str(e))
print("[!] Couldn't install packages")
print("[~] Try again manually later.")
print(INSTALL_MODULE_LATER_MESSAGE)


20 changes: 0 additions & 20 deletions runit/templates/python/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,20 +0,0 @@
aniso8601==9.0.1
certifi==2022.12.7
charset-normalizer==2.1.1
click==8.1.3
colorama==0.4.6
Flask==2.3.2
Flask-JWT-Extended==4.4.4
Flask-RESTful==0.3.9
idna==3.4
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.1
PyJWT==2.6.0
python-dotenv==0.21.0
python-runit==0.0.6
pytz==2022.6
requests==2.31.0
six==1.16.0
urllib3==1.26.12
Werkzeug==2.2.3
5 changes: 3 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from importlib.metadata import entry_points
from setuptools import setup, find_packages

VERSION = '0.2.3'
VERSION = '0.2.4'

with open('README.md', 'rt') as file:
LONG_DESCRIPTION = file.read()
Expand All @@ -16,7 +16,8 @@
long_description_content_type = "text/markdown",
packages=find_packages(),
include_package_data=True,
install_requires=['requests','python-dotenv','fastapi','passlib', 'docker'],
install_requires=['requests','python-dotenv','fastapi', \
'passlib', 'docker', 'uvicorn'],
keywords='python3 runit developer serverless architecture docker',
project_urls={
'Source': 'https://github.com/theonlyamos/runit/',
Expand Down

0 comments on commit 5991c26

Please sign in to comment.