當前位置: 首頁>>代碼示例>>Python>>正文


Python json.JSONEncoder方法代碼示例

本文整理匯總了Python中flask.json.JSONEncoder方法的典型用法代碼示例。如果您正苦於以下問題:Python json.JSONEncoder方法的具體用法?Python json.JSONEncoder怎麽用?Python json.JSONEncoder使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在flask.json的用法示例。


在下文中一共展示了json.JSONEncoder方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: default

# 需要導入模塊: from flask import json [as 別名]
# 或者: from flask.json import JSONEncoder [as 別名]
def default(self, o):
        if isinstance(o, datetime.datetime):
            if o.tzinfo:
                # eg: '2015-09-25T23:14:42.588601+00:00'
                return o.isoformat("T")
            else:
                # No timezone present - assume UTC.
                # eg: '2015-09-25T23:14:42.588601Z'
                return o.isoformat("T") + "Z"

        if isinstance(o, datetime.date):
            return o.isoformat()

        if isinstance(o, Decimal):
            return float(o)

        if isinstance(o, set):
            return list(o)

        return json.JSONEncoder.default(self, o) 
開發者ID:ooni,項目名稱:api,代碼行數:22,代碼來源:app.py

示例2: respond

# 需要導入模塊: from flask import json [as 別名]
# 或者: from flask.json import JSONEncoder [as 別名]
def respond(self, follow_up=True, **kwargs):
        """Send a response back to the peer
        
        Normally, a response requires another response from the peer until done=True. If follow_up==False, then we will not look for a response yet. This is used in action='wait' responses where we are going to send multiple responses in a row to the peer.
        """
        if self['type'] == 'response':
            assert self['done'] == False, "Can't respond to a response that is already marked done."
        data = {'command_id': self['command_id'], 'type':'response'}
        data.update(kwargs)
        if not data.has_key('done'):
            data['done'] = False
        data_str = json.dumps(data, cls=JSONEncoder)
        log.debug("Sending response : {data}".format(data=data_str))
        self.ws.send(data_str)
        if data['done'] == False and follow_up:
            # We are still expecting a response to our response:
            return self.receive() 
開發者ID:datastax,項目名稱:cstar_perf,代碼行數:19,代碼來源:socket_comms.py

示例3: send

# 需要導入模塊: from flask import json [as 別名]
# 或者: from flask.json import JSONEncoder [as 別名]
def send(self, await_response=True):
        """Send this command to our peer for them to execute"""
        #In order to send a command, there needs to be a
        #new_command==True flag on this command. Otherwise, this
        #command will be assumed to have originated from our peer and
        #should not be sent.
        if not getattr(self, 'new_command', False):
            raise AssertionError("Cannot send command that is not marked as new_command")
        data = json.dumps(self, cls=JSONEncoder)
        log.debug("Sending command : {data}".format(data=data))
        self.ws.send(data)
        if not await_response:
            return
        # Wait for the response:
        response = json.loads(self.ws.receive())
        log.debug("Received response : {response}".format(response=response))
        if response.get('type') == 'response':
            if response.get('command_id') == self['command_id']:
                return Response(self.ws, response)
            else:
                raise AssertionError("Unexpected response id in : {stuff}".format(stuff=response))
        else:
            raise AssertionError("Was expecting a response, instead got {stuff}".format(stuff=response)) 
開發者ID:datastax,項目名稱:cstar_perf,代碼行數:25,代碼來源:socket_comms.py

示例4: default

# 需要導入模塊: from flask import json [as 別名]
# 或者: from flask.json import JSONEncoder [as 別名]
def default(self, obj):
    obj_type = type(obj)
    if obj_type in _NUMPY_INT_DTYPES:
      return int(obj)
    if obj_type in _NUMPY_FP_DTYPES:
      return float(obj)
    return json.JSONEncoder.default(self, obj) 
開發者ID:tensorflow,項目名稱:tensor2tensor,代碼行數:9,代碼來源:server.py

示例5: default

# 需要導入模塊: from flask import json [as 別名]
# 或者: from flask.json import JSONEncoder [as 別名]
def default(self, obj):
        if isinstance(obj, date):
            return obj.isoformat()
        if isinstance(obj, Decimal):
            return float(obj)
        if isinstance(obj, set):
            return [o for o in obj]
        if map_is_class and isinstance(obj, map):
            return [o for o in obj]
        if hasattr(obj, 'to_dict'):
            return obj.to_dict()
        return json.JSONEncoder.default(self, obj) 
開發者ID:openspending,項目名稱:babbage,代碼行數:14,代碼來源:api.py

示例6: jsonify

# 需要導入模塊: from flask import json [as 別名]
# 或者: from flask.json import JSONEncoder [as 別名]
def jsonify(obj, status=200, headers=None):
    """ Custom JSONificaton to support obj.to_dict protocol. """
    data = JSONEncoder().encode(obj)
    if 'callback' in request.args:
        cb = request.args.get('callback')
        data = '%s && %s(%s)' % (cb, cb, data)
    return Response(data, headers=headers, status=status,
                    mimetype='application/json') 
開發者ID:openspending,項目名稱:babbage,代碼行數:10,代碼來源:api.py

示例7: create_app

# 需要導入模塊: from flask import json [as 別名]
# 或者: from flask.json import JSONEncoder [as 別名]
def create_app() -> Flask:
    app = Flask(__name__)

    app.json_encoder = JSONEncoder

    app.register_blueprint(auctions_blueprint, url_prefix="/auctions")
    app.register_blueprint(shipping_blueprint, url_prefix="/shipping")

    # TODO: move this config
    app.config["SECRET_KEY"] = "super-secret"
    app.config["DEBUG"] = True
    app.config["SECURITY_SEND_REGISTER_EMAIL"] = False
    app.config["SECURITY_REGISTERABLE"] = True
    app.config["SECURITY_PASSWORD_SALT"] = "99f885320c0f867cde17876a7849904c41a2b8120a9a9e76d1789e458e543af9"
    app.config["WTF_CSRF_ENABLED"] = False

    app_context = bootstrap_app()
    FlaskInjector(app, modules=[AuctionsWeb()], injector=app_context.injector)

    @app.before_request
    def transaction_start() -> None:
        request.tx = app_context.connection_provider.open().begin()
        request.session = app_context.connection_provider.provide_session()

    @app.after_request
    def transaction_commit(response: Response) -> Response:
        try:
            if hasattr(request, "tx") and response.status_code < 400:
                request.tx.commit()
        finally:
            app_context.connection_provider.close_if_present()

        return response

    # has to be after DB-hooks, because it relies on DB
    security_setup(app)

    return app 
開發者ID:Enforcer,項目名稱:clean-architecture,代碼行數:40,代碼來源:app.py


注:本文中的flask.json.JSONEncoder方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。