Python flask.json.JSONEncoder.default() Examples

The following are code examples for showing how to use flask.json.JSONEncoder.default(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pragma.archivelab.org   Author: ArchiveLabs   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
def default(self, obj):
        try:
            if isinstance(obj, datetime):
                if obj.utcoffset() is not None:
                    obj = obj - obj.utcoffset()
                    millis = int(
                        calendar.timegm(obj.timetuple()) * 1000 +
                        obj.microsecond / 1000
                    )
                    return millis
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj) 
Example 2
Project: blockexplorer   Author: GenesisKernel   File: json.py    GNU General Public License v2.0 6 votes vote down vote up
def default(self, obj):
        from .models.db_engine.database import Database, Table, Column
        from decimal import Decimal
        try:
            if isinstance(obj, Decimal):
                return str(obj)
            if isinstance(obj, Database):
                return obj.as_dict()
            elif isinstance(obj, Table):
                return obj.as_dict()
            elif isinstance(obj, Column):
                return obj.as_dict()

            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj) 
Example 3
Project: pymate   Author: jorticus   File: receiver.py    GNU General Public License v2.0 6 votes vote down vote up
def default(self, o):
        try:
            if isinstance(o, datetime):
                return o.isoformat()
            if isinstance(o, MxStatus):
                return o.to_json()
            if isinstance(o, MxLogPage):
                return o.to_json()
            if isinstance(o, FxStatus):
                return o.to_json()
            iterable = iter(o)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, o) 
Example 4
Project: pogom-updated   Author: PokeHunterProject   File: app.py    MIT License 6 votes vote down vote up
def default(self, obj):
        try:
            if isinstance(obj, datetime):
                if obj.utcoffset() is not None:
                    obj = obj - obj.utcoffset()
                millis = int(
                        calendar.timegm(obj.timetuple()) * 1000 +
                        obj.microsecond / 1000
                )
                return millis
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj) 
Example 5
Project: Pokemon-Go-FB-Bot   Author: Haven-Lau   File: app.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def default(self, obj):
        try:
            if isinstance(obj, datetime):
                if obj.utcoffset() is not None:
                    obj = obj - obj.utcoffset()
                millis = int(
                    calendar.timegm(obj.timetuple()) * 1000 +
                    obj.microsecond / 1000
                )
                return millis
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj) 
Example 6
Project: PokemonGo-Map   Author: medghaim   File: app.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def default(self, obj):
        try:
            if isinstance(obj, datetime):
                if obj.utcoffset() is not None:
                    obj = obj - obj.utcoffset()
                millis = int(
                    calendar.timegm(obj.timetuple()) * 1000 +
                    obj.microsecond / 1000
                )
                return millis
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj) 
Example 7
Project: pogomap   Author: dustinlieu   File: app.py    Apache License 2.0 6 votes vote down vote up
def default(self, obj):
		try:
			if isinstance(obj, datetime):
				if obj.utcoffset() is not None:
					obj = obj - obj.utcoffset()
				millis = int(
					calendar.timegm(obj.timetuple()) * 1000 +
					obj.microsecond / 1000
				)
				return millis
			iterable = iter(obj)
		except TypeError:
			pass
		else:
			return list(iterable)
		return JSONEncoder.default(self, obj) 
Example 8
Project: PoGoMap-GUI   Author: engle2192   File: app.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def default(self, obj):
        try:
            if isinstance(obj, datetime):
                if obj.utcoffset() is not None:
                    obj = obj - obj.utcoffset()
                millis = int(
                    calendar.timegm(obj.timetuple()) * 1000 +
                    obj.microsecond / 1000
                )
                return millis
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj) 
Example 9
Project: RootersCTF2019-challenges   Author: abs0lut3pwn4g3   File: factory.py    MIT License 6 votes vote down vote up
def default(self, obj):
        try:
            if isinstance(obj, datetime):
                if obj.utcoffset() is not None:
                    obj = obj - obj.utcoffset()
                millis = int(
                    calendar.timegm(obj.timetuple()) * 1000 +
                    obj.microsecond / 1000
                )
                return millis
            iterable = iter(obj)
            if isinstance(obj, decimal.Decimal):
                # Convert decimal instances to strings.
                return float(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj) 
