HOWTO fetch internet resources

Is there a way in mojo that can be used for fetching websites, get and post?
12 Replies
Alex Kirchhoff
Alex Kirchhoff15mo ago
There is not a built-in way to do it, but you can use the Python interop to use a Python library to do requests for you. In the future the community or Modular may build a library to do it in Mojo natively, but currently Python interop is the only way.
Hasan Yousef
Hasan YousefOP15mo ago
Thanks, I tried using request in Jupyter book it is fine, but in file.mojo it gave an error:
from python import Python

# The Python way: `import requests as http`
let http = Python.import_module("requests")

# Now use request as if writing in Python

fn main():
let url = 'http://example.com'
let response = http.get(url)
let content = response.text
print(content)
from python import Python

# The Python way: `import requests as http`
let http = Python.import_module("requests")

# Now use request as if writing in Python

fn main():
let url = 'http://example.com'
let response = http.get(url)
let content = response.text
print(content)
I got:
/home/hajsf/mojo/python.mojo:1:20: error: recursive reference to declaration
from python import Python
^
/home/hajsf/mojo/python.mojo:1:6: note: previously used here
from python import Python
^
/home/hajsf/mojo/python.mojo:1:1: error: 'object' does not refer to a package or module
from python import Python
^
mojo: error: failed to parse the provided Mojo
/home/hajsf/mojo/python.mojo:1:20: error: recursive reference to declaration
from python import Python
^
/home/hajsf/mojo/python.mojo:1:6: note: previously used here
from python import Python
^
/home/hajsf/mojo/python.mojo:1:1: error: 'object' does not refer to a package or module
from python import Python
^
mojo: error: failed to parse the provided Mojo
No description
Kushagra
Kushagra15mo ago
Could it be because of a top level variable?
roopesh puthalath
@Kushagra @Hasan Yousef @Alex Kirchhoff
Kushagra
Kushagra15mo ago
Ok, I'll try and let you know
roopesh puthalath
@Hasan Yousef let http = Python.import_module("requests") , add this under main it works , post i didnt check
Kushagra
Kushagra15mo ago
I thought of exactly the same
Hasan Yousef
Hasan YousefOP15mo ago
Thanks @roopesh puthalath @Kushagra and @Alex Kirchhoff , I deeply appreciate it. but have a question here, will this make the program speed the same as python or it will be supercharged by mojo?
roopesh puthalath
@Hasan Yousef here the speed is driven by the latency of your fetching.
Alex Kirchhoff
Alex Kirchhoff15mo ago
Only the parts written in Mojo will experience any speed-up.
Prabhu
Prabhu15mo ago
This is because you are shadowing the stdlib module 'python'. Don't create a "python.mojo" file as that will confuse mojo (or Python).
Want results from more Discord servers?
Add your server