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

feat: add rust imports #717

Merged
merged 10 commits into from
Dec 28, 2023
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ python --version
- WebSockets!
- Middlewares
- Hot Reloading
- Direct Rust Integration
- Community First and truly FOSS!

## 🗒️ How to contribute
Expand Down
11 changes: 11 additions & 0 deletions docs_src/src/components/documentation/ApiDocs.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,17 @@ const guides = [
name: 'Advanced Features',
description: 'Learn about advanced features in Robyn.',
},

{
href: '/documentation/api_reference/using_rust_directly',
name: 'Direct Rust Usage',
description: 'Learn about directly using Rust in Robyn.',
},
{
href: '/documentation/api_reference/graphql-support',
name: 'Advanced Features',
description: 'Learn about GraphQL Support in Robyn.',
},
{
href: '/documentation/api_reference/dependency_injection',
name: 'Dependency Injection',
Expand Down
6 changes: 5 additions & 1 deletion docs_src/src/components/documentation/Navigation.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -278,9 +278,13 @@ export const navigation = [
title: 'Exceptions',
},
{
href: '/documentation/api_reference/advanced_features#keep-a-track-of-clients-ip-address',
href: '/documentation/api_reference/advanced_features',
title: 'Advanced Features',
},
{
href: '/documentation/api_reference/using_rust_directly',
title: 'Using Rust Directly',
},
{
href: '/documentation/api_reference/graphql-support',
title: 'GraphQL Support',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ Batman scaled his application across multiple cores for better performance. He u
## What's next?


Batman was curious to know what else he could do with Robyn.
Batman wondered if it was possible to use Rust directly from Robyn's codebase.

Robyn told him to keep an eye on the GraphQl support.
Robyn showed him the path.

[GraphQl Support](/documentation/api_reference/graphql_support)
[Using Rust Directly](/documentation/api_reference/using_rust_directly)



Expand Down
144 changes: 144 additions & 0 deletions docs_src/src/pages/documentation/api_reference/using_rust_directly.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@

## Using Rust to extend Robyn


There may be occassions where Batman may be working with a high computation task, or a task that requires a lot of memory. In such cases, he may want to use Rust to implement that task. Robyn introduces a special way to do this. Not only you can use Rust to extend Python code, you can do it while maintaining the hot reloading nature of your codebase. Making it *feel* like an interpreted version in many situations.
sansyrox marked this conversation as resolved.
Show resolved Hide resolved



<Row>
<Col>
The first thing you need to is to create a Rust file. Let's call it `hello_world.rs`. You can do it using the cli:
</Col>
<Col sticky>

<CodeGroup title="Request" tag="GET" label="/hello_world">

```python {{ title: 'untyped' }}
python -m robyn --create-rust-file hello_world
```

```python {{title: 'typed'}}
python -m robyn --create-rust-file hello_world
```

</CodeGroup>
</Col>
</Row>
<Row>

<Col>
Then you can open the file and write your Rust code. For example, let's write a function that returns a string.


</Col>
<Col sticky>
<CodeGroup title="Request" tag="GET" label="/hello_world">

```rust
// hello_world.rs

// rustimport:pyo3

use pyo3::prelude::*;

#[pyfunction]
fn square(n: i32) -> i32 {
n * n * n
// this is another comment
}

```

</CodeGroup>
</Col>
</Row>

<Row>

<Col>
Every Rust file that you create using the cli will have a special comment at the top of the file. This comment is used by Robyn to know which dependencies to import. In this case, we are importing the `pyo3` crate. You can import as many crates as you want. You can also import crates from crates.io. For example, if you want to use the `rusqlite` crate, you can do it like this:



</Col>
<Col sticky>
<CodeGroup title="Request" tag="GET" label="/hello_world">

```rust
// rustimport:pyo3

//:
//: [dependencies]
//: rusqlite = "0.19.0"

use pyo3::prelude::*;

#[pyfunction]
fn square(n: i32) -> i32 {
n * n * n
// this is another comment
}

```

</CodeGroup>
</Col>
</Row>


<Row>
Then you can import the function in your Python code and use it.

<Col sticky>
<CodeGroup title="Request" tag="GET" label="/hello_world">

```python {{ title: 'untyped' }}
from hello_world import square

print(square(5))
```

```python {{title: 'typed'}}
from hello_world import square

print(square(5))
```
</CodeGroup>
</Col>

To run the code, you need to use the `--compile-rust-path` flag. This will compile the Rust code and run it. You can also use the `--dev` flag to watch for changes in the Rust code and recompile it on the fly.

<Col sticky>
<CodeGroup title="Request" tag="GET" label="/hello_world">

```python {{ title: 'untyped' }}
python -m robyn --compile-rust-path "." --dev
```

```python {{title: 'typed'}}
python -m robyn --compile-rust-path "." --dev
```
</CodeGroup>

</Col>
</Row>

An example of a Robyn app with a Rust file that using the `rusqlite` crate to connect to a database and return the number of rows in a table: https://github.com/sansyrox/rusty-sql


## What's next?


Batman was curious to know what else he could do with Robyn.

Robyn told him to keep an eye on the GraphQl support.

[GraphQl Support](/documentation/api_reference/graphql_support)







27 changes: 26 additions & 1 deletion poetry.lock

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

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ multiprocess = "0.70.14"
nestd = "0.3.1"
uvloop = { version = "0.19.0", markers = "sys_platform != 'win32' and (sys_platform != 'cygwin' and platform_python_implementation != 'PyPy')" }
jinja2 = { version = "3.0.1", optional = true }
rustimport = "^1.3.4"

[tool.poetry.extras]
templating = ["jinja2"]
Expand Down
8 changes: 7 additions & 1 deletion robyn/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from robyn.authentication import AuthenticationHandler
from robyn.dependency_injection import DependencyMap
from robyn.logger import Colors
from robyn.reloader import compile_rust_files
from robyn.env_populator import load_vars
from robyn.events import Events
from robyn.logger import logger
Expand All @@ -24,6 +25,12 @@

__version__ = get_version()

config = Config()

if (compile_path := config.compile_rust_path) is not None:
compile_rust_files(compile_path)
print("Compiled rust files")


class Robyn:
"""This is the python wrapper for the Robyn binaries."""
Expand All @@ -48,7 +55,6 @@ def __init__(
"SERVER IS RUNNING IN VERBOSE/DEBUG MODE. Set --log-level to WARN to run in production mode.",
color=Colors.BLUE,
)

if self.config.dev:
exit("Dev mode is not supported in the python wrapper. Please use the CLI. e.g. python3 -m robyn app.py --dev ")

Expand Down
15 changes: 15 additions & 0 deletions robyn/argument_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,19 @@ def __init__(self) -> None:
default=False,
help="Show the Robyn version.",
)
parser.add_argument(
"--compile-rust-path",
dest="compile_rust_path",
default=None,
help="Compile rust files in the given path.",
)

parser.add_argument(
"--create-rust-file",
dest="create_rust_file",
default=None,
help="Create a rust file with the given name.",
)

args, unknown_args = parser.parse_known_args()

Expand All @@ -66,6 +79,8 @@ def __init__(self) -> None:
self.docs = args.docs
self.open_browser = args.open_browser
self.version = args.version
self.compile_rust_path = args.compile_rust_path
self.create_rust_file = args.create_rust_file

# find something that ends with .py in unknown_args
for arg in unknown_args:
Expand Down
Loading
Loading