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

Add support for sync functions #20

Merged
merged 2 commits into from
Jun 21, 2021
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
4 changes: 2 additions & 2 deletions Cargo.lock

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

6 changes: 5 additions & 1 deletion robyn/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from .robyn import *
from .robyn import Server
from asyncio import iscoroutinefunction

class Robyn:
"""This is the python wrapper for the Robyn binaries.
Expand All @@ -8,6 +8,10 @@ def __init__(self) -> None:
self.server = Server()

def add_route(self, route_type, endpoint, handler):
handler = {
"is_async": iscoroutinefunction(handler),
"handler": handler
}
self.server.add_route(route_type, endpoint, handler)

def start(self):
Expand Down
46 changes: 36 additions & 10 deletions src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,46 @@ use tokio::io::AsyncWriteExt;
use tokio::net::TcpStream;
// pyO3 module
use pyo3::prelude::*;
use pyo3::types::{PyAny, PyDict};

pub async fn handle_message(handler: Py<PyAny>, mut stream: TcpStream) {
let f = Python::with_gil(|py| {
let coro = handler.as_ref(py).call0().unwrap();
pyo3_asyncio::into_future(&coro).unwrap()
enum PyFunction {
CoRoutine(Py<PyAny>),
OutPut(String),
}

pub async fn handle_message(process_object: Py<PyAny>, mut stream: TcpStream) {
let function: PyFunction = Python::with_gil(|py| {
let process_object_wrapper: &PyAny = process_object.as_ref(py);
let py_dict = process_object_wrapper.downcast::<PyDict>().unwrap();
let is_async: bool = py_dict.get_item("is_async").unwrap().extract().unwrap();
let handler: &PyAny = py_dict.get_item("handler").unwrap();
if is_async {
let coro = handler.call0().unwrap();
PyFunction::CoRoutine(coro.into())
} else {
let s: &str = handler.call0().unwrap().extract().unwrap();
PyFunction::OutPut(String::from(s))
}
});

let output = f.await.unwrap();
let contents = match function {
PyFunction::CoRoutine(coro) => {
let x = Python::with_gil(|py| {
let x = coro.as_ref(py);
pyo3_asyncio::into_future(x).unwrap()
});
let output = x.await.unwrap();
Python::with_gil(|py| -> PyResult<String> {
let contents: &str = output.extract(py).unwrap();
Ok(contents.to_string())
})
.unwrap()
}
PyFunction::OutPut(x) => x,
};

// let output = op.await.unwrap();
let status_line = "HTTP/1.1 200 OK";
let contents = Python::with_gil(|py| -> PyResult<String> {
let contents: &str = output.extract(py).unwrap();
Ok(contents.to_string())
})
.unwrap();

let len = contents.len();
let response = format!(
Expand Down
12 changes: 11 additions & 1 deletion src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::sync::Arc;
// pyO3 module
use pyo3::prelude::*;
use pyo3::types::PyAny;
use pyo3::types::PyDict;
use tokio::io::AsyncReadExt;
use tokio::net::{TcpListener, TcpStream};

Expand Down Expand Up @@ -49,7 +50,16 @@ impl Server {
};
}

pub fn add_route(&self, route_type: &str, route: String, handler: Py<PyAny>) {
pub fn add_route(
&self,
route_type: &str,
route: String,
handler: Py<PyAny>,
) {
// Python::with_gil(|py| {
// let py_dict: &PyDict = py_obj.as_ref(py);
// println!("{}", py_dict.get_item("is_coroutine").unwrap());
// });
println!("{} {} ", route_type, route);
let route = Route::new(RouteType::Route((route, route_type.to_string())));
self.router.add_route(route_type, route, handler);
Expand Down
6 changes: 6 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,11 @@ async def sleeper():
await asyncio.sleep(5)
return "sleep function"

@app.get("/blocker")
def blocker():
import time
time.sleep(100)
return "blocker function"

app.start()