Exemple #1
0
    def test_json_customization(self):
        class X(object):
            def __init__(self, val):
                self.val = val

        class MyEncoder(flak.json.JSONEncoder):
            def default(self, o):
                if isinstance(o, X):
                    return "<%d>" % o.val
                return flak.json.JSONEncoder.default(self, o)

        class MyDecoder(flak.json.JSONDecoder):
            def __init__(self, *args, **kwargs):
                kwargs.setdefault("object_hook", self.object_hook)
                flak.json.JSONDecoder.__init__(self, *args, **kwargs)

            def object_hook(self, obj):
                if len(obj) == 1 and "_foo" in obj:
                    return X(obj["_foo"])
                return obj

        app = Flak(__name__)
        app.json_encoder = MyEncoder
        app.json_decoder = MyDecoder

        @app.route("/", methods=["POST"])
        def index(cx):
            return cx.dumps(cx.get_json()["x"])

        c = app.test_client()
        rv = c.post("/", data=json.dumps({"x": {"_foo": 42}}), content_type="application/json")
        assert rv.data == b'"<42>"'
Exemple #2
0
 def jsonify_body(data) -> bytes:
     """
     Jsonify outgoing data
     :param data:
     :return: bytes string
     """
     return json.dumps(data).encode('utf8')  # type: bytes
Exemple #3
0
def dumps(obj, app=None, **kwargs):
    """Serialize ``obj`` to a JSON-formatted string. If there is an
    portal_forum context pushed, use the current portal_forum's configured encoder
    (:attr:`~flask.Flask.json_encoder`), or fall back to the default
    :class:`JSONEncoder`.

    Takes the same arguments as the built-in :func:`json.dumps`, and
    does some extra configuration based on the application. If the
    simplejson package is installed, it is preferred.

    :param obj: Object to serialize to JSON.
    :param app: App instance to use to configure the JSON encoder.
        Uses ``current_app`` if not given, and falls back to the default
        encoder when not in an portal_forum context.
    :param kwargs: Extra arguments passed to :func:`json.dumps`.

    .. versionchanged:: 1.0.3

        ``portal_forum`` can be passed directly, rather than requiring an portal_forum
        context for configuration.
    """
    _dump_arg_defaults(kwargs, app=app)
    encoding = kwargs.pop("encoding", None)
    rv = _json.dumps(obj, **kwargs)
    if encoding is not None and isinstance(rv, text_type):
        rv = rv.encode(encoding)
    return rv
def todo_to_json(id):
    from itsdangerous import json as _json
    todo = TodoManager.get_one_by_id(id)
    if todo:
        return jsonify(todo.to_json())
    return make_response(
        _json.dumps({'message': 'Todo with "id" %s does not exists' % id}),
        404, {'Content-Type': 'application/json'})
Exemple #5
0
 def jsonify_restrictions(filters, sorts, pagination):  # NOQA
     """
     :param filters:
     :param sorts:
     :param pagination:
     :return:
     """
     return json.dumps(RestlessAdapter.build_q(filters, sorts, pagination))
Exemple #6
0
 def get(self):
     b = Microwave.query.get_or_404(1)
     # return jsonify(microwave_schema(b))
     b_json = _json_.dumps(b, cls=JSONEncoder)
     print(type(b_json))  # str
     c_json = _json_.loads(b_json)
     print(type(c_json))  # dict
     return c_json
Exemple #7
0
        def f(*args):
            dumps_mock, dumps_mock2 = args
            dumps_mock.return_value = dumped
            dumps_mock2.return_value = dumped

            obj = JsonDict(initial_value)

            assert repr(obj) == json.dumps(initial_value, ensure_ascii=False)
Exemple #8
0
 def get(self):
     self.get_data()
     self.all_data['data'] = self.data
     self.all_data['max_temperature'] = max(self.temp)
     self.all_data['min_temperature'] = min(self.temp)
     d_str = _json_.dumps(self.all_data, cls=JSONEncoder)
     d_dict = _json_.loads(d_str)
     print(type(d_dict))
     return d_dict
Exemple #9
0
    def test_json_attr(self):
        app = Flak(__name__)

        @app.route("/add", methods=["POST"])
        def add(cx):
            json = cx.get_json()
            return text_type(json["a"] + json["b"])

        c = app.test_client()
        rv = c.post("/add", data=json.dumps({"a": 1, "b": 2}), content_type="application/json")
        assert rv.data == b"3"
