Ejemplo n.º 1
0
    def match_entry(self, data, key="title"):
        if isinstance(data, Media):
            data = data.as_json()
        db = JsonDatabase(self.name, self.db_path)
        # search by key/value pair
        movies = db.search_by_value(key, data[key])

        if len(movies):
            selected = movies[0]
            item_id = db.get_item_id(selected)
            if item_id >= 0:
                return selected, item_id
        return None, -1
Ejemplo n.º 2
0
 def remove_contact(self, name):
     contact = self.get_contact(name)
     if contact is None:
         raise ContactDoesNotExist
     with JsonDatabase("contacts", self.db_path) as db:
         item_id = db.get_item_id(contact)
         db.remove_item(item_id)
Ejemplo n.º 3
0
    def remove_entry(self, data, normalize=False, key="title"):
        if isinstance(data, Media):
            data = data.as_json()

        title = data.get(key)
        assert title is not None

        # normalization
        if normalize:
            for key in data:
                if isinstance(data[key], list) and key != "streams":
                    for idx, i in enumerate(data[key]):
                        if isinstance(i, str):
                            data[key][idx] = i.lower()
                elif isinstance(data[key], str):
                    data[key] = data[key].lower()

        with JsonDatabase(self.name, self.db_path) as db:

            # search by key/value pair
            movies = db.search_by_value(key, data[key])

            if len(movies):
                selected = movies[0]
                item_id = db.get_item_id(selected)
                if item_id >= 0:
                    print("Removing item from db")
                    db.remove_item(item_id)
Ejemplo n.º 4
0
    def update_contact(self, name, url):
        contact = self.get_contact(name)
        if contact is None:
            raise ContactDoesNotExist

        with JsonDatabase("contacts", self.db_path) as db:
            item_id = db.get_item_id(contact)
            db.update_item(item_id, {"name": name, "url": url})
Ejemplo n.º 5
0
 def add_contact(self, name, url):
     if self.get_contact(name) is not None:
         raise ContactExists
     try:
         with JsonDatabase("contacts", self.db_path) as db:
             user = {"name": name, "url": url}
             db.add_item(user)
     except Exception as e:
         LOG.error(e)
Ejemplo n.º 6
0
 def entries(self):
     entries = []
     collection = JsonDatabase(self.name, self.db_path)
     for ch in collection.db[self.name]:
         if not ch.get("streams") and not ch.get("stream") and not \
                 ch.get("url"):
             continue
         entries.append(Media.from_json(ch))
     return entries
Ejemplo n.º 7
0
 def export_baresip_contacts(self):
     db_dir = join(expanduser("~"), ".baresip", "contacts")
     with JsonDatabase("contacts", self.db_path) as db:
         users = db.search_by_key("url")
     with open(db_dir) as f:
         lines = f.readlines()
     for user in users:
         line = "\"{name}\" <{address}>".format(name=user["name"],
                                                address=user["url"])
         if line not in lines:
             lines.append(line + "\n")
     with open(db_dir, "w") as f:
         f.writelines(lines)
Ejemplo n.º 8
0
    def import_baresip_contacts(self):
        db_dir = join(expanduser("~"), ".baresip", "contacts")
        with open(db_dir) as f:
            lines = f.readlines()

        for line in lines:
            if line.startswith("#") or line == "\n":
                continue
            user, address = line.split("<")
            user = user.replace('"', "")
            address = address.split(">")[0]
            with JsonDatabase("contacts", self.db_path) as db:
                users = db.search_by_value("url", address)
            if not users:
                self.add_contact(user, address)
            else:
                self.update_contact(user, address)
Ejemplo n.º 9
0
    def add_entry(self, data, replace=True, normalize=False, key="title"):
        if isinstance(data, Media):
            data = data.as_json()

        title = data[key]
        assert title is not None

        # normalization
        if normalize:
            for key in data:
                if isinstance(data[key], list) and key != "streams":
                    for idx, i in enumerate(data[key]):
                        if isinstance(i, str):
                            data[key][idx] = i.lower()
                elif isinstance(data[key], str):
                    data[key] = data[key].lower()

        with JsonDatabase(self.name, self.db_path) as db:

            selected, item_id = self.match_entry(data, key=key)
            if selected:
                if replace:
                    print("replacing item in database")
                    db.update_item(item_id, data)
                else:
                    print("merging items")

                    # merge fields
                    for key in data:
                        if key in selected and isinstance(selected[key], list):
                            selected[key] += data[key]
                            # remove duplicates
                            selected[key] = list(set(selected[key]))
                        else:
                            selected[key] = data[key]

                    db.update_item(item_id, selected)
                return
            db.add_item(data)
