def channel_data(self, channel_num):
     """
     Pull the latest measurement data for the specified channel.
     """
     try:
         limit = int(request.query.get('limit', 250))
         if limit < 1:
             raise ValueError()
     except ValueError:
         return Response(body=json_dumps(
             {'error': 'Invalid Limit Value! Must be a positive integer.'}),
                         type='application/json',
                         status=400)
     else:
         return Response(body=json_dumps({
             'data': [
                 m.to_api_response() for m in reversed(
                     select_latest_channel_measurements(
                         self.db_conn, channel_num, limit=limit))
             ],
             'stationCountData':
             list(
                 reversed(
                     select_latest_channel_device_counts(self.db_conn,
                                                         channel_num,
                                                         limit=limit)))
         }),
                         type='application/json',
                         status=200)
Ejemplo n.º 2
0
def query():
    dic = urllib.parse.parse_qs(request.query_string)
    start_date = None
    end_date = None
    
    for key in dic:
        if key == 's':
            start_date = ''.join(dic[key])
        if key == 'e':
            end_date = ''.join(dic[key])
    
    results = None
    
    print('fetching data')
    try:
        if start_date is None:
            start_date = '2014-6-05T08:00:00Z'
        
        if end_date is None:
            end_date = '2014-6-09T23:59:00Z'
            
        results = dataManager.collect_range_comm(start_date, end_date)
    except:
        print(traceback.format_exc())
        print("parse error")
        return json_dumps([]);
    
    print('fetching done')
    response.content_type = 'application/json'
    return json_dumps(results, indent=2)
Ejemplo n.º 3
0
def add_value():
    customer_id = request.json.get('customer')
    typ_id = request.json.get('type')
    field_id = request.json.get('field')
    field_value = request.json.get('value')
    if customer_id and typ_id and field_id and field_value:
        try:
            with db_session:
                customer = Customer.get(cstm_id=customer_id)
                if customer:
                    typ = Type.get(typ_id=typ_id, typ_cstm_id=customer)
                    if typ:
                        fld_id = Field.get(fld_id=field_id, fld_typ_id=typ)
                        if fld_id:
                            FieldValue(fdvl_value=field_value,
                                       fdvl_fld_id=fld_id,
                                       fdvl_typ_id=typ)
                        return json_dumps({'status': True})
        except TransactionIntegrityError as e_addCustomer:
            return json_dumps({'status': False, 'error': str(e_addCustomer)})
        except CacheIndexError as e_CacheIndexError:
            return json_dumps({
                'status': False,
                'error': str(e_CacheIndexError)
            })
        except BaseException as e_BaseException:
            return json_dumps({'status': False, 'error': str(e_BaseException)})
    else:
        return json_dumps({'status': False})
Ejemplo n.º 4
0
def web_service_tests(test_id):
    suppress_error = bottle.request.GET.get('suppress_error') == "true"
    storage = core.docvert_storage.storage_memory_based()
    error_message = None
    if suppress_error:
        try:
            core.docvert.process_pipeline(None, test_id, "tests", None,
                                          storage)
        except Exception as exception:
            bottle.response.content_type = "text/plain"
            class_name = "%s" % type(exception).__name__
            return bottle.json_dumps([{
                "status":
                "fail",
                "message":
                "Unable to run tests due to exception. <%s> %s" %
                (class_name, exception)
            }])
    else:
        try:
            core.docvert.process_pipeline(None, test_id, "tests", None,
                                          storage)
        except (core.docvert_exception.debug_exception,
                core.docvert_exception.debug_xml_exception) as exception:
            bottle.response.content_type = exception.content_type
            return exception.data
    return bottle.json_dumps(storage.tests)
 def test_json_forged_header_issue616(self):
     test = dict(a=5, b='test', c=[1,2,3])
     e = {'CONTENT_TYPE': 'text/plain;application/json'}
     wsgiref.util.setup_testing_defaults(e)
     e['wsgi.input'].write(tob(json_dumps(test)))
     e['wsgi.input'].seek(0)
     e['CONTENT_LENGTH'] = str(len(json_dumps(test)))
     self.assertEqual(BaseRequest(e).json, None)
Ejemplo n.º 6
0
 def test_json_forged_header_issue616(self):
     test = dict(a=5, b='test', c=[1, 2, 3])
     e = {'CONTENT_TYPE': 'text/plain;application/json'}
     wsgiref.util.setup_testing_defaults(e)
     e['wsgi.input'].write(tob(json_dumps(test)))
     e['wsgi.input'].seek(0)
     e['CONTENT_LENGTH'] = str(len(json_dumps(test)))
     self.assertEqual(BaseRequest(e).json, None)
