Skip to content

Commit

Permalink
Integrate new HTTP requests (#78)
Browse files Browse the repository at this point in the history
* Add the base of http requests

* Make header files accessible

* Fix http request header fix

* Fix Server typo
  • Loading branch information
sansyrox authored Aug 30, 2021
1 parent 3200f3a commit 14520b3
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 9 deletions.
47 changes: 46 additions & 1 deletion robyn/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def add_header(self, key, value):
def remove_header(self, key):
self.server.remove_header(key)

def start(self, url="127.0.0.0", port="5000"):
def start(self, url="127.0.0.1", port="5000"):
"""
[Starts the server]
Expand Down Expand Up @@ -130,3 +130,48 @@ def inner(handler):

return inner

def head(self, endpoint):
"""
[The @app.head decorator to add a get route]
:param endpoint [str]: [endpoint to server the route]
"""
def inner(handler):
self.add_route("HEAD", endpoint, handler)

return inner

def options(self, endpoint):
"""
[The @app.options decorator to add a get route]
:param endpoint [str]: [endpoint to server the route]
"""
def inner(handler):
self.add_route("OPTIONS", endpoint, handler)

return inner


def connect(self, endpoint):
"""
[The @app.connect decorator to add a get route]
:param endpoint [str]: [endpoint to server the route]
"""
def inner(handler):
self.add_route("CONNECT", endpoint, handler)

return inner

def trace(self, endpoint):
"""
[The @app.trace decorator to add a get route]
:param endpoint [str]: [endpoint to server the route]
"""
def inner(handler):
self.add_route("TRACE", endpoint, handler)

return inner

17 changes: 12 additions & 5 deletions src/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,18 @@ pub async fn handle_request(
payload: &mut web::Payload,
req: &HttpRequest,
) -> HttpResponse {
let contents = match execute_function(function, payload, req).await {
let contents = match execute_function(function, payload, &headers, req).await {
Ok(res) => res,
Err(err) => {
println!("Error: {:?}", err);
let mut response = HttpResponse::InternalServerError();
apply_headers(&mut response, headers);
apply_headers(&mut response, &headers);
return response.finish();
}
};

let mut response = HttpResponse::Ok();
apply_headers(&mut response, headers);
apply_headers(&mut response, &headers);
response.body(contents)
}

Expand All @@ -72,6 +72,7 @@ fn read_file(file_path: &str) -> String {
async fn execute_function(
function: PyFunction,
payload: &mut web::Payload,
headers: &Headers,
req: &HttpRequest,
) -> Result<String> {
let mut data: Option<Vec<u8>> = None;
Expand All @@ -96,6 +97,10 @@ async fn execute_function(

// request object accessible while creating routes
let mut request = HashMap::new();
let mut headers_python = HashMap::new();
for elem in headers.into_iter() {
headers_python.insert(elem.key().clone(), elem.value().clone());
}
match function {
PyFunction::CoRoutine(handler) => {
let output = Python::with_gil(|py| {
Expand All @@ -105,6 +110,7 @@ async fn execute_function(
Some(res) => {
let data = res.into_py(py);
request.insert("body", data);
request.insert("headers", headers_python.into_py(py));
}
None => {}
};
Expand Down Expand Up @@ -163,12 +169,13 @@ async fn execute_function(
Some(res) => {
let data = res.into_py(py);
request.insert("body", data);
request.insert("headers", headers_python.into_py(py));
handler.call1((request,))
}
None => handler.call0(),
None => handler.call1((request,)),
};
let output: &str = output?.extract()?;

let output: &str = output?.extract()?;
Ok(output.to_string())
})
})
Expand Down
14 changes: 13 additions & 1 deletion src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ pub struct Router {
put_routes: DashMap<String, PyFunction>,
delete_routes: DashMap<String, PyFunction>,
patch_routes: DashMap<String, PyFunction>,
head_routes: DashMap<String, PyFunction>,
options_routes: DashMap<String, PyFunction>,
connect_routes: DashMap<String, PyFunction>,
trace_routes: DashMap<String, PyFunction>,
}

impl Router {
Expand All @@ -23,6 +27,10 @@ impl Router {
put_routes: DashMap::new(),
delete_routes: DashMap::new(),
patch_routes: DashMap::new(),
head_routes: DashMap::new(),
options_routes: DashMap::new(),
connect_routes: DashMap::new(),
trace_routes: DashMap::new(),
}
}

Expand All @@ -32,8 +40,12 @@ impl Router {
Method::GET => Some(&self.get_routes),
Method::POST => Some(&self.post_routes),
Method::PUT => Some(&self.put_routes),
Method::DELETE => Some(&self.delete_routes),
Method::PATCH => Some(&self.patch_routes),
Method::DELETE => Some(&self.delete_routes),
Method::HEAD => Some(&self.head_routes),
Method::OPTIONS => Some(&self.options_routes),
Method::CONNECT => Some(&self.connect_routes),
Method::TRACE => Some(&self.trace_routes),
_ => None,
}
}
Expand Down
7 changes: 6 additions & 1 deletion src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,13 @@ impl Server {

HttpServer::new(move || {
let mut app = App::new();
let event_loop_hdl = event_loop_hdl.clone();
let directories = directories.read().unwrap();

// this loop matches three types of directory serving
// 1. Serves a build folder. e.g. the build folder generated from yarn build
// 2. Shows file listing
// 3. Just serves the file without any redirection to sub links
for directory in directories.iter() {
if let Some(index_file) = &directory.index_file {
app = app.service(
Expand All @@ -89,7 +95,6 @@ impl Server {
}
}

let event_loop_hdl = event_loop_hdl.clone();
app.app_data(web::Data::new(router.clone()))
.app_data(web::Data::new(headers.clone()))
.default_service(web::route().to(move |router, headers, payload, req| {
Expand Down
3 changes: 2 additions & 1 deletion test.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ async def test():

@app.post("/jsonify")
async def json(request):
print(request)
return jsonify({"hello": "world"})

@app.post("/post")
Expand Down Expand Up @@ -55,5 +56,5 @@ def blocker():

if __name__ == "__main__":
app.add_header("server", "robyn")
app.add_directory(route="/",directory_path="./test_dir/build", index_file="index.html")
app.add_directory(route="/test_dir",directory_path="./test_dir/build", index_file="index.html")
app.start(port=5000)

0 comments on commit 14520b3

Please sign in to comment.