Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hotfix detecting robyn.env #292

Merged
merged 8 commits into from
Oct 19, 2022
Merged
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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "robyn"
version = "0.17.5"
version = "0.18.0"
authors = ["Sanskar Jethi <sansyrox@gmail.com>"]
edition = "2018"
description = "A web server that is fast!"
Expand Down
23 changes: 23 additions & 0 deletions docs/env-variables.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
## Environment Variables

There some environment variables that Robyn looks out for. e.g. `ROBYN_URL` and `ROBYN_PORT`.

You can have a `robyn.env` file to load them automatically in your environment.

The server will check for the `robyn.env` file in the root of the project. If it is able to find one, it will parse the environment variables and the set your environment.

e.g. structure

```
--project/
--robyn.env
--index.py
...
```

Sample `robyn.env`

```
ROBYN_PORT=5000
ROBYN_URL=127.0.0.1
```
12 changes: 12 additions & 0 deletions integration_tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,15 @@ def dev_session():
yield
kill_process(process)

@pytest.fixture(scope="session")
def test_session():
os.environ["ROBYN_URL"] = "127.0.0.1"
os.environ["ROBYN_PORT"] = "8080"
current_file_path = pathlib.Path(__file__).parent.resolve()
base_routes = os.path.join(current_file_path, "./base_routes.py")
command = ["python3", base_routes, "--dev"]
process = spawn_process(command)
time.sleep(5)
yield
kill_process(process)

19 changes: 9 additions & 10 deletions integration_tests/test_env_populator.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,18 @@
@pytest.fixture
def env_file():
CONTENT = """ROBYN_PORT=8080
ROBYN_URL=127.0.1.1"""
dir = path / "test_dir"
env_file = dir / "robyn.env"
env_file.write_text(CONTENT)
ROBYN_URL=127.0.0.1"""
env_path = path / "robyn.env"
env_path.write_text(CONTENT)
yield
env_file.unlink()
os.unsetenv("PORT")
env_path.unlink()
os.unsetenv("ROBYN_PORT")
os.unsetenv("ROBYN_URL")

# this tests if a connection can be made to the server with the correct port imported from the env file
def test_env_population(dev_session, env_file):
dir = path / "test_dir"
env_file = dir / "robyn.env"
load_vars(variables = parser(config_path = env_file))
def test_env_population(test_session, env_file):
env_path = path / "robyn.env"
load_vars(variables=parser(config_path=env_path))
PORT = os.environ['ROBYN_PORT']
HOST = os.environ['ROBYN_URL']
BASE_URL = f"http://{HOST}:{PORT}"
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name = "robyn"
version = "0.17.5"
version = "0.18.0"
description = "A web server that is fast!"
authors = ["Sanskar Jethi <sansyrox@gmail.com>"]

Expand Down
6 changes: 5 additions & 1 deletion robyn/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def __init__(self, file_object: str) -> None:
self.headers = []
self.directories = []
self.event_handlers = {}
load_vars()
load_vars(project_root=directory_path)
self._config_logger()

def _add_route(self, route_type, endpoint, handler, const=False):
Expand Down Expand Up @@ -105,6 +105,10 @@ def start(self, url: str = "127.0.0.1", port: int = 5000):

:param port int: reperesents the port number at which the server is listening
"""

url = os.getenv("ROBYN_URL", "127.0.0.1")
port= int(os.getenv("ROBYN_PORT", "5000"))

def init_processpool(socket):

process_pool = []
Expand Down
10 changes: 7 additions & 3 deletions robyn/dev_event_handler.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import subprocess
import sys

from watchdog.events import FileSystemEventHandler

Expand All @@ -7,11 +8,14 @@ class EventHandler(FileSystemEventHandler):
def __init__(self, file_name) -> None:
self.file_name = file_name
self.processes = []
self.python_alias = "python3" if not sys.platform.startswith("win32") else "python"
self.shell = True if sys.platform.startswith("win32") else False


def start_server_first_time(self) -> None:
if self.processes:
raise Exception("Something wrong with the server")
self.processes.append(subprocess.Popen(["python3", self.file_name], start_new_session=False))
self.processes.append(subprocess.Popen([self.python_alias, self.file_name], shell = self.shell, start_new_session=False))

def on_any_event(self, event) -> None:
"""
Expand All @@ -22,5 +26,5 @@ def on_any_event(self, event) -> None:

if len(self.processes) > 0:
for process in self.processes:
process.terminate()
self.processes.append(subprocess.Popen(["python3", self.file_name], start_new_session=False))
process.terminate()
self.processes.append(subprocess.Popen([self.python_alias, self.file_name], shell = self.shell, start_new_session=False))
20 changes: 9 additions & 11 deletions robyn/env_populator.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
from distutils.command.config import config
import os
import logging
from pathlib import Path



# Path to the root of the project
ROOT_DIR = Path(__file__).parent.parent

# Path to the environment variables
CONFIG_PATH = ROOT_DIR / 'robyn.env'

#set the logger that will log the environment variables imported from robyn.env and the ones already set
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


# parse the configuration file returning a list of tuples (key, value) containing the environment variables
def parser(config_path=CONFIG_PATH):
"""Parse the configuration file"""
def parser(config_path=None, project_root = None):
"""Find robyn.env file in root of the project and parse it """
if config_path is None:
config_path = Path(project_root) / "robyn.env"

if config_path.exists():
with open(config_path, 'r') as f:
for line in f:
Expand All @@ -26,11 +24,11 @@ def parser(config_path=CONFIG_PATH):


# check for the environment variables set in cli and if not set them
def load_vars(variables = None):
def load_vars(variables = None, project_root = None):
"""Main function"""

if variables is None:
variables = parser()
variables = parser(project_root=project_root)

for var in variables:
if var[0] in os.environ:
Expand Down
7 changes: 2 additions & 5 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,9 +454,8 @@ async fn index(
}
};

match middleware_router.get_route("AFTER_REQUEST", req.uri().path()) {
Some(((handler_function, number_of_params), route_params)) => {
let x = handle_http_middleware_request(
if let Some(((handler_function, number_of_params), route_params)) = middleware_router.get_route("AFTER_REQUEST", req.uri().path()) {
let x = handle_http_middleware_request(
handler_function,
number_of_params,
&headers_dup,
Expand All @@ -467,8 +466,6 @@ async fn index(
)
.await;
debug!("{:?}", x);
}
None => {}
};

response
Expand Down