Ejemplo n.º 7
0
 def test_json_tobig(self):
     """ Environ: Request.json property with huge body. """
     test = dict(a=5, tobig='x' * bottle.BaseRequest.MEMFILE_MAX)
     e = {'CONTENT_TYPE': 'application/json'}
     wsgiref.util.setup_testing_defaults(e)
     e['wsgi.input'].write(tob(json_dumps(test)))
     e['wsgi.input'].seek(0)
     e['CONTENT_LENGTH'] = str(len(json_dumps(test)))
     self.assertEqual(BaseRequest(e).json, None)
Ejemplo n.º 8
0
 def test_json_noheader(self):
     """ Environ: Request.json property with missing content-type header. """
     test = dict(a=5, b='test', c=[1, 2, 3])
     e = {}
     wsgiref.util.setup_testing_defaults(e)
     e['wsgi.input'].write(tob(json_dumps(test)))
     e['wsgi.input'].seek(0)
     e['CONTENT_LENGTH'] = str(len(json_dumps(test)))
     self.assertEqual(BaseRequest(e).json, None)
 def test_json_noheader(self):
     """ Environ: Request.json property with missing content-type header. """
     test = dict(a=5, b='test', c=[1,2,3])
     e = {}
     wsgiref.util.setup_testing_defaults(e)
     e['wsgi.input'].write(tob(json_dumps(test)))
     e['wsgi.input'].seek(0)
     e['CONTENT_LENGTH'] = str(len(json_dumps(test)))
     self.assertEqual(BaseRequest(e).json, None)
Ejemplo n.º 10
0
 def test_json_valid(self):
     """ Environ: Request.json property. """
     test = dict(a=5, b='test', c=[1, 2, 3])
     e = {'CONTENT_TYPE': 'application/json; charset=UTF-8'}
     wsgiref.util.setup_testing_defaults(e)
     e['wsgi.input'].write(tob(json_dumps(test)))
     e['wsgi.input'].seek(0)
     e['CONTENT_LENGTH'] = str(len(json_dumps(test)))
     self.assertEqual(BaseRequest(e).json, test)
 def test_json_tobig(self):
     """ Environ: Request.json property with huge body. """
     test = dict(a=5, tobig='x' * bottle.BaseRequest.MEMFILE_MAX)
     e = {'CONTENT_TYPE': 'application/json'}
     wsgiref.util.setup_testing_defaults(e)
     e['wsgi.input'].write(tob(json_dumps(test)))
     e['wsgi.input'].seek(0)
     e['CONTENT_LENGTH'] = str(len(json_dumps(test)))
     self.assertRaises(HTTPError, lambda: BaseRequest(e).json)
 def test_json_valid(self):
     """ Environ: Request.json property. """
     test = dict(a=5, b='test', c=[1,2,3])
     e = {'CONTENT_TYPE': 'application/json; charset=UTF-8'}
     wsgiref.util.setup_testing_defaults(e)
     e['wsgi.input'].write(tob(json_dumps(test)))
     e['wsgi.input'].seek(0)
     e['CONTENT_LENGTH'] = str(len(json_dumps(test)))
     self.assertEqual(BaseRequest(e).json, test)
Ejemplo n.º 13
0
def query():
    dic = urllib.parse.parse_qs(request.query_string)
    
    start_date = ''
    end_date = ''
    from_id = None
    to_id = None
    loc = None
    
    for key in dic:
        if key == 's':
            start_date = ''.join(dic[key])
        if key == 'e':
            end_date = ''.join(dic[key])
        if key == 'loc':
            loc = ''.join(dic[key])
        if key == 'id1':
            to_id = ''.join(dic[key])
        if key == 'id2':
            from_id = ''.join(dic[key])
            
    results = None
    
    print('fetching data')
    try:
#     s_converted = TimeFunc.time_func_solr_date_to_python_date('2014-6-06T08:00:00Z')
#     e_converted = TimeFunc.time_func_solr_date_to_python_date('2014-6-08T23:59:00Z')
        if start_date is None:
            start_date = '2014-6-05T08:00:00Z'
        
        if end_date is None:
            end_date = '2014-6-09T23:59:00Z'
            
        if from_id is None or to_id is None or from_id is '*' or to_id is '*':
            raise ValueError('invalid id1 or id2')
        
        if loc is None:
            loc = '*'
            
        start_date = '2014-6-05T08:00:00Z'
        end_date = '2014-6-09T23:59:00Z'
    
        results = solr.queryCommunication(from_id, to_id, start_date, end_date, loc)
    
    except ValueError as err:
        print("wildcard passed")
        response.status = 400
        return err.args
    
    except:
        print(traceback.format_exc())
        print("parse error")
        return json_dumps([])
    
    print('fetching done')
    response.content_type = 'application/json'
    return json_dumps(results, indent=2)