Exemple #10
0
def logout():
    # Remove the user information from the session
    logout_user()
    # Remove session keys set by Flask-Principal
    for key in ('identity.name', 'identity.auth_type', 'hippo_user', 'crumbs'):
        session.pop(key, None)
    # Tell Flask-Principal the user is anonymous
    identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
    token = request.cookies.get(app.config['CASTIEL_AUTH_TOKEN'])
    if token:
        requests.post(app.config['COLDSTAR_URL'] + 'cas/api/release', data=json.dumps({'token': token}))
    return redirect(request.args.get('next') or '/')
Exemple #11
0
    def test_jsonify_body_returns_bytes_type(self):
        test_data = {
            'key1': 'key2',
            'ключ1': 'значение1',
            'key2': {
                'key21': 'value21'
            },
            'key3': ['value31', 'value32']
        }
        check_data = json.dumps(test_data)

        res = self.obj.jsonify_body(test_data)

        assert res == bytes(check_data, 'utf-8') and type(res) == bytes
Exemple #12
0
    def test_repr_json_serialize(self, initial_value):
        dumped = json.dumps(initial_value)

        @patch('json.dumps')
        @patch('itsdangerous.json.dumps')
        def f(*args):
            dumps_mock, dumps_mock2 = args
            dumps_mock.return_value = dumped
            dumps_mock2.return_value = dumped

            obj = JsonDict(initial_value)

            assert repr(obj) == json.dumps(initial_value, ensure_ascii=False)

        f()
Exemple #13
0
def dumps(obj, **kwargs):
    """把 ``obj`` 序列化成一个 JSON 格式的 ``str`` 。
    如果在堆栈上有一个网络应用的话,
    使用网络应用的配置编码器 (:attr:`~flask.Flask.json_encoder`) 。

    本函数可以返回 ``unicode`` 字符串或返回只有 ASCII 内容的字节字符串,
    默认情况自动强制成 unicode 字符串。这种默认行为是通过 ``JSON_AS_ASCII``
    配置变量来控制的,并且可以通过 simplejson 的 ``ensure_ascii`` 参数来覆写。
    """
    _dump_arg_defaults(kwargs)
    encoding = kwargs.pop('encoding', None)
    rv = _json.dumps(obj, **kwargs)
    if encoding is not None and isinstance(rv, text_type):
        rv = rv.encode(encoding)
    return rv
Exemple #14
0
def dumps(obj, **kwargs):
    """Serialize ``obj`` to a JSON formatted ``str`` by using the application's
    configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an
    application on the stack.

    This function can return ``unicode`` strings or ascii-only bytestrings by
    default which coerce into unicode strings automatically.  That behavior by
    default is controlled by the ``JSON_AS_ASCII`` configuration variable
    and can be overridden by the simplejson ``ensure_ascii`` parameter.
    """
    _dump_arg_defaults(kwargs)
    encoding = kwargs.pop('encoding', None)
    rv = _json.dumps(obj, **kwargs)
    if encoding is not None and isinstance(rv, text_type):
        rv = rv.encode(encoding)
    return rv
Exemple #15
0
def dumps(obj, **kwargs):
    """Serialize ``obj`` to a JSON formatted ``str`` by using the application's
    configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an
    application on the stack.

    This function can return ``unicode`` strings or ascii-only bytestrings by
    default which coerce into unicode strings automatically.  That behavior by
    default is controlled by the ``JSON_AS_ASCII`` configuration variable
    and can be overridden by the simplejson ``ensure_ascii`` parameter.
    """
    _dump_arg_defaults(kwargs)
    encoding = kwargs.pop('encoding', None)
    rv = _json.dumps(obj, **kwargs)
    if encoding is not None and isinstance(rv, text_type):
        rv = rv.encode(encoding)
    return rv
Exemple #16
0
    def get(self):
        # b = Microwave.query.get_or_404(1)
        # # return jsonify(microwave_schema(b))
        # b_json = _json_.dumps(b, cls=JSONEncoder)
        # print(type(b_json))         # str
        # c_json = _json_.loads(b_json)
        # print(type(c_json))         # dict
        # return c_json

        parser = reqparse.RequestParser()
        parser.add_argument('page', type=int, help='Page error')
        args = parser.parse_args()
        print(args)
        print(Microwave.query.first())
        a = Microwave.query.filter(Microwave.station_id == '54511',
                                   Microwave.datatype == '11').paginate(
                                       page=args["page"], per_page=2)
        a_items = a.items
        a_json = _json_.dumps(a_items, cls=JSONEncoder)
        a_jsons = _json_.loads(a_json)
        return a_jsons
