Git Product home page Git Product logo

pywry's Introduction

PyWry Web Viewer

PyWryLogo

Easily create HTML webviewers in python utilizing the wry library. Unlike many HTML viewers that exist for Python - Pywry allows you to run javascript. PyWry is also a ~2mb footprint for Mac and Windows - Linux will require a few more libraries which are listed below.

Please note: this library is currently in early alpha and is NOT ready for production use.

Installation


PyWry is available on PyPI and can be installed with pip:

pip install pywry

For development, you can install from source with the following steps:

  • Clone the repository: git clone https://github.com/OpenBB-finance/pywry.git
  • Install rust: curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  • Create a virtual environment: python -m venv venv
  • Acitvate the environment: source venv/bin/activate (Unix) or venv\Scripts\activate (Windows)
  • Install dependencies: pip install .[dev]
  • Build the pip package: maturin build
  • Install the package: pip install [file path from above] --force-reinstall

Usage

import asyncio
import sys

from pywry import PyWry


async def main_loop():
    while True:
        await asyncio.sleep(1)


if __name__ == "__main__":
    try:
        handler = PyWry()
        handler.send_html("<h1 style='color: red;'>Welcome to PyWry!</h1>")
        handler.start()

        # PyWry creates a new thread for the backend,
        # so we need to run the main loop in the main thread.
        # otherwise, the program will exit immediately.
        handler.loop.run_until_complete(main_loop())
    except KeyboardInterrupt:
        print("Keyboard interrupt detected. Exiting...")
        sys.exit(0)

JSON Keys

PyWry uses a JSON object to communicate between the python and rust backends and the javascript frontend. The following keys are available:

Key Type Description
html Path | str The path to the HTML file to be loaded, or HTML string.
title str The title of the window.
icon str | Path The path to png icon to be used for the window.
json_data str | dict A JSON string or dictionary to be passed to the javascript frontend. (see below)
height int The height of the window.
width int The width of the window.
download_path str | Path The path to the download directory.

Javascript

PyWry allows you to run javascript in the frontend. To do this, you can pass a dictionary of data to the json_data key in the send_html method. This dictionary will be converted to a JSON string and passed to the frontend. You can then access this data in the frontend by using the window.json_data object. For example:


Python

from pathlib import Path
# code from above ...

# change send_html line to:
        handler.send_html(
            html=Path(__file__).parent / "index.html", json_data={"name": "PyWry"}
        )

HTML

<html>
    <head>
        <script>
            window.onload = () => {
                // if you passed a JSON string, you will need to parse it first
                if (typeof window.json_data === "string") {
                    window.json_data = JSON.parse(window.json_data);
                }
                document.getElementById("name").innerHTML = window.json_data.name;
            };
        </script>
    </head>
    <body>
        <h1 style='color: red;'>Hello, <span id="name"></span>!</h1>
    </body>
</html>

Platform-specific notes

All platforms use TAO to build the window, and wry re-exports it as an application module. Here is the underlying web engine each platform uses, and some dependencies you might need to install.

Linux

Tao uses gtk-rs and its related libraries for window creation and wry also needs WebKitGTK for WebView. So please make sure the following packages are installed:

Arch Linux / Manjaro

sudo pacman -S webkit2gtk

Debian / Ubuntu

sudo apt install libwebkit2gtk-4.0-dev

Fedora / CentOS / AlmaLinux

sudo dnf install gtk3-devel webkit2gtk3-devel

macOS

WebKit is native to macOS, so no additional dependencies are needed.

Windows

WebView2 provided by Microsoft Edge Chromium is used. So wry supports Windows 7, 8, 10 and 11.


Troubleshooting Linux

"/lib/x86_64-linux-gnu/libgio-2.0.so.0: undefined symbol: g_module_open_full"

This is a known issue with the gio library. You can fix it by installing the libglib2.0-dev package.

PyWry is a project that aims to provide Python bindings for WRY, a cross-platform webview library. WRY is a trademark of the Tauri Program within the Commons Conservancy and PyWry is not officially endorsed or supported by them. PyWry is an independent and community-driven effort that respects the original goals and values of Tauri and WRY. PyWry does not claim any ownership or affiliation with WRY or the Tauri Program.

pywry's People

Contributors

andrewkenreich avatar colin99d avatar dependabot[bot] avatar didierrlopes avatar jose-donato avatar tehcoderer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

pywry's Issues

'--release' cannot be used multiple times

When building from source using maturin I'm getting the following error:

cargo rustc --lib --manifest-path Cargo.toml --features pyo3/extension-module --release --no-default-features --release -v -- --crate-type cdylib
error: the argument '--release' cannot be used multiple times

Extreme CPU usage

This is continuation of this issue

OpenBB-finance/OpenBBTerminal#5104

Just running this example

import asyncio
import sys

from pywry import PyWry


async def main_loop():
    while True:
        await asyncio.sleep(1)