Ejemplo n.º 14
0
 def test_json_tobig(self):
     """ Environ: Request.json property with huge body. """
     test = dict(a=5, tobig="x" * bottle.BaseRequest.MEMFILE_MAX)
     e = {"CONTENT_TYPE": "application/json"}
     wsgiref.util.setup_testing_defaults(e)
     e["wsgi.input"].write(tob(json_dumps(test)))
     e["wsgi.input"].seek(0)
     e["CONTENT_LENGTH"] = str(len(json_dumps(test)))
     self.assertEqual(BaseRequest(e).json, None)
Ejemplo n.º 15
0
    def test_json_plugin_catches_httpresponse(self):
        @self.app.get('/return')
        def _():
            return HTTPResponse({'test': 'ko'}, 402)
        @self.app.get('/raise')
        def _():
            raise HTTPResponse({'test': 'ko2'}, 402)

        self.assertBody(json_dumps({'test': 'ko'}), '/return')
        self.assertBody(json_dumps({'test': 'ko2'}), '/raise')
Ejemplo n.º 16
0
 def __callback_to_response(self, callback_name: str):
     may_callback = getattr(self, callback_name)
     if hasattr(may_callback, "__map__"):
         try:
             try:
                 return json_dumps(may_callback(request.json))
             except:
                 return json_dumps(may_callback())
         except:
             return json_dumps("")
Ejemplo n.º 17
0
def query():
    dic = urllib.parse.parse_qs(request.query_string)
    
    start_date = None
    end_date = None
    id = None
    type = None
    
    for key in dic:
        if key == 's':
            start_date = ''.join(dic[key])
        if key == 'e':
            end_date = ''.join(dic[key])
        if key == 'id':
            id = ''.join(dic[key])
        if key == 'type':
            type = ''.join(dic[key])
        
    results = None
    
    print('fetching data')
    try:

        if start_date is None:
            start_date = '2014-6-05T08:00:00Z'
        
        if end_date is None:
            end_date = '2014-6-09T23:59:00Z'
                   
        if id is None or id is '*':
            raise ValueError('You must specify an id')
        
        if type is None:
            type = '*'
        
        if type is '1':
            type = 'true'
        elif type is '0':
            type = 'false'
            
        results = solr.queryTrajectory(id, start_date, end_date, type)
        
    except ValueError as err:
        print("wildcard passed")
        response.status = 400
        return err.args
    
    except:
        print(traceback.format_exc())
        print("parse error")
        return json_dumps([]);
    
    print('fetching done')
    response.content_type = 'application/json'
    return json_dumps(results, indent=2)
Ejemplo n.º 18
0
    def test_json_plugin_catches_httpresponse(self):
        @self.app.get('/return')
        def _():
            return HTTPResponse({'test': 'ko'}, 402)

        @self.app.get('/raise')
        def _():
            raise HTTPResponse({'test': 'ko2'}, 402)

        self.assertBody(json_dumps({'test': 'ko'}), '/return')
        self.assertBody(json_dumps({'test': 'ko2'}), '/raise')
Ejemplo n.º 19
0
 def _validate_this(self, callback, route, *args, **kwargs):
     if not route.rule.startswith(self.openapi_base_path):
         return callback(*args, **kwargs)
     elif self.serve_openapi_schema and route.rule == self.openapi_schema_url:
         return callback(*args, **kwargs)
     elif self.serve_swagger_ui and route.rule.startswith(self.swagger_ui_base_url):
         return callback(*args, **kwargs)
     else:
         try:
             openapi_request = _bottle_request_to_openapi_request(request)
             if self.validate_requests:
                 request_validation_result = self.request_validator.validate(openapi_request)
             else:
                 request_validation_result = None
             if not self.validate_requests or not request_validation_result.errors:
                 request.openapi_request = openapi_request
                 result = callback(*args, **kwargs)
                 if self.auto_jsonify and isinstance(result, (dict, list)):
                     response.body = result = json_dumps(result)
                     response.content_type = 'application/json'
                     openapi_response = _bottle_response_to_openapi_response(response)
                 elif self.auto_jsonify and isinstance(result, HTTPResponse):
                     result.body = json_dumps(result.body)
                     response.content_type = result.content_type = 'application/json'
                     openapi_response = _bottle_response_to_openapi_response(result)
                 elif isinstance(result, HTTPResponse):
                     openapi_response = _bottle_response_to_openapi_response(result)
                 else:
                     response.body = result
                     openapi_response = _bottle_response_to_openapi_response(response)
                 if self.validate_responses:
                     response_validation_result = self.response_validator.validate(openapi_request, openapi_response)
                 else:
                     response_validation_result = None
                 if not self.validate_responses or not response_validation_result.errors:
                     return result
                 else:
                     return self.response_error_handler(
                         request,
                         result if isinstance(result, Response) else response,
                         response_validation_result
                     )
             else:
                 return self.request_error_handler(request, request_validation_result)
         except Exception as e:
             # Should we attempt to validate an HTTP response that was raised?
             if isinstance(e, HTTPResponse):
                 raise e
             return self.exception_handler(request, e)
         finally:
             request.openapi_request = None