Exemple #17
0
def stream_read(pos=-1, summary=None):
    if summary is None:
        summary = request.args.get('summary', None)
        summary = False if summary is None else True

    # if stream_tracker exists, then we're in a 2nd call of the same request.
    pos = getattr(g, 'stream_tracker', pos)

    if pos < 1:
        pos = 0

    item = read(pos, summary)
    g.stream_tracker = item.reads.pos

    response = models.Response(state.hostname, 200, 'Ok', None,
                               (time() - g.begin) * 1000)
    if isinstance(item, models.LazyResponse):
        item.add_response(response)
    if isinstance(item, models.Model):
        item = item.asdict()
    else:
        item.update(response.asdict())
    return json.dumps(item)
Exemple #18
0
    def get(self):
        # b = Microwave.query.get_or_404(1)
        # # return jsonify(microwave_schema(b))
        # b_json = _json_.dumps(b, cls=JSONEncoder)
        # print(type(b_json))         # str
        # c_json = _json_.loads(b_json)
        # print(type(c_json))         # dict
        # return c_json

        parser = reqparse.RequestParser()
        parser.add_argument('time_down', type=str, help='Time_down error')
        parser.add_argument('time_up', type=str, help='Time_up error')
        args = parser.parse_args()
        print(args)
        print(Microwave.query.first())
        print(type(args['time_down']))
        a = Microwave.query.filter(
            Microwave.station_id == '54511', Microwave.datatype == '11',
            Microwave.datetime >= args['time_down'],
            Microwave.datetime <= args['time_up']).all()
        a_json = _json_.dumps(a, cls=JSONEncoder)
        a_jsons = _json_.loads(a_json)
        return a_jsons
Exemple #19
0
import io
import uuid
from datetime import date
from .globals import current_app, request
from ._compat import text_type, PY2

from werkzeug.http import http_date
from jinja2 import Markup

# Use the same json implementation as itsdangerous on which we
# depend anyways.
from itsdangerous import json as _json

# Figure out if simplejson escapes slashes.  This behavior was changed
# from one version to another without reason.
_slash_escape = '\\/' not in _json.dumps('/')

__all__ = [
    'dump', 'dumps', 'load', 'loads', 'htmlsafe_dump', 'htmlsafe_dumps',
    'JSONDecoder', 'JSONEncoder', 'jsonify'
]


def _wrap_reader_for_text(fp, encoding):
    if isinstance(fp.read(0), bytes):
        fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)
    return fp


def _wrap_writer_for_text(fp, encoding):
    try:
Exemple #20
0
def check_valid_login():
    if (request.endpoint and
            'static' not in request.endpoint and
            not current_user.is_admin() and
            not getattr(app.view_functions[request.endpoint], 'is_public', False)):

        login_valid = False

        auth_token = request.cookies.get(app.config['CASTIEL_AUTH_TOKEN'])
        if auth_token:
            try:
                result = requests.post(app.config['COLDSTAR_URL'] + 'cas/api/check', data=json.dumps({'token': auth_token, 'prolong': True}))
            except ConnectionError:
                raise CasNotAvailable
            else:
                if result.status_code == 200:
                    answer = result.json()
                    if answer['success']:
                        if not current_user.is_authenticated():
                            user = UserAuth.get_by_id(answer['user_id'])
                            if login_user(user):
                                session_save_user(user)
                                # Tell Flask-Principal the identity changed
                                identity_changed.send(current_app._get_current_object(), identity=Identity(answer['user_id']))
                                return redirect(request.url or UserProfileManager.get_default_url())
                            else:
                                pass
                                # errors.append(u'Аккаунт неактивен')
                        login_valid = True
                    else:
                        # Remove the user information from the session
                        logout_user()
                        # Remove session keys set by Flask-Principal
                        for key in ('identity.name', 'identity.auth_type', 'hippo_user', 'crumbs'):
                            session.pop(key, None)
                        # Tell Flask-Principal the user is anonymous
                        identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())

        if not login_valid:
            # return redirect(url_for('login', next=request.url))
            return redirect(app.config['COLDSTAR_URL'] + 'cas/login?back=%s' % urllib2.quote(request.url))
        if not getattr(current_user, 'current_role', None) and request.endpoint != 'wm_config':
            return redirect(url_for('select_role', next=request.url))
Exemple #21
0
from jinja2 import Markup
from werkzeug.http import http_date

from .._compat import PY2
from .._compat import text_type
from ..globals import current_app
from ..globals import request