Example 10
Project: plexivity   Author: mutschler   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, _LazyString):
            return str(o)

        return BaseEncoder.default(self, o) 
Example 11
Project: qis   Author: quru   File: flask_ext.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime):
            ds = o.isoformat()
            if '+' not in ds:
                ds += 'Z'
            return ds
        elif isinstance(o, Exception):
            return {
                'exception': {
                    'type': type(o).__name__,
                    'message': str(o.args[0] if len(o.args) == 1 else ''),
                    'repr': repr(o)
                }
            }
        return JSONEncoder.default(self, o) 
Example 12
Project: elogy   Author: johanfforsberg   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime):
            serial = obj.timestamp()
            return serial
        elif isinstance(obj, peewee.SelectQuery):
            print("select")
            return list(obj)
        elif isinstance(obj, peewee.Model):
            serial = model_to_dict(obj, recurse=False)
            return serial

        return JSONEncoder.default(self, obj) 
Example 13
Project: white   Author: whiteclover   File: patch.py    GNU General Public License v2.0 5 votes vote down vote up
def default(self, o):
        if hasattr(o, '__json__') and callable(o.__json__):
            return o.__json__()
        if isinstance(o, (date,
                          datetime,
                          time)):
            return o.isoformat()[:19].replace('T', ' ')
        elif isinstance(o, (int, long)):
            return int(o)
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif hasattr(o, '__html__'):
            return text_type(o.__html__())
        return _JSONEncoder.default(self, o) 
Example 14
Project: progressivis   Author: jdfekete   File: app.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def default(self, o):
        "Handle default encoding."
        if isinstance(o, float) and np.isnan(o):
            return None
        if isinstance(o, np.integer):
            return int(o)
        if isinstance(o, np.bool_):
            return bool(o)
        if isinstance(o, np.ndarray):
            return o.tolist()
        return JSONEncoder.default(self, o) 
Example 15
Project: progressivis   Author: jdfekete   File: app.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def app_create(config="settings.py", scheduler=None):
    "Create the application"
    if scheduler is None:
        scheduler = Scheduler.default
    app = Flask('progressivis.server')
    if isinstance(config, str):
        app.config.from_pyfile(config)
    elif isinstance(config, dict):
        app.config.update(config)
    app.json_encoder = JSONEncoder4Numpy
    app.register_blueprint(progressivis_bp)
    progressivis_bp.setup(scheduler)
    return app 
Example 16
Project: progressivis   Author: jdfekete   File: app.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def start_server(scheduler=None, debug=False):
    "Start the server"
    # pylint: disable=global-statement
    global socketio
    eventlet.monkey_patch() # see https://github.com/miguelgrinberg/Flask-SocketIO/issues/357

    if scheduler is None:
        scheduler = Scheduler.default
    print('Scheduler %s has %d modules' % (scheduler.__class__.__name__, len(scheduler)))
    app = app_create(scheduler)
    app.debug = debug
    socketio = SocketIO(app, json=flask_json)
    socketio.on_event('connect', _on_connect)
    socketio.on_event('disconnect', _on_disconnect)
    socketio.on_event('join', _on_join)
    socketio.on_event('/progressivis/scheduler/start', _on_start)
    socketio.on_event('/progressivis/scheduler/step', _on_step)
    socketio.on_event('/progressivis/scheduler/stop', _on_stop)
    socketio.on_event('/progressivis/scheduler', _on_scheduler)
    socketio.on_event('/progressivis/module/get', _on_module_get)
    socketio.on_event('/progressivis/module/hotline_on', _on_module_hotline_on)
    socketio.on_event('/progressivis/module/hotline_off', _on_module_hotline_off)
    socketio.on_event('/progressivis/module/df', _on_module_df)
    socketio.on_event('/progressivis/module/input', _on_module_input)
    socketio.on_event('/progressivis/module/quality', _on_module_quality)
    socketio.on_event('/progressivis/logger', _on_logger)
    socketio.run(app) 