Ejemplo n.º 20
0
    def _swagger_validate(self, callback, route, *args, **kwargs):
        swagger_op = self._swagger_op(route)

        if not swagger_op:
            if self.serve_swagger_schema and route.rule == self.swagger_schema_url:
                return callback(*args, **kwargs)
            elif self.serve_swagger_ui and route.rule.startswith(
                    self.swagger_ui_base_url):
                return callback(*args, **kwargs)
            elif not route.rule.startswith(
                    self.swagger_base_path) or self.ignore_undefined_routes:
                return callback(*args, **kwargs)
            else:
                return self.swagger_op_not_found_handler(route)

        try:
            request.swagger_op = swagger_op

            try:
                request.swagger_data = self._validate_request(
                    swagger_op,
                    ignore_security_definitions=self.
                    ignore_security_definitions)
            except SwaggerSecurityValidationError as e:
                return self.invalid_security_handler(e)
            except ValidationError as e:
                return self.invalid_request_handler(e)

            result = callback(*args, **kwargs)
            result_payload = result.body if isinstance(
                result, HTTPResponse) else result

            try:
                self._validate_response(swagger_op, result_payload)
            except (ValidationError, MatchingResponseNotFound) as e:
                return self.invalid_response_handler(e)

            if self.auto_jsonify and isinstance(result, (dict, list)):
                result = json_dumps(result)
                response.content_type = 'application/json'
            elif self.auto_jsonify and isinstance(result, HTTPResponse):
                result.body = json_dumps(result_payload)
                response.content_type = result.content_type = 'application/json'
        except Exception as e:
            # Bottle handles redirects by raising an HTTPResponse instance
            if isinstance(e, HTTPResponse):
                raise e

            return self.exception_handler(e)

        return result
Ejemplo n.º 21
0
def query():
    print('requested')
    dic = urllib.parse.parse_qs(request.query_string)
    
    start_date = None
    end_date = None
    
    for key in dic:
        if key == 's':
            start_date = ''.join(dic[key])
        if key == 'e':
            end_date = ''.join(dic[key])
        
    results = None
    
    print('fetching data')
    try:

        if start_date is None:
            start_date = '2014-6-05T08:00:00Z'
        
        if end_date is None:
            end_date = '2014-6-09T23:59:00Z'

        date_str = None
        
        if start_date.startswith("2014-06-06"):
            date_str = "friday"
        elif start_date.startswith("2014-06-07"):
            date_str = "saturday"
        elif start_date.startswith("2014-06-08"):
            date_str = "sunday"
        
        rst = solr.query_traj_checkin_kde(start_date, end_date)
        results = kmeans.kmeans(date_str, rst)
        
    except ValueError as err:
        print("wildcard passed")
        response.status = 400
        return err.args
    
    except:
        print(traceback.format_exc())
        print("parse error")
        return json_dumps([]);
    
    print('fetching done')
    response.content_type = 'application/json'
    return json_dumps(results, indent=2)
Ejemplo n.º 22
0
def multiple():
    P = get_info_object()
    q = request.POST.get('q','')
    nodes = q.split()
    enabled_plugins = []
    if q:
        enabled_plugins = request.POST.getall("plugins")
    all_plugins = P.plugins
    return {"q": q,
            "nodes": nodes,
            "plugins": all_plugins,
            "nodes_js": json_dumps(nodes),
            "plugins_js": json_dumps(enabled_plugins),
            "enabled_plugins": enabled_plugins
            }
Ejemplo n.º 23
0
def query():
    dic = urllib.parse.parse_qs(request.query_string)
    start_date = None
    end_date = None
    t = None
    
    for key in dic:
        if key == 's':
            start_date = ''.join(dic[key])
        if key == 'e':
            end_date = ''.join(dic[key])
        if key == 'type':
            t = ''.join(dic[key])
            
    results = None
    
    print('fetching data')
    try:
        if start_date is None:
            raise ValueError('You must specify start date')
        
        if end_date is None:
            raise ValueError('You must specify end date')
        
        if t is None:
            raise ValueError('You must specify movement type')
        
        rst = dataManager.collect_range_traj_locations(start_date, end_date, t)
        print("Saw {0} result(s).".format(len(rst)))
        print("...kde initializing")
        results = kde.KDE(rst,0,102,0,102)
        print("kde done...")
        results = results.tolist()
            
    except ValueError as err:
        print("wrong parameters passed")
        response.status = 400
        return err.args
    
    except:
        
        print("parse error")
        print(traceback.format_exc())
        return json_dumps([])
    
    print('fetching done')
    response.content_type = 'application/json'
    return json_dumps(results, indent=2)
