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 async support in WS #134

Merged
merged 7 commits into from
Dec 20, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
3 changes: 2 additions & 1 deletion integration_tests/base_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@
i = -1

@websocket.on("message")
def connect():
async def connect():
global i
i+=1
if i==0:
print("hello, world")
return "Whaaat??"
elif i==1:
return "Whooo??"
Expand Down
36 changes: 33 additions & 3 deletions src/web_socket_connection.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::types::PyFunction;

use actix::{Actor, StreamHandler};
use actix::prelude::*;
use actix::{Actor, AsyncContext, StreamHandler};
use actix_web::{web, Error, HttpRequest, HttpResponse};
use actix_web_actors::ws;
use actix_web_actors::ws::WebsocketContext;
Expand All @@ -27,6 +28,10 @@ impl Actor for MyWs {
}
}

#[derive(Message)]
#[rtype(result = "Result<(), ()>")]
struct CommandRunner(String);

/// Handler for ws::Message message
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
Expand Down Expand Up @@ -70,9 +75,34 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
let op: &str = op.extract().unwrap();

return ctx.text(op);
// return ctx.text(op);
}),
PyFunction::CoRoutine(_handler) => {
println!("Async functions are not supported in WS right now.");
PyFunction::CoRoutine(handler) => {
println!("{:?}", handler);
let fut = Python::with_gil(|py| {
let handler = handler.as_ref(py);
let coro = handler.call0().unwrap();
pyo3_asyncio::tokio::into_future(coro)
});
sansyrox marked this conversation as resolved.
Show resolved Hide resolved
// let fut = async move {
// println!("Hello world");
// }
// tokio::spawn(async {
// let output = fut.await.unwrap();

// Python::with_gil(|py| {
// println!("Bruhhh moment");
// let contents: &str = output.extract(py).unwrap();
// println!("{:?}", contents);
// });
// });
// let f = async move {};
let f = async move {
fut.unwrap().await.unwrap();
};
let x = actix::fut::wrap_future::<_, Self>(f);
ctx.spawn(x);
// ctx.add_stream("Hello, world");
return ctx.text("Async Functions are not supported in WS right now.");
}
}
Expand Down