Example 17
Project: pass-culture-api   Author: betagouv   File: json_encoder.py    Mozilla Public License 2.0 5 votes vote down vote up
def default(self, obj):
        try:
            if isinstance(obj, Enum):
                return str(obj)
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj) 
Example 18
Project: flask-base-api   Author: mtnbarreto   File: base_definitions.py    MIT License 5 votes vote down vote up
def default(self, obj):
        try:
            if isinstance(obj, datetime.date):
                return obj.isoformat()
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj) 
Example 19
Project: arxiv-search   Author: arXiv   File: encode.py    MIT License 5 votes vote down vote up
def default(self, obj: Any) -> Union[str, List[Any]]:
        """Overriden to render date(time)s in isoformat."""
        try:
            if isinstance(obj, (date, datetime)):
                return obj.isoformat()
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj) #type: ignore 
Example 20
Project: Elogy   Author: MaxIV-KitsControls   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, datetime):
            serial = obj.timestamp()
            return serial
        elif isinstance(obj, peewee.SelectQuery):
            print("select")
            return list(obj)
        elif isinstance(obj, peewee.Model):
            serial = model_to_dict(obj, recurse=False)
            return serial

        return JSONEncoder.default(self, obj) 
Example 21
Project: Anemone   Author: Winnak   File: models.py    MIT License 5 votes vote down vote up
def default(self, obj): #override JSONEncoder's "default" method
        if isinstance(obj, Project):
            return dict(name=obj.name, slug=obj.slug, path=obj.path,
                        description=obj.description)
        else:
            JSONEncoder.default(self, obj)
    #pylint: enable=E0202 
Example 22
Project: fava   Author: beancount   File: charts.py    MIT License 5 votes vote down vote up
def default(self, o):  # pylint: disable=method-hidden
        if isinstance(o, Decimal):
            return float(o)
        if isinstance(o, (datetime.date, Amount, Position)):
            return str(o)
        if isinstance(o, (set, frozenset)):
            return list(o)
        try:
            return JSONEncoder.default(self, o)
        except TypeError:
            return str(o) 
Example 23
Project: inspect-docker-image   Author: giantswarm   File: service.py    Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        try:
            if isinstance(obj, datetime):
                return obj.isoformat()
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj) 
Example 24
Project: AI-Scalpel-Trading-Bot   Author: hackobi   File: api_server.py    GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        try:
            if isinstance(obj, Arrow):
                return obj.for_json()
            elif isinstance(obj, date):
                return obj.strftime("%Y-%m-%d")
            elif isinstance(obj, datetime):
                return obj.strftime("%Y-%m-%d %H:%M:%S")
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj) 
Example 25
Project: bso   Author: MinistereSupRecherche   File: json_encoding.py    MIT License 5 votes vote down vote up
def default(self, obj):
        """Default."""
        try:
            if isinstance(obj, datetime):
                return obj.strftime(BaseConfig.DATETIME_FORMAT)
            elif isinstance(obj, ObjectId):
                return str(obj)
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj) 
Example 26
Project: jitenshea   Author: garaud   File: webapi.py    MIT License 5 votes vote down vote up
def default(self, obj):
        try:
            if isinstance(obj, datetime):
                return obj.strftime(ISO_DATETIME)
            if isinstance(obj, date):
                return obj.strftime(ISO_DATE)
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)
        return JSONEncoder.default(self, obj) 
Example 27
Project: spanner-orm   Author: leapfrogtechnology   File: model_json_encoder.py    MIT License 5 votes vote down vote up
def default(self, obj):
        try:
            if isinstance(obj, BaseModel):
                return obj.__dict__()
            if isinstance(obj, date):
                return obj.strftime('%Y-%m-%d')
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)

        return JSONEncoder.default(self, obj) 
Example 28
Project: restpie3   Author: tomimick   File: webutil.py    MIT License 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, peewee.SelectQuery):
            return list(obj)
        if isinstance(obj, db.BaseModel):
            return obj.serialize()
        elif isinstance(obj, datetime.datetime):
#             dt_local = util.utc2local(obj)
            return obj.isoformat() if obj else None
        return JSONEncoder.default(self, obj)