Ejemplo n.º 24
0
def json_error_handler(res):
    if res.content_type == 'application/json':
        return res.body
    res.content_type = 'application/json'
    if res.body == 'Unknown Error.':
        res.body = bottle.HTTP_CODES[res.status_code]
    return bottle.json_dumps({'error': res.body})
Ejemplo n.º 25
0
def find(card_list_id: str):
    session.rollback()
    result = query_helper.find_by_id(session,
                                     CardList,
                                     card_list_id,
                                     json_result=True)
    return json_dumps(model_helper.insert_field_objects(session, result))
Ejemplo n.º 26
0
def inserir_peer():
    global db

    if not request.json:
        return json_dumps({'erro': 'requisição inválida'})
    elif 'porta' in request.json and type(request.json['porta']) != int:
        return json_dumps({'erro': 'requisição inválida'})

    db.evento(
        "peer", "insert",
        **dict(ip=request.remote_addr,
               porta=request.json['porta'],
               tempo='{}:{}'.format(request.remote_addr,
                                    request.json['porta'])))

    return json_dumps({'sucesso': 'cadastrado com sucesso'})
Ejemplo n.º 27
0
def post():
    if bottle.request.is_ajax:
        section = bottle.request.forms.get("section")
        startfrom = int(bottle.request.forms.get("startfrom"))
        data = list()
        if section == 'all':
            with dbutils.dbopen() as db:
                allusers = users.get(0, count=slice(startfrom, USERS_PER_PAGE), dbconnection=db)
                page = pages.PageBuilder('user_row')
                if pages.auth.loggedin():
                    if len(pages.auth.current().friends()) > 0:
                        friends = pages.auth.current().friends(True)
                        page.add_param('myfriends', friends)
                for user in allusers:
                    page.add_param('user', user)
                    user_tpl = page.template()
                    data.append(user_tpl)
                return bottle.json_dumps(data)
        return ''
    else:
        if 'search' in bottle.request.forms:
            query = bottle.request.forms.get('q')
            with dbutils.dbopen() as db:
                allusers = users.search(query, dbconnection=db)
                page = pages.PageBuilder('users', allusers=users.get(allusers, dbconnection=db),
                                         count=len(allusers),
                                         search=True, search_q=bottle.request.forms.get('q'))
                if pages.auth.loggedin() and len(pages.auth.current().friends()) > 0:
                    friends = pages.auth.current().friends(True)
                    page.add_param('myfriends', friends)
                return page
Ejemplo n.º 28
0
 def write(self):
     try:
         with open(self.filename, mode='w') as fp:
             json = json_dumps(self.data, indent=4)
             fp.write(json)
     except Exception as ex:
         logger.error("Failed writing config file: " + str(ex))
Ejemplo n.º 29
0
def json_error_handler(res):
    if res.content_type == "application/json":
        return res.body
    res.content_type = "application/json"
    if res.body == "Unknown Error.":
        res.body = bottle.HTTP_CODES[res.status_code]
    return bottle.json_dumps({"error": res.body})
Ejemplo n.º 30
0
 def test_json(self):
     self.app.route('/')(lambda: {'a': 1})
     if bottle.json_dumps:
         self.assertBody(bottle.json_dumps({'a': 1}))
         self.assertHeader('Content-Type', 'application/json')
     else:
         print "Warning: No json module installed."
Ejemplo n.º 31
0
def makeJSONP(callback, data):
    # wraps the data in callback to prep it for JSONP response
    response_data = callback
    response_data += '('
    response_data += bottle.json_dumps(data)
    response_data += ');'
    return response_data
Ejemplo n.º 32
0
 def test_json(self):
     self.app.route('/')(lambda: {'a': 1})
     try:
         self.assertBody(bottle.json_dumps({'a': 1}))
         self.assertHeader('Content-Type','application/json')
     except ImportError:
         warn("Skipping JSON tests.")
Ejemplo n.º 33
0
 def test_json(self):
     self.app.route('/')(lambda: {'a': 1})
     if bottle.json_dumps:
         self.assertBody(bottle.json_dumps({'a': 1}))
         self.assertHeader('Content-Type','application/json')
     else:
         print "Warning: No json module installed."
