pyi18n-v2


Namepyi18n-v2 JSON
Version 1.2.2 PyPI version JSON
download
home_pagehttps://github.com/sectasy0/pyi18n
SummarySimple and easy to use internationalizationlibrary inspired by Ruby i18n
upload_time2024-06-21 05:24:39
maintainerNone
docs_urlNone
authorPiotr Markiewicz
requires_pythonNone
licenseMIT License
keywords pyi18n
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            # PyI18n
> PyI18n is GNU gettext free, simple and easy to use internationalization library for Python, inspired by Ruby i18n.

![Python version][python-image] [![Code Climate](https://codeclimate.com/github/sectasy0/pyi18n/badges/gpa.svg)](https://codeclimate.com/github/sectasy0/pyi18n/coverage) [![Issue Count](https://codeclimate.com/github/sectasy0/pyi18n/badges/issue_count.svg)](https://codeclimate.com/github/sectasy0/pyi18n) [![pyi18n](https://github.com/sectasy0/pyi18n/actions/workflows/python-app.yml/badge.svg)](https://github.com/sectasy0/pyi18n/actions/workflows/python-app.yml)

**Documentation available at [https://sectasy0.github.io/pyi18n](https://sectasy0.github.io/pyi18n).**

## Installation

You can install PyI18n via pip:
```sh
pip install pyi18n-v2
```

## Getting Started

A few motivating and useful examples of how pyi18n can be used.

To use PyI18n in your application, you will first need to create a locales folder in the root directory of your project. Within this folder, you can create locale files in the format of your choice (e.g. YAML, JSON).

For example:

```sh
$ mkdir -p my_app/locales
$ touch my_app/locales/en.yml
$ touch my_app/locales/pl.yml
$ touch my_app/locales/de.yml
```

You can then create an instance of the PyI18n class, passing in the desired languages and, optionally, a custom locales directory.

```python
from pyi18n import PyI18n

# default load_path is locales/
# you can change this path by specifying load_path parameter
i18n = PyI18n(("en", "pl", "de", "jp"), load_path="translations/")
_: callable = i18n.gettext

print(_("en", "hello.hello_user", user="John"))
#> Hello John!

print(_("pl", "hello.hello_user", user="John"))
#> Witaj John!

print(_("de", "hello.hello_user", user="John"))
#> Hallo John!

print(_("jp", "hello.hello_user", user="ジョンさん"))
#> こんにちは、ジョンさん!
```

## Namespaces

PyI18n supports namespaces, which allows you to organize your translations into separate groups.

To use PyI18n with namespaces, you need to define the loader object yourself. Here's an example:
```py
from pyi18n.loaders import PyI18nYamlLoader
from pyi18n import PyI18n

if __name__ == "__main__":
    loader: PyI18nYamlLoader = PyI18nYamlLoader('locales/', namespaced=True)
    pyi18n: PyI18n = PyI18n(('en_US', 'de_DE'), loader=loader)

```

In this example, we create an instance of the PyI18nYamlLoader class with the namespaced parameter set to True. This tells the loader to look for namespaced locales in separate folders instead of one single file for one locale.

Here's an example of the expected file structure for the locales:
```
locales
    en_US
        common.yml
        analysis.yml
    de_DE
        common.yml
        analysis.yml
```

To get a key that is located in the common namespace, you should use the dot notation in your translation call:
```py
_(locale, 'common.greetings')
```

## Integrate pyi18n with Django project
To integrate pyi18n into your Django project, you will need to first add a locale field to your user model class. This field will store the user's preferred language, which will be used to retrieve the appropriate translations from the locales directory.

Next, you will need to configure pyi18n in your settings.py file by creating an instance of the PyI18n class and specifying the available languages. You can also create a gettext function for ease of use.

In your views, you can then use the gettext function to retrieve translations based on the user's preferred language. To use translations in templates, you will need to create a custom template tag that utilizes the gettext function.


### settings.py
```python
from pyi18n import PyI18n

i18n: PyI18n = PyI18n(['pl', 'en'])
_: callable = i18n.gettext
```

### views.py
```python
from mysite.settings import _

def index(request):
    translated: str = _(request.user.locale, 'hello', name="John")
    return HttpResponse(f"This is an example view. {translated}")
```

### register template tag
```python
from django import template
from mysite.settings import _

register = template.Library()

@register.simple_tag
def translate(locale: str, path: str, **kwargs):
    return _(locale, path, **kwargs)
```

### usage in templates
> **_NOTE:_**  Wrap this tag inside jinja2 special characters
```python
translate request.current_user.locale, "hello", name="John"
```

That's it, you have now successfully installed and configured PyI18n for your project. You can now use the provided gettext function to easily retrieve translations based on the user's preferred language. Additionally, you can use the provided template tag to easily retrieve translations in your templates. And if you need to use custom loaders you can use the PyI18nBaseLoader to create your own loaders.

---
## Creating custom loader class

To create custom locale loader you have to create a class which will inherit from PyI18nBaseLoader and override `load` method with all required parameters (see below). You can see an example of custom locale loader in `examples/custom_xml_loader.py`.

```python
from pyi18n.loaders import PyI18nBaseLoader


class MyCustomLoader(PyI18nBaseLoader):

    def load(self, locales: tuple, load_path: str):
        # load_path is the path where your loader will look for locales files
        # locales is a tuple of locales which will be loaded
        # return a dictionary with locale data

        ...your custom loader logic...

        return {}
```

Then pass your custom loader to PyI18n class.

```python
from pyi18n.loaders import PyI18nBaseLoader


class MyCustomLoader(PyI18nBaseLoader):

    def load(self, locales: tuple, load_path: str):
        # load_path is the path where your loader will look for locales files
        # locales is a tuple of locales which will be loaded

        ...your custom loader logic...

        # have to return a dictionary
        return {}

# don't use load_path in `PyI18n` constructor, if not using default yaml loader
if __name__ == "__main__":
    load_path: str = "locales/"
    loader: PyI18nBaseLoader = MyCustomLoader(load_path=load_path)
    i18n: PyI18n = PyI18n(("en",), loader=loader)
    _: callable = i18n.gettext

    print(_("en", "hello.hello_user", user="John"))
    #> Hello John!
```

## Tasks

### Tasks usage

```sh
$ pyi18n-tasks
usage: pyi18n-tasks [-h] [-p PATH] normalize
pyi18n-tasks: error: the following arguments are required: normalize
```

### Normalization
Normalization process will sort locales alphabetically. The default normalization path is `locales/`, you can change it by passing `-p` argument.

```sh
$ pyi18n-tasks normalize
```

```sh
$ pyi18n-tasks normalize -p my_app/locales/
```

## Run tests

```sh
python3 tests/run_tests.py
```

For any questions and suggestions or bugs please create an issue.
## Limitations
* Normalization task will not work for custom loader classes except xml, cause it's based on loader type field ( If you have an idea how to solve this differently please open the issue with a description ), if you need that use one of build in loaders or user XML loader from example.

## Roadmap

See issues, If I have enough time and come up with a good idea on how this package can be improved, I'll post it there, along with tip.

## Release History

**Release History available at [https://sectasy0.github.io/pyi18n/home/release-history/](https://sectasy0.github.io/pyi18n/home/release-history/).**

## Contributing

1. Fork it (<https://github.com/sectasy0/pyi18n>)
2. Create your feature branch (`git checkout -b feature/fooBar`)
3. Commit your changes (`git commit -am 'feat: Add some fooBar'`)
4. Push to the branch (`git push origin feature/fooBar`)
5. Create a new Pull Request

[python-image]: https://img.shields.io/badge/python-3.6-blue
[pypi-image]: https://img.shields.io/badge/pypi-remly-blue
[pypi-url]:  pypi.org/project/pyi18n/



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/sectasy0/pyi18n",
    "name": "pyi18n-v2",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "pyi18n",
    "author": "Piotr Markiewicz",
    "author_email": "sectasy0@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/45/c9/b7da06f31595185aa01f1b2ad4d0bc187f499278cc98b5b29bc5d5f6ce61/pyi18n-v2-1.2.2.tar.gz",
    "platform": null,
    "description": "# PyI18n\n> PyI18n is GNU gettext free, simple and easy to use internationalization library for Python, inspired by Ruby i18n.\n\n![Python version][python-image] [![Code Climate](https://codeclimate.com/github/sectasy0/pyi18n/badges/gpa.svg)](https://codeclimate.com/github/sectasy0/pyi18n/coverage) [![Issue Count](https://codeclimate.com/github/sectasy0/pyi18n/badges/issue_count.svg)](https://codeclimate.com/github/sectasy0/pyi18n) [![pyi18n](https://github.com/sectasy0/pyi18n/actions/workflows/python-app.yml/badge.svg)](https://github.com/sectasy0/pyi18n/actions/workflows/python-app.yml)\n\n**Documentation available at [https://sectasy0.github.io/pyi18n](https://sectasy0.github.io/pyi18n).**\n\n## Installation\n\nYou can install PyI18n via pip:\n```sh\npip install pyi18n-v2\n```\n\n## Getting Started\n\nA few motivating and useful examples of how pyi18n can be used.\n\nTo use PyI18n in your application, you will first need to create a locales folder in the root directory of your project. Within this folder, you can create locale files in the format of your choice (e.g. YAML, JSON).\n\nFor example:\n\n```sh\n$ mkdir -p my_app/locales\n$ touch my_app/locales/en.yml\n$ touch my_app/locales/pl.yml\n$ touch my_app/locales/de.yml\n```\n\nYou can then create an instance of the PyI18n class, passing in the desired languages and, optionally, a custom locales directory.\n\n```python\nfrom pyi18n import PyI18n\n\n# default load_path is locales/\n# you can change this path by specifying load_path parameter\ni18n = PyI18n((\"en\", \"pl\", \"de\", \"jp\"), load_path=\"translations/\")\n_: callable = i18n.gettext\n\nprint(_(\"en\", \"hello.hello_user\", user=\"John\"))\n#> Hello John!\n\nprint(_(\"pl\", \"hello.hello_user\", user=\"John\"))\n#> Witaj John!\n\nprint(_(\"de\", \"hello.hello_user\", user=\"John\"))\n#> Hallo John!\n\nprint(_(\"jp\", \"hello.hello_user\", user=\"\u30b8\u30e7\u30f3\u3055\u3093\"))\n#> \u3053\u3093\u306b\u3061\u306f\u3001\u30b8\u30e7\u30f3\u3055\u3093\uff01\n```\n\n## Namespaces\n\nPyI18n supports namespaces, which allows you to organize your translations into separate groups.\n\nTo use PyI18n with namespaces, you need to define the loader object yourself. Here's an example:\n```py\nfrom pyi18n.loaders import PyI18nYamlLoader\nfrom pyi18n import PyI18n\n\nif __name__ == \"__main__\":\n    loader: PyI18nYamlLoader = PyI18nYamlLoader('locales/', namespaced=True)\n    pyi18n: PyI18n = PyI18n(('en_US', 'de_DE'), loader=loader)\n\n```\n\nIn this example, we create an instance of the PyI18nYamlLoader class with the namespaced parameter set to True. This tells the loader to look for namespaced locales in separate folders instead of one single file for one locale.\n\nHere's an example of the expected file structure for the locales:\n```\nlocales\n    en_US\n        common.yml\n        analysis.yml\n    de_DE\n        common.yml\n        analysis.yml\n```\n\nTo get a key that is located in the common namespace, you should use the dot notation in your translation call:\n```py\n_(locale, 'common.greetings')\n```\n\n## Integrate pyi18n with Django project\nTo integrate pyi18n into your Django project, you will need to first add a locale field to your user model class. This field will store the user's preferred language, which will be used to retrieve the appropriate translations from the locales directory.\n\nNext, you will need to configure pyi18n in your settings.py file by creating an instance of the PyI18n class and specifying the available languages. You can also create a gettext function for ease of use.\n\nIn your views, you can then use the gettext function to retrieve translations based on the user's preferred language. To use translations in templates, you will need to create a custom template tag that utilizes the gettext function.\n\n\n### settings.py\n```python\nfrom pyi18n import PyI18n\n\ni18n: PyI18n = PyI18n(['pl', 'en'])\n_: callable = i18n.gettext\n```\n\n### views.py\n```python\nfrom mysite.settings import _\n\ndef index(request):\n    translated: str = _(request.user.locale, 'hello', name=\"John\")\n    return HttpResponse(f\"This is an example view. {translated}\")\n```\n\n### register template tag\n```python\nfrom django import template\nfrom mysite.settings import _\n\nregister = template.Library()\n\n@register.simple_tag\ndef translate(locale: str, path: str, **kwargs):\n    return _(locale, path, **kwargs)\n```\n\n### usage in templates\n> **_NOTE:_**  Wrap this tag inside jinja2 special characters\n```python\ntranslate request.current_user.locale, \"hello\", name=\"John\"\n```\n\nThat's it, you have now successfully installed and configured PyI18n for your project. You can now use the provided gettext function to easily retrieve translations based on the user's preferred language. Additionally, you can use the provided template tag to easily retrieve translations in your templates. And if you need to use custom loaders you can use the PyI18nBaseLoader to create your own loaders.\n\n---\n## Creating custom loader class\n\nTo create custom locale loader you have to create a class which will inherit from PyI18nBaseLoader and override `load` method with all required parameters (see below). You can see an example of custom locale loader in `examples/custom_xml_loader.py`.\n\n```python\nfrom pyi18n.loaders import PyI18nBaseLoader\n\n\nclass MyCustomLoader(PyI18nBaseLoader):\n\n    def load(self, locales: tuple, load_path: str):\n        # load_path is the path where your loader will look for locales files\n        # locales is a tuple of locales which will be loaded\n        # return a dictionary with locale data\n\n        ...your custom loader logic...\n\n        return {}\n```\n\nThen pass your custom loader to PyI18n class.\n\n```python\nfrom pyi18n.loaders import PyI18nBaseLoader\n\n\nclass MyCustomLoader(PyI18nBaseLoader):\n\n    def load(self, locales: tuple, load_path: str):\n        # load_path is the path where your loader will look for locales files\n        # locales is a tuple of locales which will be loaded\n\n        ...your custom loader logic...\n\n        # have to return a dictionary\n        return {}\n\n# don't use load_path in `PyI18n` constructor, if not using default yaml loader\nif __name__ == \"__main__\":\n    load_path: str = \"locales/\"\n    loader: PyI18nBaseLoader = MyCustomLoader(load_path=load_path)\n    i18n: PyI18n = PyI18n((\"en\",), loader=loader)\n    _: callable = i18n.gettext\n\n    print(_(\"en\", \"hello.hello_user\", user=\"John\"))\n    #> Hello John!\n```\n\n## Tasks\n\n### Tasks usage\n\n```sh\n$ pyi18n-tasks\nusage: pyi18n-tasks [-h] [-p PATH] normalize\npyi18n-tasks: error: the following arguments are required: normalize\n```\n\n### Normalization\nNormalization process will sort locales alphabetically. The default normalization path is `locales/`, you can change it by passing `-p` argument.\n\n```sh\n$ pyi18n-tasks normalize\n```\n\n```sh\n$ pyi18n-tasks normalize -p my_app/locales/\n```\n\n## Run tests\n\n```sh\npython3 tests/run_tests.py\n```\n\nFor any questions and suggestions or bugs please create an issue.\n## Limitations\n* Normalization task will not work for custom loader classes except xml, cause it's based on loader type field ( If you have an idea how to solve this differently please open the issue with a description ), if you need that use one of build in loaders or user XML loader from example.\n\n## Roadmap\n\nSee issues, If I have enough time and come up with a good idea on how this package can be improved, I'll post it there, along with tip.\n\n## Release History\n\n**Release History available at [https://sectasy0.github.io/pyi18n/home/release-history/](https://sectasy0.github.io/pyi18n/home/release-history/).**\n\n## Contributing\n\n1. Fork it (<https://github.com/sectasy0/pyi18n>)\n2. Create your feature branch (`git checkout -b feature/fooBar`)\n3. Commit your changes (`git commit -am 'feat: Add some fooBar'`)\n4. Push to the branch (`git push origin feature/fooBar`)\n5. Create a new Pull Request\n\n[python-image]: https://img.shields.io/badge/python-3.6-blue\n[pypi-image]: https://img.shields.io/badge/pypi-remly-blue\n[pypi-url]:  pypi.org/project/pyi18n/\n\n\n",
    "bugtrack_url": null,
    "license": "MIT License",
    "summary": "Simple and easy to use internationalizationlibrary inspired by Ruby i18n",
    "version": "1.2.2",
    "project_urls": {
        "Homepage": "https://github.com/sectasy0/pyi18n"
    },
    "split_keywords": [
        "pyi18n"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "706162315bfda77798c049e2b7d3ea9182b93597ef7804460659d84fd131f661",
                "md5": "01e482215664cadab3f73d32cc94f0cc",
                "sha256": "1a5f64f4d1fde0a559876288849893384ac0ef25ba8df06ff7eac25ac368e556"
            },
            "downloads": -1,
            "filename": "pyi18n_v2-1.2.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "01e482215664cadab3f73d32cc94f0cc",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 18981,
            "upload_time": "2024-06-21T05:24:36",
            "upload_time_iso_8601": "2024-06-21T05:24:36.912204Z",
            "url": "https://files.pythonhosted.org/packages/70/61/62315bfda77798c049e2b7d3ea9182b93597ef7804460659d84fd131f661/pyi18n_v2-1.2.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "45c9b7da06f31595185aa01f1b2ad4d0bc187f499278cc98b5b29bc5d5f6ce61",
                "md5": "4add4ebae31e6386bbe7d75f015e09f5",
                "sha256": "96919717c933f6cfa4abfd496ce9f6d0ccad0ac74361475883b2e236fc5c14e7"
            },
            "downloads": -1,
            "filename": "pyi18n-v2-1.2.2.tar.gz",
            "has_sig": false,
            "md5_digest": "4add4ebae31e6386bbe7d75f015e09f5",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 17628,
            "upload_time": "2024-06-21T05:24:39",
            "upload_time_iso_8601": "2024-06-21T05:24:39.024545Z",
            "url": "https://files.pythonhosted.org/packages/45/c9/b7da06f31595185aa01f1b2ad4d0bc187f499278cc98b5b29bc5d5f6ce61/pyi18n-v2-1.2.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-21 05:24:39",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "sectasy0",
    "github_project": "pyi18n",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "pyi18n-v2"
}
        
Elapsed time: 3.38450s