async def run(request, *args):
            try:
                response = await f(request, *args)

                if not only_exception:
                    err_msg = ""
                    traceinfo = request.get("_traceinfo", [])
                    for line in traceinfo:
                        err_msg += "TRACE:{}\n".format(line)

                    body = json.loads(response.body)
                    body['_trace'] = err_msg
                    return sjson(body)

                return response
            except:
                logging.error("trace err!\n" + traceback.format_exc())
                err_msg = traceback.format_exc() + "\n"

                traceinfo = request.get("_traceinfo", [])
                for line in traceinfo:
                    err_msg += "TRACE:{}\n".format(line)
                return sjson({
                    "err": models.errors.system_error,
                    "err_msg": err_msg
                })
Beispiel #2
0
    async def capture_start(req):
        if await car.capturing.get():
            return sjson({"error": "already capturing"}, status=400)

        out = req.params.get("out")
        out = Path(out or f"out.{time.time()}")
        if out.exists():
            return sjson({"error": "can't start capture into existing folder"},
                         status=400)

        loop = asyncio.get_event_loop()
        await car.capturing.set(True)
        loop.create_task(capture(out))

        return sjson({"value": True})
Beispiel #3
0
def json(body, **kwargs):
    """Create a JSON-encoded `HTTPResponse` for an endpoint.

    Args:
        body (dict): A dictionary of data that will be encoded into a JSON
            HTTPResponse.
        **kwargs: Keyword arguments to pass to the response constructor.

    Returns:
        sanic.HTTPResponse: The Sanic endpoint response with the given body
            encoded as JSON.
    """
    if config.options.get('pretty_json'):
        return sjson(body, indent=2, dumps=_dumps, **kwargs)
    return sjson(body, **kwargs)
Beispiel #4
0
async def index(request):
    async with aiohttp.ClientSession() as sess:
        data = asyncio.gather(*[
            fetch(sess, 'http://httpbin.org/get?id={}'.format(link))
            for link in range(10000)
        ])
        return sjson(await data)
Beispiel #5
0
 async def _default_health_check(self, request):
     '''
     The route for checking health for default
     '''
     return sjson({
         "state": "health",
         "info": "service is healthy"
     })
Beispiel #6
0
async def json_response(request, response):
    result = []
    if isinstance(response, list):
        for item in response:
            result.append(await output_dict(item))
    elif isinstance(response, dict):
        result.append(await output_dict(response))
    else:
        return response

    return sjson({'responses': result}, status=200)
Beispiel #7
0
    async def handle_request(func, *args):
        resp_code = 200
        try:
            resp = func(*args)
        except AccessException as ae:
            logger.error("Error: {}".format(ae))
            resp_code = ae.error_code
            resp = {"Error": str(ae)}
        except Exception as ex:
            resp_code = 500
            logger.error("Error: {}".format(ex))
            resp = {'Error': 'Internal Server Error'}

        return sjson(resp, status=resp_code)
async def get_screenshot(request, machine_id, screenshot_id):
    screenshot = {}
    with data.Connection.use() as conn:
        screenshot = data.Screenshot.get({
            '_id': screenshot_id
        }, conn=conn).first()
    return sjson(
        {
            'responses': [{
                'result': {
                    'screenshot_id': f'{screenshot_id}',
                    'base64_data': screenshot.image_base64,
                    'suffix': screenshot.file_type,
                    'status': screenshot.status,
                },
                'type':
                'retry_until_last',
                'is_last':
                False if screenshot.status == 'not_obtained' else True,
            }]
        },
        status=200)
Beispiel #9
0
 async def capture_get(request):
     return sjson({"value": await car.capturing.get()})
def json_result(data, env=None):
    body = {"data": data, "env": env}
    return sjson(body)
Beispiel #11
0
def index(request):
    return sjson({"hello": "mama"})
