Exemple #1
0
def add(prio, cat, name, title):
    "ajout d'une tâche"
    db = util.Couchdb(name)
    if not db.valid():
        return json.dumps(db.status(), indent=2)

    payload = {
        "type": "task",
        "title": ' '.join(title),
        "slug": '-'.join(title),
        "category": cat,
        "priority": prio,
        "status": u'new'
    }

    key = str(uuid.uuid4())
    if not db.put(key, data=payload):
        return json.dumps(db.status(), indent=2)

    response = {
        'status': 'ok',
        'code': 200,
        'msg': {
            'result': u'created',
            'id': key
        }
    }
    current_app.config['logger'].info(response)
    return json.dumps(response, indent=2)
Exemple #2
0
def init(count, name=None):
    "création de tâches exemples"
    db = util.Couchdb(name)
    if not db.valid():
        return json.dumps(db.status(), indent=2)

    # création de tâches
    factory = Faker('fr_FR')
    factory.add_provider(StatusProvider)

    for i in range(0, count):
        title = factory.sentence(nb_words=3)
        payload = {
            "type": "task",
            "title": title,
            "slug": slugify(title),
            "category": factory.word(),
            "priority": factory.word(ext_word_list=('low', 'medium', 'high')),
            "status": factory.status(),
            "description": factory.paragraph(nb_sentences=1)
        }

        if not db.put(str(uuid.uuid4()), data=payload):
            return json.dumps(db.status(), indent=2)

    response = {'status': 'ok', 'code': 200, 'msg': {'result': count}}
    current_app.config['logger'].info(response)
    return json.dumps(response, indent=2)
Exemple #3
0
def init(count, name=None):
    "création de auteurs exemples"
    db = util.Couchdb(name)
    if not db.valid():
        return json.dumps(db.status(), indent=2)

    # génération des auteurs
    factory = Faker('fr_FR')
    factory.add_provider(GenreProvider)

    for i in range(0, count):
        name = factory.last_name()
        first_name = factory.first_name()
        payload = {
            "type": "auteur",
            "nom": name,
            "prenom": first_name,
            "pays": factory.country()
        }

        if not db.put(str(uuid.uuid4()), data=payload):
            return json.dumps(db.status(), indent=2)

    response = {'status': 'ok', 'code': 200, 'msg': {'result': count}}
    current_app.config['logger'].info(response)
    return json.dumps(response, indent=2)
Exemple #4
0
def init(count, name=None):
    "création de livres exemples"
    db = util.Couchdb(name)
    if not db.valid():
        return json.dumps(db.status(), indent=2)

    # génération des livres
    factory = Faker('fr_FR')
    factory.add_provider(GenreProvider)

    for i in range(0, count):
        title = factory.sentence(nb_words=3)
        payload = {
            "type": "book",
            "title": title,
            "slug": slugify(title),
            "author": factory.last_name(),
            "publisher":
            factory.word(ext_word_list=('rivages', 'seuil', 'etc')),
            "genre": factory.genre(),
            "year": factory.year(),
            "description": factory.paragraph(nb_sentences=1)
        }

        if not db.put(str(uuid.uuid4()), data=payload):
            return json.dumps(db.status(), indent=2)

    response = {'status': 'ok', 'code': 200, 'msg': {'result': count}}
    current_app.config['logger'].info(response)
    return json.dumps(response, indent=2)
    return 'ok'
Exemple #5
0
def add(name, country, auteur):
    u"ajout d'un auteur"
    db = util.Couchdb(name)
    if not db.valid():
        return json.dumps(db.status(), indent=2)

    print unicode(country)

    payload = {
        "type": "author",
        "name": auteur[1].capitalize(),
        "firstname": auteur[0].capitalize(),
        "country": country.title()
    }

    print payload
    return

    # verification si auteur existe
    params = {'key': '\"{}\"'.format(payload['name'])}
    view = db.get('_design/authors/_view/byName', params=params)
    if view is None:
        return json.dumps(db.status(), indent=2)

    if view['rows']:
        response = {
            'status': u'error',
            'code': 412,
            'msg': {
                'reason': 'author already exist',
                'name': payload['name']
            }
        }
        return json.dumps(response, indent=2)

    key = str(uuid.uuid4())
    if not db.put(key, data=payload):
        return json.dumps(db.status(), indent=2)

    response = {
        'status': 'ok',
        'code': 200,
        'msg': {
            'result': u'created',
            'id': key
        }
    }
    current_app.config['logger'].info(response)
    return json.dumps(response, indent=2)
Exemple #6
0
def list(f, count, filter, name=None):
    "liste les tâches"
    db = util.Couchdb(name)
    if not db.valid():
        return json.dumps(db.status(), indent=2)

    # récupération des documents
    params = {'limit': count, 'skip': 0}

    if filter == 'prio':
        target = '_design/tasks/_view/byPriority'
        params['key'] = '"low"'
        params['reduce'] = False
    else:
        target = '_design/tasks/_view/byId'

    view = db.get(target, params)
    if view is None:
        return json.dumps(db.status(), indent=2)

    data = []
    table = PrettyTable(['id', 'title', 'category', 'status', 'priority'])

    for task in view['rows']:
        doc = db.get(task['id'])

        data.append({
            'id': doc['_id'],
            'title': doc['title'],
            'category': doc['category'],
            'status': doc['status'],
            'priority': doc['priority']
        })
        table.add_row([
            doc['_id'], doc['title'], doc['category'], doc['status'],
            doc['priority']
        ])

    if f == 'table':
        return table

    sortie = {'total': 10, 'count': 10, 'tasks': data}
    return json.dumps(sortie, indent=2)
