Skip to content

Commit

Permalink
added Tag64 to convert to html tags and fixed some errors
Browse files Browse the repository at this point in the history
  • Loading branch information
N0x1s committed Jun 25, 2020
1 parent 7a332e8 commit 6390a90
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 51 deletions.
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

# b64!
[![Python 3.7.1](https://img.shields.io/badge/Python-3.7.1-green.svg)](http://www.python.org/download/)

Expand All @@ -23,7 +24,7 @@ cd data_b64
python setup.py install
```
## How to use

### 1) Converting local/remote images/text ... to base64 and the opposite
Let us suppose you have a group of data that you want to convert to base64 or the opposite
```python
>>> from b64 import B64
Expand All @@ -48,6 +49,16 @@ Let us suppose you have a group of data that you want to convert to base64 or th
> b'iVBORw0KGgoAAAANSUhEUgAAAcwAAAHMCAYAAABY25iGA...'
>>> B64('example.txt', to='string').data # converting local base64 string to bytes
> b'Hello'
```
### 2) convert videos/images/css/js ... to html tag
```python
>>> from b64 import Tag64
>>> t = Tag64('https://avatars3.githubusercontent.com/u/1', 'img')
>>> t.html_tag
> '<img src="data:;base64,/9j/4AAQSkZJRgABAQAAAQA...'
>>> t.data_uri
> b'iVBORw0KGgoAAAANSUhEUgAAAcwAAAHMCAYAAABY25iGA...'

```
## Todo
I will try to maintain this respiratory and update or add new things to it you are welcome to contribute :relaxed:
Expand Down
5 changes: 4 additions & 1 deletion b64/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
from .core import B64
from .core import (
B64,
Tag64
)
42 changes: 39 additions & 3 deletions b64/core.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from b64 import utils
import base64
from urllib import parse
from b64 import utils
from cached_properties import Property as property
from bs4 import BeautifulSoup


class B64:
Expand All @@ -25,7 +25,7 @@ def file_bytes(self):
if not self.source:
raise utils.FileNotFound
return self.source
elif parse.urlparse(self.source).scheme:
elif utils.fix_url(self.source, True).scheme:
r = utils.download_file(self.source, *self._args, **self._kwargs)
del self._args, self._kwargs
return r
Expand All @@ -34,3 +34,39 @@ def file_bytes(self):
@property
def data(self):
return self.convert()


class Tag64:
""" convert html, css, images tags, to html(base64) """
__version__ = '0.1'
def __init__(self, source, tag=None, mime=None, tag_attr={}):
self.source = source
self.tag = tag
self.mime = mime
self.tag_attr = tag_attr

@property(timeout=3600)
def b64_string(self):
return B64(self.source).data.decode('utf-8')

@property
def data_uri(self):
return f'data:{self.mime if self.mime else ""};base64,{self.b64_string}'

@property
def attr(self):
if self.tag == 'link':
return 'href'
elif self.tag == 'object':
return 'data'
return 'src'

@property
def html_tag(self):
t = self.soup_contractor.new_tag(name=self.tag,
**{self.attr:self.data_uri}, **self.tag_attr)
return str(t) # t

@property(general=True)
def soup_contractor(self):
return BeautifulSoup(features='lxml')
79 changes: 37 additions & 42 deletions b64/utils.py
Original file line number Diff line number Diff line change
@@ -1,52 +1,47 @@
import os
import requests


class FileNotFound(Exception):
""" Exception for file not found """
""" Exception for file not found """

def __init__(self):
msg = '''
def __init__(self):
msg = '''
File Not Found, please check your path, permission, and headers
And Try Again'''
super().__init__(msg)


def download_file(source, codes=(200, ), chunk=1024, *args, **kwargs) -> bytes:
""" a function to download files from internet to bytes """
file = bytes()
try:
r = requests.get(source, stream=True, *args, **kwargs)
except Exception as e:
raise FileNotFound
if r.status_code not in codes:
raise FileNotFound
while True:
r.raw.decode_content = True
part = r.raw.read(chunk)
if not part:
break
file += part
return file
super().__init__(msg)


def download_file(source, codes=None, chunk=1024, *args, **kwargs) -> bytes:
""" a function to download files from internet to bytes """
if codes is None:
codes = range(100, 309)
file = bytes()
try:
r = requests.get(fix_url(source), stream=True, *args, **kwargs)
except Exception as e:
raise FileNotFound
if r.status_code not in codes:
raise FileNotFound
while True:
r.raw.decode_content = True
part = r.raw.read(chunk)
if not part:
break
file += part
return file


def read_file(source: str) -> bytes:
""" read local file bytes """
if os.path.exists(source) and os.path.isfile(source):
with open(source, 'rb') as fobj:
return fobj.read()
raise FileNotFound


def exists(source) -> bool:
""" check if the source exists """
dtype = self._detect_type(source)
if dtype == 'local':
return os.path.exists(source) and os.path.isfile(source)
elif dtype == 'remote':
try:
r = request.urlopen(source)
except Exception as e:
return False
return r.status in code
return bool(source)
""" read local file bytes """
if os.path.exists(source) and os.path.isfile(source):
with open(source, 'rb') as fobj:
return fobj.read()
raise FileNotFound


def fix_url(url, parse=False):
if parse:
return requests.utils.urlparse(url)
if url.startswith('//'):
return f'https:{url}'
return url
19 changes: 15 additions & 4 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
from distutils.core import setup
with open('README.md', 'r', encoding='utf-8') as fobj:
long_description = fobj.read()

setup(
name='b64',
packages=['b64'],
version='0.1',
version='0.3',
license='MIT',
description='convert local/online data to base64 fast, easy and clean',
description='convert html/local/online data to base64 fast, easy and clean',
author='n0x1s',
author_email='[email protected]',
url='https://github.com/n0x1s/data_b64',
download_url='https://github.com/N0x1s/data_b64/archive/0.2.tar.gz',
download_url='https://github.com/N0x1s/data_b64/archive/0.3.tar.gz',
long_description=long_description,
long_description_content_type="text/markdown",
keywords=['base64', 'image to base64', 'video to base64',
'base64 convert'],
'base64 convert', 'html to base64', 'data uri'],
install_requires=[
'requests',
'bs4',
'lxml',
'cached_properties',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
Expand Down

0 comments on commit 6390a90

Please sign in to comment.