try:
    import dataclasses
except ImportError:
    dataclasses = None

# Figure out if simplejson escapes slashes.  This behavior was changed
# from one version to another without reason.
_slash_escape = "\\/" not in _json.dumps("/")

__all__ = [
    "dump",
    "dumps",
    "load",
    "loads",
    "htmlsafe_dump",
    "htmlsafe_dumps",
    "JSONDecoder",
    "JSONEncoder",
    "jsonify",
]


def _wrap_reader_for_text(fp, encoding):
def root():

    global ALIST_PREFIX

    if ALIST_PREFIX is None:
        ALIST_PREFIX = current_app.config['CACHE_KEY_PREFIX'] + "alist_"

    if request.method == "GET":

        keys = ['timestamp', 'nonce', 'signature', 'echostr']
        fields = tuple(map(request.args.get, keys))

        if any(f is None for f in fields):
            abort(404)

        timestamp, nonce, signature, echostr = fields

        raw = ''.join(sorted([TOKEN, timestamp, nonce]))

        if xSHA1(raw) != signature:
            raise WxbotAuthFailed("Verification Error !")

        return echostr

    elif request.method == "POST":

        keys = ['signature', 'nonce', 'openid', 'timestamp']

        if any(k not in request.args for k in keys):
            abort(404)

        msg = receive.parse_message(request.stream.read())
        no_reply = 'success'

        if isinstance(msg, receive.Message):

            to_user = msg.FromUserName
            from_user = msg.ToUserName
            message_type = msg.MsgType

            if message_type == 'text':

                content = msg.Content.strip()
                if content == '[Unsupported Message]':
                    return no_reply

                ## syntax: Q [any]

                mat = re_Q.match(content)
                if mat is None:
                    return no_reply

                keyword = mat.group(1)
                keyword = keyword.strip() if keyword is not None else None

                if keyword is None or len(keyword) == 0:
                    return reply.TextMessage(to_user, from_user, text.Q_INTRO)

                ## syntax: Q [index]

                mat = re_index.match(keyword)

                if mat is not None:

                    ix = int(mat.group(1)) - 1

                    if ix < 0:
                        return reply.TextMessage(to_user, from_user,
                                                 text.INDEX_OUT_OF_RANGE)

                    alist = RedisList(ALIST_PREFIX + to_user)
                    article = alist[ix]

                    if article is None:
                        return reply.TextMessage(to_user, from_user,
                                                 text.INDEX_OUT_OF_RANGE)

                    alist.expires(ALIST_EXPIRES)
                    article = json.loads(article)

                    return reply.ArticleMessage(to_user, from_user, [article])

                ## syntax: Q [keywords]

                mat = re_date.match(keyword)

                if mat is None:

                    sbq = db.session.\
                        query(
                            Article.aid,
                            db.fts_match(
                                Article.ix_text,
                                keyword,
                                db.fts_match.BOOLEAN
                            ).label('score')
                        ).\
                        order_by(
                            db.desc('score'),
                            Article.masssend_time.desc(),
                            Article.idx.asc()
                        ).\
                        limit(SEARCH_RESULT_COUNT).\
                        subquery()

                    articles = db.session.\
                        query(
                            Article.title,
                            Article.digest,
                            Article.cover_url,
                            Article.content_url,
                        ).\
                        join(sbq, sbq.c.aid == Article.aid).\
                        order_by(
                            sbq.c.score.desc(),
                            Article.masssend_time.desc(),
                            Article.idx.asc()
                        ).\
                        all()

                    if len(articles) == 0:
                        return reply.TextMessage(to_user, from_user,
                                                 text.NO_ARTICLE_MATCHED)

                    alist = RedisList(ALIST_PREFIX + to_user)
                    alist.clear()

                    if len(articles) == 1:
                        return reply.ArticleMessage(to_user, from_user,
                                                    articles)

                    content = '\n'.join("(%d) %s" % (ix + 1, a.title)
                                        for (ix, a) in enumerate(articles))

                    articles = [json.dumps(a._asdict()) for a in articles]
                    alist.append(*articles)
                    alist.expires(ALIST_EXPIRES)

                    return reply.TextMessage(to_user, from_user, content)

                ## syntax: Q[YYMMDD] / Q[YYMM]

                if mat.group(1) is not None:
                    year, month, day = map(int, mat.group(1, 2, 3))
                elif mat.group(4) is not None:
                    year, month = map(int, mat.group(4, 5))
                    day = None
                else:
                    return no_reply

                try:
                    st, ed = get_time_range(year, month, day)
                except ValueError as e:
                    return reply.TextMessage(to_user, from_user,
                                             text.INVALID_DATE)

                ## syntax: Q [YYMMDD]

                if mat.group(1) is not None:

                    sbq = db.session.\
                        query(Article.aid).\
                        filter(Article.masssend_time.between(st, ed)).\
                        order_by(
                            Article.masssend_time.desc(),
                            Article.idx.asc()
                        ).\
                        subquery()

                    articles = db.session.\
                        query(
                            Article.title,
                            Article.digest,
                            Article.cover_url,
                            Article.content_url
                        ).\
                        join(sbq, sbq.c.aid == Article.aid).\
                        order_by(
                            Article.masssend_time.desc(),
                            Article.idx.asc()
                        ).\
                        all()

                    if len(articles) == 0:
                        return reply.TextMessage(to_user, from_user,
                                                 text.NO_ARTICLE_ON_THIS_DAY)

                    alist = RedisList(ALIST_PREFIX + to_user)
                    alist.clear()

                    if len(articles) == 1:
                        return reply.ArticleMessage(to_user, from_user,
                                                    articles)

                    content = '\n'.join("(%d) %s" % (ix + 1, a.title)
                                        for (ix, a) in enumerate(articles))

                    articles = [json.dumps(a._asdict()) for a in articles]
                    alist.append(*articles)
                    alist.expires(ALIST_EXPIRES)

                    return reply.TextMessage(to_user, from_user, content)

                ## syntax: Q [YYMM]

                else:

                    articles = db.session.\
                        query(
                            Article.title,
                            Article.masssend_time
                        ).\
                        filter(Article.masssend_time.between(st, ed)).\
                        order_by(
                            Article.masssend_time.desc(),
                            Article.idx.asc()
                        ).\
                        all()

                    if len(articles) == 0:
                        return reply.TextMessage(to_user, from_user,
                                                 text.NO_ARTICLE_IN_THIS_MONTH)

                    articles = [
                        (time.strftime("%m-%d",
                                       time.localtime(a.masssend_time)),
                         a.title) for a in articles
                    ]

                    content = '\n'.join("%s %s" % a for a in articles)

                    return reply.TextMessage(to_user, from_user, content)

        elif isinstance(msg, receive.Event):

            to_user = msg.FromUserName
            from_user = msg.ToUserName
            event_type = msg.Event

            if event_type == 'subscribe':
                return reply.TextMessage(to_user, from_user, text.WELCOME)

            if event_type == 'CLICK':

                content = EVENT_REPLY_MAP.get(msg.EventKey)
                if content is None:
                    return no_reply

                return reply.TextMessage(to_user, from_user, content)

        return no_reply

    else:
        abort(405)