def query():
    """
    given {start_time, end_time, grid_id [optional]}
    return -> [{grid_id, volume}, ...]
    """
    start_time = datetime.strptime(request.query.get('start_time'), '%Y-%m-%dT%H:%M:%SZ')
    end_time = datetime.strptime(request.query.get('end_time'), '%Y-%m-%dT%H:%M:%SZ')
    grid_id = request.query.get('grid_id')

    mg = MongoDB()
    mg.connect()

    print('querying grid volumes...')

#     if grid_id:
#         results = mg.group_by([{'$match': {'created_at': {'$gt': start_time, '$lt': end_time}, 'grid_id': grid_id}},
#                                {'$group': {'_id': '$grid_id', 'count': {'$sum': 1}}}
#                                ])
#     else:
#         results = mg.group_by([{'$match': {'created_at': {'$gt': start_time, '$lt': end_time}}},
#                                {'$group': {'_id': '$grid_id', 'count': {'$sum': 1}}}
#                                ])
#    group and count distinct user:
    results = mg.group_by([ {'$match': {'created_at': {'$gt': start_time, '$lt': end_time}}},
                            {'$group': {'_id':{ 'grid_id':'$grid_id', 'user_id':'$user_id' }, 'count': {'$sum': 1} } },
                            {'$group': {'_id': '$_id.grid_id', 'count': {'$sum': 1}}}
                          ])

    ret = []
    for result in results:
        ret.append({'grid_id': result['_id'], 'volume': result['count']})

    response.content_type = 'application/json'
    return json_dumps(ret, indent=2)
Ejemplo n.º 35
0
def value():
    zeit = grap.grap_zeit()
    flow = grap.grap_flow()

    print(zeit)
    print(flow)
    return json_dumps({'data': flow, 'labels': zeit})
Ejemplo n.º 36
0
def find(board_user_id: str):
    session.rollback()
    result = query_helper.find_by_id(session,
                                     BoardUser,
                                     board_user_id,
                                     json_result=True)
    return json_dumps(model_helper.insert_field_objects(session, result))
def kv_store_set(transaction, key_name, value):
    assert isinstance(key_name, str)
    with cursor_manager(transaction) as c:
        c.execute(
            """
            REPLACE INTO keyValueStore(keyName, value) VALUES(?, ?)
            """, (key_name, json_dumps(value)))
Ejemplo n.º 38
0
def update(board_user_id: str, ver: str):
    session.rollback()
    data = deepcopy(request.data)
    data.update({"updated_by_id": request.user["id"]})
    old_data = query_helper.find_by_params(session,
                                           BoardUser, [{
                                               "id": {
                                                   "$eq": board_user_id
                                               }
                                           }, {
                                               "ver": {
                                                   "$eq": ver
                                               }
                                           }],
                                           json_result=True)
    result = query_helper.update_by_params(session,
                                           BoardUser, [{
                                               "id": {
                                                   "$eq": board_user_id
                                               }
                                           }, {
                                               "ver": {
                                                   "$eq": ver
                                               }
                                           }],
                                           data,
                                           json_result=True)
    log_helper.log_update(session, BoardUser, request.user["id"], result,
                          old_data)
    session.commit()
    return json_dumps(model_helper.insert_field_objects(session, result))
Ejemplo n.º 39
0
def delete(user_id: str, ver: str):
    session.rollback()
    old_data = query_helper.find_by_params(session,
                                           User, [{
                                               "id": {
                                                   "$eq": user_id
                                               }
                                           }, {
                                               "ver": {
                                                   "$eq": ver
                                               }
                                           }],
                                           json_result=True)
    result = query_helper.delete_by_params(
        session,
        User, [{
            "id": {
                "$eq": user_id
            }
        }, {
            "ver": {
                "$eq": ver
            }
        }], {'deleted_by_id': request.user['id']},
        json_result=True)
    log_helper.log_update(session, User, request.user["id"], result, old_data)
    session.commit()
    return json_dumps(model_helper.insert_field_objects(session, result))
Ejemplo n.º 40
0
 def test_json(self):
     self.app.route('/')(lambda: {'a': 1})
     try:
         self.assertBody(bottle.json_dumps({'a': 1}))
         self.assertHeader('Content-Type','application/json')
     except ImportError:
         warn("Skipping JSON tests.")
Ejemplo n.º 41
0
def get_type():
    typ_list = []
    customer = request.query.get('customer')
    if customer:
        customer_id = Customer.get(cstm_id=customer)
        for typ in Type.select(lambda f: f.typ_cstm_id == customer_id):
            typ_list.append({'typ_id': typ.typ_id, "typ_name": typ.typ_name})
        return json_dumps({'getType': typ_list})
Ejemplo n.º 42
0
def count():
    session.rollback()
    return json_dumps(
        query_helper.count(
            session, Board,
            request.pagination.get("filters", [])
        )
    )
