Ejemplo n.º 1
0
 def post(self, *args, **kwargs):
     try:
         data = dict()
         data['name'] = self.get_argument('name')
         data['department'] = self.get_argument('department')
         data['description'] = self.get_argument('description')
         data['prize'] = self.get_argument('prize')
         manager1 = dict(name=self.get_argument('manager1-name'),
                         number=self.get_argument('manager1-phone'),
                         email=self.get_argument('manager1-email'))
         manager2 = dict(name=self.get_argument('manager2-name'),
                         number=self.get_argument('manager2-phone'),
                         email=self.get_argument('manager2-email'))
         manager3 = dict(name=self.get_argument('manager3-name'),
                         number=self.get_argument('manager3-phone'),
                         email=self.get_argument('manager3-email'))
         manager4 = dict(name=self.get_argument('manager4-name'),
                         number=self.get_argument('manager4-phone'),
                         email=self.get_argument('manager4-email'))
         data['manager'] = [manager1, manager2, manager3, manager4]
         data['fees'] = self.get_argument('fees')
         data['numberOfParticipants'] = self.get_argument('participants')
         data['name'] = str(data['name']).replace(' ', '-')
         db_name = self.get_argument('type')
         db = couch.BlockingCouch(db_name,
                                  "http://*****:*****@127.0.0.1:5984")
         db.save_doc(data)
         self.redirect(url + '/api/registration/events')
     except Exception as error:
         print(error)
         self.send_error(400)
Ejemplo n.º 2
0
    def get(self, *args, **kwargs):
        try:
            # We must have a secure connection.
            if not (self.request.protocol == "https" or
                    self.request.headers.get("x-forwarded-proto") == "https"):
                raise tornado.web.HTTPError(
                    403, reason="Secure connection required.")

            # We must have a session cookie.
            if self.get_cookie("slycatauth", None) is None:
                raise tornado.web.HTTPError(403, reason="No session.")

            # Validate the session cookie.
            sid = self.get_cookie("slycatauth")
            database = couch.BlockingCouch("slycat")
            session = database.get_doc(sid)
            log.error(
                "current session is at %s seconds ::: session expires at %s seconds,  is current session expired? %s"
                % ((datetime.datetime.utcnow() - datetime.datetime.strptime(
                    session["created"],
                    "%Y-%m-%dT%H:%M:%S.%f")).total_seconds(),
                   configuration["slycat"]["session-timeout"].total_seconds(),
                   (datetime.datetime.utcnow() - datetime.datetime.strptime(
                       session["created"],
                       "%Y-%m-%dT%H:%M:%S.%f")).total_seconds() >
                   configuration["slycat"]["session-timeout"].total_seconds()))
            if (datetime.datetime.utcnow() - datetime.datetime.strptime(
                    session["created"], "%Y-%m-%dT%H:%M:%S.%f")
                ).total_seconds(
                ) > configuration["slycat"]["session-timeout"].total_seconds():
                raise tornado.web.HTTPError(403, reason="Session expired.")

            self.user = session["creator"]
            self.projects = set()

            # OK, proceed to upgrade the connection to a websocket.
            tornado.websocket.WebSocketHandler.get(self, *args, **kwargs)
        except tornado.web.HTTPError as e:
            self.set_status(e.status, e.reason)
        except couch.NotFound:
            raise tornado.web.HTTPError(
                404,
                reason=
                "Session not found, could be expired, authorization required.")
        except Exception as e:
            raise

        timestamp = datetime.datetime.utcnow().strftime("%d/%b/%Y:%H:%M:%S")
        log.access(
            "%s - %s [%s] \"%s %s %s\" %s - \"%s\"" %
            (self.request.remote_ip, self.user, timestamp, self.request.method,
             self.request.uri, self.request.version, self.get_status(),
             self.request.headers.get("user-agent")))
Ejemplo n.º 3
0
def create_db(dbname, db_uri):
    """
    Create a database
    :param dbname: name of the database
    :param db_uri: uri of couch db
    """
    couchdb = couch.BlockingCouch(dbname, db_uri)
    list_of_dbs = couchdb.list_dbs()
    if dbname not in list_of_dbs:
        couchdb.create_db(db_name=dbname)
        print "Database '{}' created".format(dbname)
    else:
        print "Database '{}' already exists.  Not creating".format(dbname)
Ejemplo n.º 4
0
def load_docs(dbname, docs, db_uri):
    """
    save documents to a given database
    :param dbname: name of the database
    :param docs: a list of dictionaries representing the documents
    :param db_uri: uri of couch db
    """
    couchdb = couch.BlockingCouch(dbname, db_uri)
    try:
        couchdb.save_docs(docs)
    except couch.CouchException as exc:
        # http status code CREATED
        if exc.code == 201:
            print '\tdocs already exist'
        else:
            raise
    else:
        print '\tdocs successfully loaded'