Ejemplo n.º 10
0
 def list_contacts(self):
     with JsonDatabase("contacts", self.db_path) as db:
         users = db.search_by_key("url")
     return users
Ejemplo n.º 11
0
from json_database import JsonDatabase
from os.path import isfile

optional_file_path = "users.db"

if not isfile(optional_file_path):
    print("run database_create.py first!")
    exit()

db = JsonDatabase(
    "users", optional_file_path)  # loaded automatically from previous step
users_with_defined_age = db.search_by_key("age")

assert len(users_with_defined_age) == 2

for user in users_with_defined_age:
    print(user["name"], user["age"])

# keys do not need to be an exact match
users = db.search_by_key("birth", fuzzy=True)
for user, conf in users:
    print("matched with confidence", conf)
    print(user["name"], user["birthday"])

# search by key/value pair
users_12years_old = db.search_by_value("age", 12)

for user in users_12years_old:
    assert user["age"] == 12

# fuzzy key/value pair search
Ejemplo n.º 12
0
party_name_key = "party_name"
user_name_key = "user_name"
auth_code_key = "auth_code"
playlist_id_key = "playlist_id"
song_name_key = "song_name"
artist_name_key = "artist_name"


spot_actions = SpotifyActions(client_id, client_secret, scope, redirect_uri)

spau = SpotifyOAuth(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri,
                    scope=scope)


app = Flask(__name__)
database = JsonDatabase(database_file_name, write_freq=1)


def _add_party_to_database(db, party):
    _dict = {playlist_id_key: party.playlist_id, user_name_key: party.user, party_name_key: party.party_name,
             auth_code_key: party.auth_code}
    db.insert(_dict)


@app.route('/')
def home():
    return render_template("home.html")


@app.route("/sptfy_auth", methods=['GET', 'POST'])
def auth():
Ejemplo n.º 13
0
 def total_entries(self):
     return len(JsonDatabase(self.name, self.db_path))
Ejemplo n.º 14
0
 def print_collection(self):
     JsonDatabase(self.name, self.db_path).print()
Ejemplo n.º 15
0
 def search_contact(self, url):
     with JsonDatabase("contacts", self.db_path) as db:
         users = db.search_by_value("url", url)
         if len(users):
             return users[0]
     return None
Ejemplo n.º 16
0
 def get_contact(self, name):
     with JsonDatabase("contacts", self.db_path) as db:
         users = db.search_by_value("name", name)
         if len(users):
             return users[0]
     return None
Ejemplo n.º 17
0
from json_database import JsonDatabase

optional_file_path = "users.db"

db = JsonDatabase("users", optional_file_path)

# add some users to the database

for user in [
    {
        "name": "bob",
        "age": 12
    },
    {
        "name": "bobby"
    },
    {
        "name": ["joe", "jony"]
    },
    {
        "name": "john"
    },
    {
        "name": "jones",
        "age": 35
    },
    {
        "name": "jorge"
    },  # NOTE: no duplicate entries allowed
    {
        "name": "jorge"
from json_database import JsonDatabase

db = JsonDatabase("users")


class User:
    def __init__(self, email, key=None, data=None):
        self.email = email
        self.secret_key = key
        self.data = data

    def __repr__(self):
        return "User:"******"*****@*****.**", data={"name": "jonas", "birthday": "12 May"})
user2 = User("*****@*****.**",
             "secret",
             data={
                 "name": ["joe", "jony"],
                 "age": 12
             })

# objects will be jsonified here, they will no longer be User objects
# if you need them to be a specific class use some ORM lib instead (SQLAlchemy is great)
db.add_item(user1)
db.add_item(user2)

# search entries with non empty key
print(db.search_by_key("secret_key"))
Ejemplo n.º 19
0
 def add_contact(self, name, url):
     if self.get_contact(name) is not None:
         raise ContactExists
     with JsonDatabase("contacts", self.db_path) as db:
         user = {"name": name, "url": url}
         db.add_item(user)
Ejemplo n.º 20
0
 def print_contacts(self):
     with JsonDatabase("contacts", self.db_path) as db:
         db.print()
from json_database import JsonDatabase

db_path = "users.db"

with JsonDatabase("users", db_path) as db:
    # add some users to the database

    for user in [{
            "name": "bob",
            "age": 12
    }, {
            "name": "bobby"
    }, {
            "name": ["joe", "jony"]
    }, {
            "name": "john"
    }, {
            "name": "jones",
            "age": 35
    }, {
            "name": "joey",
            "birthday": "may 12"
    }]:
        db.add_item(user)

# auto saved