Python quart.jsonify() Examples

The following are 20 code examples of quart.jsonify(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module quart , or try the search function .
Example #1
Source File: test_testing.py    From quart with MIT License 6 votes vote down vote up
def test_cookie_jar() -> None:
    app = Quart(__name__)
    app.secret_key = "secret"

    @app.route("/", methods=["GET"])
    async def echo() -> Response:
        foo = session.get("foo")
        bar = request.cookies.get("bar")
        session["foo"] = "bar"
        response = jsonify({"foo": foo, "bar": bar})
        response.set_cookie("bar", "foo")
        return response

    client = Client(app)
    response = await client.get("/")
    assert (await response.get_json()) == {"foo": None, "bar": None}
    response = await client.get("/")
    assert (await response.get_json()) == {"foo": "bar", "bar": "foo"} 
Example #2
Source File: test_testing.py    From quart with MIT License 6 votes vote down vote up
def test_redirect_cookie_jar() -> None:
    app = Quart(__name__)
    app.secret_key = "secret"

    @app.route("/a")
    async def a() -> Response:
        response = redirect("/b")
        response.set_cookie("bar", "foo")
        return response

    @app.route("/b")
    async def echo() -> Response:
        bar = request.cookies.get("bar")
        response = jsonify({"bar": bar})
        return response

    client = Client(app)
    response = await client.get("/a", follow_redirects=True)
    assert (await response.get_json()) == {"bar": "foo"} 
Example #3
Source File: progress_bar.py    From quart with MIT License 5 votes vote down vote up
def check_status():
    global aredis, sr
    status = dict()
    try:
        if await aredis.get('state') == b'running':
            if await aredis.get('processed') != await aredis.get('lastProcessed'):
                await aredis.set('percent', round(
                    int(await aredis.get('processed')) / int(await aredis.get('length_of_work')) * 100, 2))
                await aredis.set('lastProcessed', str(await aredis.get('processed')))
    except:
        pass

    try:
        status['state'] = sr.get('state').decode()
        status['processed'] = sr.get('processed').decode()
        status['length_of_work'] = sr.get('length_of_work').decode()
        status['percent_complete'] = sr.get('percent').decode()
    except:
        status['state'] = sr.get('state')
        status['processed'] = sr.get('processed')
        status['length_of_work'] = sr.get('length_of_work')
        status['percent_complete'] = sr.get('percent')

    status['hint'] = 'refresh me.'

    return jsonify(status) 
Example #4
Source File: view.py    From code-jam-5 with MIT License 5 votes vote down vote up
def location():
    try:
        latitude = str(quart.request.args['lat'])
        longitude = str(quart.request.args['lng'])
    except KeyError:
        log.info('Failed to get coordinates from parameters.')
        return quart.abort(400)

    city = await app.azavea.get_nearest_city(latitude, longitude)
    if not city:
        log.info(f'Could not find a city for {latitude}, {longitude}')
        return quart.abort(404)
    else:
        return quart.jsonify(dataclasses.asdict(city)) 
Example #5
Source File: rest.py    From stacks-usecase with Apache License 2.0 5 votes vote down vote up
def pred():
    issue = list()
    issue.append(quart.request.json["issue"])
    if not quart.request.json or not "issue" in quart.request.json:
        quart.abort(400)
    labels = infer(issue)
    return quart.jsonify({"label": labels}), 201 
Example #6
Source File: rest.py    From stacks-usecase with Apache License 2.0 5 votes vote down vote up
def index():
    return quart.jsonify(banner), 201 
Example #7
Source File: rest.py    From stacks-usecase with Apache License 2.0 5 votes vote down vote up
def not_found(error):
    return quart.make_response(quart.jsonify({"error": "Not found"}), 404) 
Example #8
Source File: rest.py    From stacks-usecase with Apache License 2.0 5 votes vote down vote up
def recog():
    if quart.request.files.get("img"):
        img = quart.request.files["img"].read()
        img = Image.open(io.BytesIO(img))
        y_hat = classify(img)
        return quart.jsonify({"class": y_hat[0], "prob": y_hat[1]}), 201
    return quart.jsonify({"status": "not an image file"}) 
Example #9
Source File: rest.py    From stacks-usecase with Apache License 2.0 5 votes vote down vote up
def usage():
    return quart.jsonify({"info": banner}), 201 
Example #10
Source File: __init__.py    From aiocqhttp with MIT License 5 votes vote down vote up
def _handle_http_event(self) -> Response:
        if self._secret:
            if 'X-Signature' not in request.headers:
                self.logger.warning('signature header is missed')
                abort(401)

            sec = self._secret
            sec = sec.encode('utf-8') if isinstance(sec, str) else sec
            sig = hmac.new(sec, await request.get_data(), 'sha1').hexdigest()
            if request.headers['X-Signature'] != 'sha1=' + sig:
                self.logger.warning('signature header is invalid')
                abort(403)

        payload = await request.json
        if not isinstance(payload, dict):
            abort(400)

        if request.headers['X-Self-ID'] in self._wsr_api_clients:
            self.logger.warning(
                'there is already a reverse websocket api connection, '
                'so the event may be handled twice.')

        response = await self._handle_event(payload)
        if isinstance(response, dict):
            return jsonify(response)
        return Response('', 204) 
Example #11
Source File: server.py    From cellular-network-proxy_docker with Apache License 2.0 5 votes vote down vote up
def replicas():
    return jsonify(await get_replicas(int(request.args.get("type", "1")))) 
Example #12
Source File: city_api.py    From async-techniques-python-course with MIT License 5 votes vote down vote up
def sun(zip_code: str, country: str):
    lat, long = await location_service.get_lat_long(zip_code, country)
    sun_data = await sun_service.for_today(lat, long)
    if not sun_data:
        quart.abort(404)
    return quart.jsonify(sun_data) 
Example #13
Source File: city_api.py    From async-techniques-python-course with MIT License 5 votes vote down vote up
def weather(zip_code: str, country: str):
    weather_data = await weather_service.get_current(zip_code, country)
    if not weather_data:
        quart.abort(404)
    return quart.jsonify(weather_data) 
Example #14
Source File: test_testing.py    From quart with MIT License 5 votes vote down vote up
def test_set_cookie() -> None:
    app = Quart(__name__)

    @app.route("/", methods=["GET"])
    async def echo() -> Response:
        return jsonify({"foo": request.cookies.get("foo")})

    client = Client(app)
    client.set_cookie("localhost", "foo", "bar")
    response = await client.get("/")
    assert (await response.get_json()) == {"foo": "bar"} 
Example #15
Source File: test_testing.py    From quart with MIT License 5 votes vote down vote up
def test_form() -> None:
    app = Quart(__name__)

    @app.route("/", methods=["POST"])
    async def echo() -> Response:
        data = await request.form
        return jsonify(**data)

    client = Client(app)
    response = await client.post("/", form={"a": "b"})
    assert (await response.get_json()) == {"a": "b"} 
Example #16
Source File: test_testing.py    From quart with MIT License 5 votes vote down vote up
def test_json() -> None:
    app = Quart(__name__)

    @app.route("/", methods=["POST"])
    async def echo() -> Response:
        data = await request.get_json()
        return jsonify(data)

    client = Client(app)
    response = await client.post("/", json={"a": "b"})
    assert (await response.get_json()) == {"a": "b"} 
Example #17
Source File: broadcast.py    From quart with MIT License 5 votes vote down vote up
def broadcast():
    data = await request.get_json()
    for queue in app.clients:
        await queue.put(data['message'])
    return jsonify(True) 
Example #18
Source File: test_basic.py    From quart with MIT License 4 votes vote down vote up
def app() -> Quart:
    app = Quart(__name__)

    @app.route("/")
    async def index() -> ResponseReturnValue:
        return "index"

    @app.route("/sync/")
    def sync() -> ResponseReturnValue:
        return "index"

    @app.route("/json/", methods=["POST"])
    async def json() -> ResponseReturnValue:
        data = await request.get_json()
        return jsonify(data)

    @app.route("/implicit_json/", methods=["POST"])
    async def implicit_json() -> ResponseReturnValue:
        data = await request.get_json()
        return data

    @app.route("/error/")
    async def error() -> ResponseReturnValue:
        abort(409)
        return "OK"

    @app.route("/param/<param>")
    async def param() -> ResponseReturnValue:
        return param

    @app.errorhandler(409)
    async def generic_http_handler(_: Exception) -> ResponseReturnValue:
        return "Something Unique", 409

    @app.errorhandler(404)
    async def not_found_handler(_: Exception) -> ResponseReturnValue:
        return "Not Found", 404

    @app.websocket("/ws/")
    async def ws() -> None:
        # async for message in websocket:
        while True:
            message = await websocket.receive()
            await websocket.send(message)

    @app.websocket("/ws/abort/")
    async def ws_abort() -> None:
        abort(401)

    return app 
Example #19
Source File: marionette.py    From yobot with GNU General Public License v3.0 4 votes vote down vote up
def register_routes(self, app: Quart):

        @app.route(
            urljoin(self.setting['public_basepath'], 'marionette/'),
            methods=['GET'])
        async def yobot_marionette():
            new_cookie = None
            key_used = False
            key = request.args.get('key')
            if key is not None:
                user = Admin_key.get_or_none(Admin_key.key == key)
                if user is None:
                    return '403 Forbidden', 403
                if user.key_used:
                    key = None
                    key_used = True
                else:
                    user.key_used = True
                    user.save()
                    new_cookie = user.cookie
            if key is None:
                auth = request.cookies.get('yobot_auth')
                if auth is None:
                    if key_used:
                        return '链接已过期', 410
                    else:
                        return '403 Forbidden', 403
                user = Admin_key.get_or_none(Admin_key.cookie == auth)
                if user is None:
                    return '403 Forbidden', 403
            if not user.valid:
                return '登录已过期', 410

            res = await make_response(await render_template('marionette.html'))
            if new_cookie is not None:
                res.set_cookie('yobot_auth', new_cookie, max_age=604800)
            return res

        @app.route(
            urljoin(self.setting['public_basepath'], 'marionette/api/'),
            methods=['POST'])
        async def yobot_marionette_api():
            auth = request.cookies.get('yobot_auth')
            if auth is None:
                return '403 Forbidden', 403
            user = Admin_key.get_or_none(Admin_key.cookie == auth)
            if user is None:
                return '403 Forbidden', 403
            req = await request.get_json()
            if req is None:
                return '406 Not Acceptable', 406
            try:
                await self.api.send_msg(**req)
            except Exception as e:
                return jsonify(code=1, message=str(e))
            return jsonify(code=0, message='success') 
Example #20
Source File: web_util.py    From yobot with GNU General Public License v3.0 4 votes vote down vote up
def register_routes(self, app: Quart):

        @app.route(
            urljoin(self.setting['public_basepath'], 'api/ip-location/'),
            methods=['GET'])
        async def yobot_api_iplocation():
            if 'yobot_user' not in session:
                return jsonify(['unauthorized'])
            ip = request.args.get('ip')
            if ip is None:
                return jsonify(['unknown'])
            try:
                location = await _ip_location(ip)
            except:
                location = ['unknown']
            return jsonify(location)

        @app.route(
            urljoin(self.setting['public_basepath'], 'api/get-domain/'),
            methods=['GET'])
        async def yobot_api_getdomain():
            if 'yobot_user' not in session:
                return jsonify(code=400, message='Unauthorized')
            name = request.args.get('name')
            if name is None:
                return jsonify(code=400, message='No name specified')
            try:
                async with aiohttp.request('GET', url='http://api2.yobot.win/getdomain/?name='+name) as response:
                    if response.status != 200:
                        raise ServerError(
                            f'http code {response.status} from api2.yobot.win')
                    res = await response.json()
            except:
                return jsonify(code=401, message='Fail: Connect to Server')
            return jsonify(res)

        @app.route(
            urljoin(self.setting["public_basepath"],
                    "resource/<path:filename>"),
            methods=["GET"])
        async def yobot_resource(filename):
            localfile = os.path.join(self.resource_path, filename)
            if not os.path.exists(localfile):
                if filename.endswith('.jpg'):
                    filename = filename[:-4] + '.webp@w400'
                try:
                    async with aiohttp.request(
                        "GET",
                        url=f'https://redive.estertion.win/{filename}'
                    ) as response:
                        res = await response.read()
                        if response.status != 200:
                            return res, response.status
                except aiohttp.ClientError as e:
                    print(e)
                    return '404: Not Found', 404
                if not os.path.exists(os.path.dirname(localfile)):
                    os.makedirs(os.path.dirname(localfile))
                with open(localfile, 'wb') as f:
                    f.write(res)
            return await send_file(localfile)