Ejemplo n.º 43
0
def get_customer():
    customer_list = []
    for customer in Customer.select():
        customer_list.append({
            'customer_id': customer.cstm_id,
            "customer_name": customer.cstm_name
        })
    return json_dumps({'getCustomer': customer_list})
Ejemplo n.º 44
0
def log(card_id: str):
    session.rollback()
    return json_dumps(
        query_helper.list_query(
            session, CardLog, [{"entity_id": {"$eq": card_id}}],
            json_result=True
        )
    )
Ejemplo n.º 45
0
def inserir_produto():
    global db

    if not request.json:
        return json_dumps({'erro': 'requisição inválida'})
    elif 'nome' in request.json and type(request.json['nome']) != str:
        return json_dumps({'erro': 'requisição inválida'})
    elif 'qtde' in request.json and type(request.json['qtde']) != int:
        return json_dumps({'erro': 'requisição inválida'})

    db.evento(
        "produto", "insert",
        **dict(seller=request.remote_addr,
               nome=request.json['nome'],
               qtde=request.json['qtde']))

    return json_dumps({'sucesso': 'cadastrado com sucesso'})
Ejemplo n.º 46
0
def create():
    session.rollback()
    data = deepcopy(request.data)
    data.update({"created_by_id": request.user["id"]})
    result = query_helper.save(session, BoardUser, data, json_result=True)
    log_helper.log_insert(session, BoardUser, request.user["id"], result)
    session.commit()
    return json_dumps(model_helper.insert_field_objects(session, result))
Ejemplo n.º 47
0
def atualiza_produto(id_produto):
    global db

    if not request.json:
        return json_dumps({'erro': 'requisição inválida'})
    elif id_produto not in db.select_produto():
        return json_dumps({'erro': 'produto não existe'})
    elif 'nome' in request.json and type(request.json['nome']) != str:
        return json_dumps({'erro': 'requisição inválida'})
    elif 'qtde' in request.json and type(request.json['qtde']) != int:
        return json_dumps({'erro': 'requisição inválida'})

    db.evento(
        "produto", "update",
        **dict(nome=request.json.get('nome'), qtde=request.json.get('qtde')))

    return json_dumps({'sucesso': 'atualizado com sucesso'})
Ejemplo n.º 48
0
def web_service_tests(test_id):
    suppress_error = bottle.request.GET.get('suppress_error') == "true"
    storage = core.docvert_storage.storage_memory_based()
    error_message = None
    if suppress_error:
        try:
            core.docvert.process_pipeline(None, test_id, "tests", None, storage)
        except Exception as exception:
            bottle.response.content_type = "text/plain"
            class_name = "%s" % type(exception).__name__
            return bottle.json_dumps([{"status":"fail", "message": "Unable to run tests due to exception. <%s> %s" % (class_name, exception)}])
    else:
        try:
            core.docvert.process_pipeline(None, test_id, "tests", None, storage)
        except (core.docvert_exception.debug_exception, core.docvert_exception.debug_xml_exception) as exception:
            bottle.response.content_type = exception.content_type
            return exception.data
    return bottle.json_dumps(storage.tests)
Ejemplo n.º 49
0
def index():
    session.rollback()
    results = query_helper.list_query(session,
                                      BoardUser,
                                      request.pagination.get("filters", []),
                                      request.pagination,
                                      json_result=True)
    return json_dumps(
        [model_helper.insert_field_objects(session, row) for row in results])
Ejemplo n.º 50
0
def makeJSONP(callback, data):
    """ wraps the data in callback to prep it for JSONP response

        borrowed/stolen from https://github.com/foxbunny/HTTPy-RPC/blob/master/app.py
    """
    response_data = callback
    response_data += '('
    response_data += json_dumps(data)
    response_data += ');'
    return response_data
Ejemplo n.º 51
0
def push():
    data = request.json

    try:
        head_commit = data['head_commit']['id']
        cmd_id = head_commit[:8]
    except (TypeError, KeyError):
        head_commit = ''
        cmd_id = str(time.time())

    if execute(cmd_id, [UPDATE_CMD, head_commit], stdin=json_dumps(data).encode('utf-8')):
        return 'ok'
    else:
        return '!!'
Ejemplo n.º 52
0
def info():
    P = get_info_object()
    query = request.GET.get("arg",'')
    arg = ""
    options = {}
    plugins = []
    if query:
        args, options = util.parse_query(query)
        arg = args[0]
        all_plugins = P.plugins
        relevant_plugins = [p for p in all_plugins if P.compatible_argument(p.name, arg)]
        plugins = sorted(relevant_plugins, key=lambda x:x.name)
        options = json_dumps(options)
        query = cgi.escape(query, quote=True)
    return {"query": query, "arg": arg, "plugins": plugins, "options": options}