Ejemplo n.º 5
0
def run_blocking_tests():
    # set up tests
    doc1 = {'msg': 'Test doc 1'}
    doc2 = {'msg': 'Test doc 2'}
    doc3 = {'value': float('nan')}

    db = couch.BlockingCouch(dbname1)
    db2 = couch.BlockingCouch(dbname2)

    try:
        db.delete_db()
    except couch.NotFound:
        pass
    try:
        db2.delete_db()
    except couch.NotFound:
        pass

    # create database
    resp = db.create_db()
    assert 'ok' in resp, 'Failed to create database'

    # list databases
    resp = db.list_dbs()
    assert db.db_name in resp, 'Database not in list of databases'

    # info_db
    resp = db.info_db()
    assert ('db_name' in resp) and (resp['db_name'] == db.db_name), \
        'No database info'

    # uuids
    resp = db.uuids()
    assert re.match('[0-9a-f]{32}', resp[0]), 'Failed to get uuid'

    # save doc
    resp = db.save_doc(doc1)
    assert ('rev' in resp) and ('id' in resp), 'Failed to save doc'
    doc1.update({'_id': resp['id'], '_rev': resp['rev']})

    # save doc with wrong rev number
    try:
        db.save_doc({'_id': doc1['_id'], '_rev': 'a'})
        raise AssertionError('No error when overwriting doc with wrong rev')
    except couch.CouchException:
        pass

    # has doc
    resp = db.has_doc(doc1['_id'])
    assert resp, "Failed on getting head of doc"

    # has doc on non-existing doc
    resp = db.has_doc('a')
    assert not resp, "Failed on getting head of non-existing doc"

    # get doc
    resp = db.get_doc(doc1['_id'])
    assert doc1 == resp, 'Failed to get doc'

    # get non-existing doc
    try:
        resp = db.get_doc('a')
        raise AssertionError('No error on request for unexisting doc')
    except couch.NotFound:
        pass

    # save docs
    doc1['msg2'] = 'Another message'
    resp = db.save_docs([doc1, doc2])
    assert all('rev' in item and 'id' in item for item in resp), \
        'Failed to save docs'
    doc1['_rev'] = resp[0]['rev']
    doc2.update({'_id': resp[1]['id'], '_rev': resp[1]['rev']})

    # get docs
    resp = db.get_docs([doc1['_id'], doc2['_id']])
    assert [doc1, doc2] == resp, 'Failed to get docs'

    # get non-existing docs
    try:
        resp = db.get_docs(['a', 'b'])
    except couch.NotFound:
        pass
    else:
        raise AssertionError('No error on request for unexisting docs')

    # list docs
    resp = db.view_all_docs(include_docs=True)
    assert {doc1['_id']: doc1['_rev'], doc2['_id']: doc2['_rev']} == \
        dict((row['doc']['_id'], row['doc']['_rev'])
             for row in resp['rows']), 'Failed listing all docs'

    # pull database
    resp = db2.pull_db(dbname1, create_target=True)
    assert 'ok' in resp, 'Replication failed'
    assert dbname2 in db2.list_dbs(), \
        'Replication failed, new database replication not found'

    # delete docs
    resp = db2.delete_docs([doc1, doc2])
    assert resp[0]['id'] == doc1['_id'] and resp[1]['id'] == doc2['_id'], \
        'Failed to delete docs'
    assert len(db2.view_all_docs()['rows']) == 0, \
        'Failed to delete docs, database not empty'

    # delete database
    resp = db2.delete_db()
    assert 'ok' in resp, 'Failed to delete database'

    # upload design doc
    design = {
        '_id': '_design/test',
        'views': {
            'msg': {
                'map':
                'function(doc) { if (doc.msg) { '
                'emit(doc._id, doc.msg); } }'
            }
        }
    }
    resp = db.save_doc(design)
    assert 'ok' in resp, 'Failed to upload design doc'
    design['_rev'] = resp['rev']

    # view
    resp = db.view('test', 'msg')
    assert [doc1['_id'], doc2['_id']] == \
        [row['key'] for row in resp['rows']], \
        'Failed to get view results from design doc'

    # delete doc
    resp = db.delete_doc(doc2)
    assert resp['id'] == doc2['_id'], 'Failed to delete doc2'

    # save attachment
    data = {'msg3': 'This is a test'}
    attachment = {
        'mimetype': 'application/json',
        'name': 'test attachment',
        'data': json.dumps(data)
    }
    resp = db.save_attachment(doc1, attachment)
    assert 'ok' in resp, 'Attachment not saved'
    doc1['_rev'] = resp['rev']

    # get attachment
    resp = db.get_attachment(doc1, attachment['name'], attachment['mimetype'])
    assert json.loads(resp.decode('utf8')) == data, 'Attachment not loaded'

    # delete attachment
    resp = db.delete_attachment(doc1, attachment['name'])
    assert 'ok' in resp, 'Attachment not deleted'
    doc1['_rev'] = resp['rev']

    # put invalid doc
    try:
        db.save_doc(doc3)
    except ValueError:
        pass
    else:
        raise AssertionError('No error on doc containing NaN')

    # done testing, delete test db
    db.delete_db()

    print('All blocking tests passed')