Beispiel #12
0
async def test(request):
    if request.method == "OPTIONS":
        return text("ok")
    payload = request.json
    print(payload)
    if "origin" not in payload:
        return HTTPResponse("Missing trip origin", status=400)
    if "destination" not in payload:
        return HTTPResponse("Missing trip destination", status=400)
    if all([all(["lat", "lon"]) in payload[k] for k in payload.keys()]):
        return HTTPResponse("Missing lat/lon", status=400)

    origin = payload["origin"]
    destination = payload["destination"]

    print(origin)
    print(destination)

    url = 'https://cn-geo1.uber.com/rt/riders/me/fare-estimate'
    device_id = str(uuid.uuid4()).upper()
    headers = {
        'host': 'cn-geo1.uber.com',
        'Connection': 'keep-alive',
        'x-uber-device-epoch': '%.2f' % time.time(),
        'x-uber-device-location-latitude': '37.76345',
        'x-uber-request-uuid': str(uuid.uuid4()).upper(),
        'x-uber-client-session': str(uuid.uuid4()).upper(),
        'x-uber-client-name': 'client',
        'x-uber-device-id-tracking-enabled': '1',
        'X-Uber-RedirectCount': '0',
        'x-uber-device-os': '8.2',
        'x-uber-token': random.choice(tokens),
        'x-uber-device': 'iphone',
        'x-uber-device-ids': 'aaid:' + device_id,
        'Accept-Encoding': 'gzip, deflate',
        'Proxy-Connection': 'keep-alive',
        'x-uber-device-location-longitude': '-122.43649',
        'Accept-Language': 'en;q=1',
        'x-uber-device-language': 'en',
        'x-uber-client-id': 'com.ubercab.UberClient',
        'x-uber-device-h-accuracy': '200.00000',
        'User-Agent': '/iphone/3.225.3',
        'x-uber-device-model': 'iPhone4,1',
        'Accept': '*/*',
        'x-uber-device-v-accuracy': '12.27833',
        'x-uber-client-version': '3.225.3',
        'x-uber-device-id': device_id,
        'Content-Type': 'application/json',
        'Content-Length': '1750',
        'x-uber-device-location-altitude': '195.99226',
    }

    data = {
        "destination": {
            "addressComponents": [],
            "address_components": [],
            "components": [],
            "latitude": destination["lat"],
            "longitude": destination["lon"],
            "translations": {}
        },
        "isScheduledRide":
        None,
        "pickupLocation": {
            "addressComponents": [],
            "address_components": [],
            "components": [],
            "latitude": origin["lat"],
            "longitude": origin["lon"],
            "translations": {}
        },
        "userExperiments": [{
            "group": "master",
            "name": "beehive_upfront_pricing_v2"
        }],
        "vehicleViewIds": [],
        "version":
        "1.0.0"
    }

    r = requests.post(url=url,
                      headers=headers,
                      data=json.dumps(data),
                      proxies=proxies)

    print(r.text)

    fare_infos = [
        v for v in r.json()["packageVariants"]
        if "fareInfo" in v["pricingInfo"]
    ]

    print(fare_infos)

    data = {
        "deviceParameters": {
            "mcc": "310",
            "mnc": "VZW"
        },
        "launchParameters": {},
        "requestPickupLocation": {
            "locationSource": "DefaultDevice",
            "targetLocation": {
                "latitude": origin["lat"],
                "longitude": origin["lon"]
            }
        }
    }

    r = requests.post('https://cn-geo1.uber.com/rt/riders/me/app-launch',
                      headers=headers,
                      data=json.dumps(data),
                      proxies=proxies)

    vehicleviews = {
        int(k): {
            "name": v["displayName"],
            "image": v["productImage"]["url"] if "productImage" in v else None
        }
        for k, v in r.json()["city"]["vehicleViews"].items()
    }

    print(vehicleviews)

    # viewid_to_product = {
    #     4651: "ASSIST",
    #     2930: "SELECT",
    #     1930: "WAV",
    #     942: "uberXL",
    #     8: "uberX",
    #     2: "SUV",
    #     1: "BLACK",
    #     1491: "POOL"
    # }

    variants = [{
        "price":
        float(f["pricingInfo"]["fareInfo"]["upfrontFare"]["fare"]),
        "surge":
        f["pricingInfo"]["fareInfo"]["upfrontFare"]["surgeMultiplier"],
        "key":
        f["pricingInfo"]["packageVariantUuid"],
        "product":
        vehicleviews[f["vehicleViewId"]]["name"],
        "image":
        vehicleviews[f["vehicleViewId"]]["image"]
    } for f in fare_infos]

    return sjson(sorted(variants, key=lambda x: x["price"]))
Beispiel #13
0
 def status(request):
     return sjson({'Status': 'OK'})
Beispiel #14
0
 def general_error_handler(request, ex):
     logger.error("Error: {}".format(ex))
     return sjson({"Error": "Internal Server Error"}, status=500)
Beispiel #15
0
 def ae_error_handler(request, ae):
     logger.error("Error: {}".format(ae))
     return sjson({"Error": str(ae)}, status=ae.error_code)
Beispiel #16
0
 async def _default_health_check(self, request):
     return sjson({"state": "health", "info": "service is healthy"})