Exemple #23
0
import uuid
from datetime import date
from .globals import current_app, request
from ._compat import text_type, PY2

from werkzeug.http import http_date
from jinja2 import Markup

# Use the same json implementation as itsdangerous on which we
# depend anyways.
from itsdangerous import json as _json


# Figure out if simplejson escapes slashes.  This behavior was changed
# from one version to another without reason.
_slash_escape = '\\/' not in _json.dumps('/')


__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump',
           'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',
           'jsonify']


def _wrap_reader_for_text(fp, encoding):
    if isinstance(fp.read(0), bytes):
        fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)
    return fp


def _wrap_writer_for_text(fp, encoding):
    try:
Exemple #24
0
def _dumps(obj, **kw):
    encoding = kw.pop('encoding', None)
    rv = _json.dumps(obj, **kw)
    if encoding is not None and isinstance(rv, text_type):
        rv = rv.encode(encoding)
    return rv
Exemple #25
0
 def __repr__(self):
     return json.dumps(self.__wrapped__, ensure_ascii=False)
Exemple #26
0
import uuid
from datetime import date, datetime
from flask.globals import current_app, request
from flask._compat import text_type, PY2

from werkzeug.http import http_date
from jinja2 import Markup

# Use the same json implementation as itsdangerous on which we
# depend anyways.
from itsdangerous import json as _json


# Figure out if simplejson escapes slashes.  This behavior was changed
# from one version to another without reason.
_slash_escape = "\\/" not in _json.dumps("/")


__all__ = [
    "dump",
    "dumps",
    "load",
    "loads",
    "htmlsafe_dump",
    "htmlsafe_dumps",
    "JSONDecoder",
    "JSONEncoder",
    "jsonify",
]