Ejemplo n.º 53
0
def cb():
    log.debug('~ Uploading!')
    bottle.response.set_header('Content-Type', 'application/json')
    yield
    prefix = os.path.join(config.shared_root, bottle.request.POST['prefix'].lstrip('/'))
    if prefix[-1] != '/':
        prefix += '/'
    items = []
    errors = []
    for f in bottle.request.files.values():
        fname = prefix+f.filename
        for t, d in root_objects.save_object_to_path(fname, f.file.read):
            if t == 'err':
                errors.append(d)
            elif t == 'new':
                items.append( [d, guess_type(d)] )
            yield
    yield bottle.json_dumps( {'error':errors or False, 'children': {'c':['link', 'mime'], 'r':items} } )
Ejemplo n.º 54
0
    def task(self):
        if not self.config.organization_id:
            return

        url = self.config.app_url + "/api/printer/ping/" + self.key
        data = {
            "name": self.config.server_name,
            "ip": self.config.find_local_ip(),
            "port": self.config.port,
            "secret": self.config.api_key,
            "organizationId": self.config.organization_id
        }
        headers = {"Content-type": "application/json"}
        json = json_dumps(data)
        bin_json = json.encode()
        req = urllib.request.Request(url, bin_json, headers)
        try:
            resp = urllib.request.urlopen(req)
            logger.debug("Ping: {0}".format(resp.read()))
        except Exception as ex:
            logger.error("Ping to %s failed: %s" % (url, str(ex)))
def query():
    """
    given {start_time, end_time, aggregation}
    return -> [{time, freq}, ...]
    """
    start_time = datetime.strptime(request.query.get("start_time"), '%Y-%m-%dT%H:%M:%SZ')
    end_time = datetime.strptime(request.query.get("end_time"), '%Y-%m-%dT%H:%M:%SZ')
    aggregation = request.query.get("aggregation")

    mg = MongoDB()
    mg.connect()

    print("querying time series...")
    results = mg.find( {'created_at': {'$gt': start_time, '$lt': end_time}} )

    results = Grid.get_ts(results, aggregation)

    ret = []
    for result in results:
        ret.append({'start_time': result[0].to_datetime().strftime('%Y-%m-%dT%H:%M:%SZ'),
                    'frequency': result[1].item()})

    response.content_type = 'application/json'
    return json_dumps(ret, indent=2)
Ejemplo n.º 56
0
    def test_json_HTTPError(self):
        self.app.error(400)(lambda e: e.body)
        self.app.route('/')(lambda: bottle.HTTPError(400, {'a': 1}))

        self.assertBody(bottle.json_dumps({'a': 1}))
        self.assertHeader('Content-Type','application/json')
Ejemplo n.º 57
0
    def test_json(self):
        self.app.route('/')(lambda: {'a': 1})

        self.assertBody(bottle.json_dumps({'a': 1}))
        self.assertHeader('Content-Type','application/json')
Ejemplo n.º 58
0
    def test_json_HTTPResponse(self):
        self.app.route('/')(lambda: bottle.HTTPResponse({'a': 1}, 500))

        self.assertBody(bottle.json_dumps({'a': 1}))
        self.assertHeader('Content-Type','application/json')
Ejemplo n.º 59
0
    storage = core.docvert_storage.storage_memory_based()
    error_message = None
    if suppress_error:
        try:
            core.docvert.process_pipeline(None, test_id, "tests", None, storage)
        except Exception, exception:
            bottle.response.content_type = "text/plain"
            class_name = "%s" % type(exception).__name__
            return bottle.json_dumps([{"status":"fail", "message": "Unable to run tests due to exception. <%s> %s" % (class_name, exception)}])
    else:
        try:
            core.docvert.process_pipeline(None, test_id, "tests", None, storage)
        except (core.docvert_exception.debug_exception, core.docvert_exception.debug_xml_exception), exception:
            bottle.response.content_type = exception.content_type
            return exception.data
    return bottle.json_dumps(storage.tests)

@bottle.route('/tests/', method='GET')
def tests_wrongdir():
    bottle.redirect('/tests')

@bottle.route('/3rdparty/sscdocapi')
def third_party_sscdocapi():
    return bottle.static_file('sscdocapi.html', root='%s/core/3rd-party/' % docvert_root)    

try:
    bottle.run(host=host, port=port, quiet=False)
except socket.error, e:
    if 'address already in use' in str(e).lower():
        print 'ERROR: %s:%i already in use.\nTry another port? Use command line parameter -H HOST or -p PORT to change it.' % (host, port)
    else:
Ejemplo n.º 60
0
def libreoffice_status():
    return bottle.json_dumps( {"libreoffice-status":core.docvert_libreoffice.checkLibreOfficeStatus()} )