示例#1
0
文件: __init__.py 项目: cjh1/tomviz
            def handle_rpc():
                json_body = {}
                try:
                    if bottle.request.headers['CONTENT_TYPE'] \
                       not in ('application/json', 'application/json-rpc'):
                        raise ParseError(
                            message='Invalid content type.',
                            data=bottle.request.headers['CONTENT_TYPE'])
                    try:
                        json_body = bottle.json_loads(
                            bottle.request.body.read())
                    except ValueError as err:
                        raise ParseError(
                            message='Invalid JSON.',
                            data=json.dumps(traceback.format_exc()))

                    response = self._endpoint.rpc(json_body)
                    # If we have error set the HTTP status code
                    if 'error' in response:
                        error = response['error']
                        status = jsonrpc_code_to_status.get(error['code'], 500)
                        bottle.response.status = status

                    return response
                except JsonRpcError as err:
                    return jsonrpc_message({
                        'id': json_body.get('id'),
                        'error': err.to_json()
                    })
示例#2
0
def do_work():
    context = zmq.Context()
    receiver = context.socket(zmq.SUB)
    receiver.connect('tcp://localhost:{}'.format(ZEROMQ_PORT))
    receiver.setsockopt(zmq.SUBSCRIBE, '')
    externalapi = ExternalApi('http://45.55.88.99:99/api/', 'nota', 'yu', 'yu')
    print 'worker ready'

    while True:
        s = receiver.recv_pyobj()
        if s.command == Command.SAVE:
            with open(s.path) as f:
                data = json_loads(f.read())
                options = InvoiceOptions()
                options.incrementar_codigo = False
                options.revisar_producto = False
                options.crear_cliente = True
                data['options'] = options
                del data.timestamp
                serialized = json_dumps(data.serialize())
                codigo = externalapi.save(serialized).json()['codigo']
                with sessionmanager as session:
                    session.query(NPedidoTemporal).filter_by(
                        id=s.uid).update({
                            NPedidoTemporal.status: 'uploaded',
                            NPedidoTemporal.external_id: codigo})
                    session.flush()
        elif s.command == Command.COMMIT:
            t = Invoice(InvMetadata, [])
            with sessionmanager as session:
                temp = session.query(NPedidoTemporal).filter_by(id=s.uid).first()
                if temp.external_id is not None:
                    t.meta.uid = temp.external_id
                    externalapi.commit(t)
示例#3
0
 def load(self):
     if path.exists(self.filename):
         try:
             with open(self.filename) as fp:
                 json = fp.read()
                 self.data.update(json_loads(json))
         except Exception as ex:
             logger.error("Failed reading config file: " + str(ex))
             self.data = {}
示例#4
0
 def parseJson(self, rep):
     if 'AJAX Error' in rep:
         html = self.load(self.pyfile.url, decode=True)
         m = re.search(r"waitingtime = (\d+);", html)
         if m:
             seconds = int(m.group(1))
             self.logDebug("You have to wait %d seconds between free downloads" % seconds)
             self.retry(wait_time=seconds)
         else:
             self.error(_("Unable to detect wait time between free downloads"))
     elif 'Hash expired' in rep:
         self.retry(reason=_("Hash expired"))
     return json_loads(rep)
示例#5
0
def auth_code(code:str, redirec_page:str) -> (str, int, str):
    url = "https://oauth.vk.com/access_token?client_id={0}&client_secret={1}&code={2}&redirect_uri=http://{3}:{4}" + redirec_page
    url = url.format(config.vk.appid, config.vk.secret, code, config.server.ip, config.server.port)
    try:
        response = urllib.request.urlopen(url)
    except Exception as e:
        e = ValueError()
        e.vkerror = dict()
        e.vkerror['error'] = "Auth error"
        e.vkerror['error_description'] = "Unauthorized"
        raise e
    response = response.read().decode()
    response = bottle.json_loads(response)
    if 'error' in response:
        e = ValueError()
        e.vkerror = response
        raise e
    return response['access_token'], response['user_id'], response.get('email')
示例#6
0
 def crear_ingreso():
     json_content = request.body.read()
     json_dict = json_loads(json_content)
     ingreso = Transferencia.deserialize(json_dict)
     ingreso = transapi.save(ingreso)
     return {'codigo': ingreso.meta.uid}