Exemple #7
0
def bulk(data, name):
    u'ajout en masse'
    db = util.Couchdb(name)
    if not db.valid():
        return json.dumps(db.status(), indent=2)

    try:
        payload = {'docs': json.load(data)}
    except Exception as e:
        response = {'status': u'error', 'code': 400, 'msg': {'reason': str(e)}}
        return json.dumps(response, indent=2)

    for book in payload['docs']:
        book['type'] = 'book'
        book['slug'] = slugify(book['title'])
        book['_id'] = str(uuid.uuid4())

    db.post('_bulk_docs', data=payload)
    return json.dumps(db.status(), indent=2)
Exemple #8
0
def list(f, count, filter, name=None):
    u"liste des livres"
    db = util.Couchdb(name)
    if not db.valid():
        return json.dumps(db.status(), indent=2)

    # récupération des documents
    params = {'limit': count, 'skip': 0}

    if filter == 'genre':
        target = '_design/books/_view/byGenre'
        params['key'] = '"policier"'
        params['reduce'] = False
    else:
        target = '_design/books/_view/byId'

    view = db.get(target, params)
    if view is None:
        return json.dumps(db.status(), indent=2)

    data = []
    table = PrettyTable(['id', 'title', 'genre', 'author', 'year'])

    for book in view['rows']:
        doc = db.get(book['id'])

        data.append({
            'id': doc['_id'],
            'title': doc['title'],
            'genre': doc['genre'],
            'author': doc['author'],
            'year': doc['year']
        })
        table.add_row([
            doc['_id'], doc['title'], doc['genre'], doc['author'], doc['year']
        ])

    if f == 'table':
        return table

    sortie = {'total': 10, 'count': 10, 'tasks': data}
    return json.dumps(sortie, indent=2)
Exemple #9
0
def bulk(data, name):
    u'ajout en masse'
    db = util.Couchdb(name)
    if not db.valid():
        return json.dumps(db.status(), indent=2)

    try:
        payload = {'docs': json.load(data)}
    except Exception as e:
        response = {'status': u'error', 'code': 400, 'msg': {'reason': str(e)}}
        return json.dumps(response, indent=2)

    for author in payload['docs']:
        author['type'] = 'auteur'
        author['_id'] = str(uuid.uuid4())
        author['pays'] = author['pays'].title()
        author['langue'] = author['langue'].capitalize()
        author['nom'] = author['nom'].title()
        author['prenom'] = author['prenom'].title()
        author['slug'] = slugify(author['prenom'] + ' ' + author['nom'],
                                 separator='_')

    db.post('_bulk_docs', data=payload)
    return json.dumps(db.status(), indent=2)
Exemple #10
0
def list(f, count, start, filtre, name=None):
    u"liste des auteurs"
    db = util.Couchdb(name)
    if not db.valid():
        return json.dumps(db.status(), indent=2)

    if (start < 0) or (count > 20):
        response = {
            'status': u'error',
            'code': 412,
            'msg': {
                'reason': 'invalid count or start conditions'
            }
        }
        return json.dumps(response, indent=2)

    params = {'reduce': False, 'limit': count, 'skip': start, 'stale': 'ok'}

    if filtre is None:
        target = '_design/authors/_view/parNom'
    else:
        try:
            key, val = filtre.split('=')
        except ValueError as e:
            response = {
                'status': u'error',
                'code': 412,
                'msg': {
                    'reason': 'invalid filter format'
                }
            }
            return json.dumps(response, indent=2)

        if key not in ('pays', 'langue', 'sexe', 'genre'):
            response = {
                'status': u'error',
                'code': 412,
                'msg': {
                    'reason': 'invalid filter argument'
                }
            }
            return json.dumps(response, indent=2)

        target = '_design/authors/_view/par' + key.capitalize()
        #        params ['key']='\"{}\"'.format (val.decode('cp1252').capitalize())
        print val.title() if key != 'genre' else val
        params['key'] = '\"{}\"'.format(val.title() if key != 'genre' else val)

    # récupération de la liste des documents
    view = db.get(target, params)
    if view is None:
        return json.dumps(db.status(), indent=2)

    # récupération des auteurs
    data = []
    table = PrettyTable(['id', 'Nom', 'Prenom', 'Pays', 'Langue', 'Sexe'])

    total = view['total_rows']
    count = 0
    for author in view['rows']:
        doc = db.get(author['id'])
        count += 1

        data.append({
            'id': doc['_id'],
            'nom': doc['nom'],
            'prenom': doc['prenom'],
            'pays': doc['pays'],
            'langue': doc['langue'],
            'sexe': doc['sexe']
        })
        table.add_row([
            doc['_id'], doc['nom'], doc['prenom'], doc['pays'], doc['langue'],
            doc['sexe']
        ])

    if f == 'table':
        return table

    sortie = {'total': total, 'count': count, 'start': start, 'auteurs': data}
    with open('alain.json', 'w') as f:
        json.dump(sortie, f)
    return json.dumps(sortie, ensure_ascii=False).encode('utf8')