if __name__ == "__main__":
    try:
        handler = PyWry()
        handler.send_html("<h1 style='color: red;'>Welcome to PyWry!</h1>")
        handler.start()

        # PyWry creates a new thread for the backend,
        # so we need to run the main loop in the main thread.
        # otherwise, the program will exit immediately.
        handler.loop.run_until_complete(main_loop())
    except KeyboardInterrupt:
        print("Keyboard interrupt detected. Exiting...")
        sys.exit(0)

Gives 100 CPU usage. Why is that ? This consumes more cpu than anything else in openbb.

Is it busy waiting ?
Is it missing asyncio.sleep somewhere?

Build failure on Linux with wry 0.31.0

Tested on Linux with rustc 1.72.0 and 1.64.0 and python 3.9 and 3.10 in a clean conda environment, installing pywry through pip.

Build fails because method EventLoop::with_user_event is used and wry 0.31.0 is specified in Cargo.toml, even though this method was dropped in 0.31.0.

error[E0599]: no function or associated item named `with_user_event` found for struct `EventLoop<_>` in the current scope
         --> src/headless.rs:160:52
          |
      160 |     let event_loop: EventLoop<UserEvent> = EventLoop::with_user_event();
          |                                                       ^^^^^^^^^^^^^^^ function or associated item not found in `EventLoop<_>`


      error[E0599]: no function or associated item named `with_user_event` found for struct `EventLoop<_>` in the current scope
         --> src/window.rs:223:52
          |
      223 |     let event_loop: EventLoop<UserEvent> = EventLoop::with_user_event();
          |                                                       ^^^^^^^^^^^^^^^ function or associated item not found in `EventLoop<_>`

That being said, with_user_event still exists in class EventLoopBuilder, and the latter is used by pywry in headless.rs and window.rs on Windows and Mac platforms. Should we use it on all platforms now?

Build failure with latest rustc

Build fails with rustc 1.72.0 with the following errors (fine with rustc 1.64.0):

      error[E0308]: mismatched types
         --> src/headless.rs:155:51
          |
      155 | pub fn start_headless(console: ConsolePrinter) -> Result<(), String> {
          |        --------------                             ^^^^^^^^^^^^^^^^^^ expected `Result<(), String>`, found `()`
          |        |
          |        implicitly returns `()` as its body has no tail or `return` expression
          |
          = note:   expected enum `Result<(), std::string::String>`
                  found unit type `()`


      error[E0308]: mismatched types
         --> src/window.rs:218:46
          |
      218 | pub fn start_wry(console: ConsolePrinter) -> Result<(), String> {
          |        ---------                             ^^^^^^^^^^^^^^^^^^ expected `Result<(), String>`, found `()`
          |        |
          |        implicitly returns `()` as its body has no tail or `return` expression
          |
          = note:   expected enum `Result<(), std::string::String>`
                  found unit type `()`

pyinstaller doesn't work

When compiling the example to exe using pyinstaller

pyinstaller --onedir main.py

and then opening the compiled exe file the app starts but no window is opened and no error

typo in the readme

Easily create HTML webviewers in python utilizing the yrw library

should be wry not yrw

GLIBCXX_3.4.32 not found error

The error:
/home/user/.conda/envs/obb/bin/../lib/libstdc++.so.6: version `GLIBCXX_3.4.32' not found (required by /lib64/libwebkit2gtk-4.0.so.37)

How to replicate:

  1. install OpenBBTerminal by following the directions for linux (fedora)
  2. create, activate and install dependencies for the conda obb env
  3. python -c 'import pywry'

The installed files are one version short

(obb) [user@fedoralaptop OpenBBTerminal]$ strings /home/user/.conda/envs/obb/bin/../lib/libstdc++.so.6 | grep GLIBCXX_3.4.3
GLIBCXX_3.4.3
GLIBCXX_3.4.30
GLIBCXX_3.4.31
GLIBCXX_3.4.31
GLIBCXX_3.4.3
GLIBCXX_3.4.30

Error installing `pywry` when building `OpenBB Terminal` from source

Hi

I was trying to build OpenBB Terminal from source but when running poetry install -E all your package failed to build.
I am using a computer with Ubuntu 22.04.

The error output I got was this.

After running

sudo apt-get install libjavascriptcoregtk-4.1-dev

I got an equivalent error, now saying that I need the package libsoup-3.0.

By running

sudo apt install libsoup-3.0-dev

I again got an equivalent error, now saying that I need the package libwebkit2gtk-4.1 ๐Ÿค 

Finally, by running

sudo apt install libwebkit2gtk-4.1-dev

and then poetry install -E all I succeeded in building OpenBBTerminal.

I am curious to why the dependency issues weren't handled by the underlying Rust code?

Cheers
jsr-p

Security Address

Hello!

I may have found a security issue in latest version of pywry. Following responsible disclosure, is there an email or other private channel where I could share the details?
Thank you

Two way communication

Add two way communication so we can call Python from frontend or call JS from Python

Bundling and Updating

We would love to add pywry to our examples at https://github.com/crabnebula-dev/cargo-packager - which is a generic bundler and updater based on the original systems we built for Tauri, but designed for use by anyone who needs the elegance and security of developer signatures to verify updates regardless of their underlying language paradigm.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.