10 captures
28 Sep 2020 - 04 Dec 2025
Mar APR May
20
2020 2021 2022
success
fail

About this capture

COLLECTED BY

Collection: Common Crawl

Web crawl data from Common Crawl.
TIMESTAMPS

The Wayback Machine - http://web.archive.org/web/20210420233401/https://www.fullstackpython.com/flask-json-jsonencoder-examples.html
 

Full Stack Python logoFull Stack Python
All topics | Blog | Supporter's Edition | @fullstackpython | Facebook | What's new?

flask.json JSONEncoder Example Code






JSONEncoder is a class within the Flask project under the flask.json module. JSONEncoder is the default JSON encoder for Flask and was designed to handle more types than Python's standard library json module.

jsonify is another callable from the flask.json package with code examples.

Example 1 from Flask-Security-Too


Flask-Security-Too (PyPi page and project documentation) is a maintained fork of the original Flask-Security project that makes it easier to add common security features to Flask web applications. A few of the critical goals of the Flask-Security-Too project are ensuring JavaScript client-based single-page applications (SPAs) can work securely with Flask-based backends and that guidance by the OWASP organization is followed by default.

The Flask-Security-Too project is provided as open source under the MIT license.

Flask-Security-Too / flask_security / utils.py

# utils.py
import abc
import base64
import datetime
from functools import partial
import hashlib
import hmac
import time
from typing import Dict, List
import warnings
from datetime import timedelta
from urllib.parse import parse_qsl, parse_qs, urlsplit, urlunsplit, urlencode
import urllib.request
import urllib.error

from flask import (
    _request_ctx_stack,
    after_this_request,
    current_app,
    flash,
    g,
    request,
    session,
    url_for,
)
from flask.json import JSONEncoder
from flask_login import login_user as _login_user
from flask_login import logout_user as _logout_user
from flask_login import current_user
from flask_login import COOKIE_NAME as REMEMBER_COOKIE_NAME
from flask_principal import AnonymousIdentity, Identity, identity_changed, Need
from flask_wtf import csrf
from wtforms import ValidationError
from itsdangerous import BadSignature, SignatureExpired
from werkzeug.local import LocalProxy
from werkzeug.datastructures import MultiDict

from .quart_compat import best, get_quart_status
from .signals import user_authenticated

_security = LocalProxy(lambda: current_app.extensions["security"])

_datastore = LocalProxy(lambda: _security.datastore)

_pwd_context = LocalProxy(lambda: _security.pwd_context)

_hashing_context = LocalProxy(lambda: _security.hashing_context)

localize_callback = LocalProxy(lambda: _security.i18n_domain.gettext)



## ... source file abbreviated to get to JSONEncoder examples ...


        accept_mimetypes.best = best
    if accept_mimetypes.best == "application/json":
        return True
    return False


def json_error_response(errors):
    if isinstance(errors, str):
        response_json = dict(error=errors)
    elif isinstance(errors, dict):
        response_json = dict(errors=errors)
    else:
        raise TypeError("The errors argument should be either a str or dict.")

    return response_json


class FsJsonEncoder(JSONEncoder):

    def default(self, obj):
        from .babel import is_lazy_string

        if is_lazy_string(obj):
            return str(obj)
        else:
            return JSONEncoder.default(self, obj)


class SmsSenderBaseClass(metaclass=abc.ABCMeta):
    def __init__(self):
        pass

    @abc.abstractmethod
    def send_sms(self, from_number, to_number, msg):  # pragma: no cover
        return


class DummySmsSender(SmsSenderBaseClass):
    def send_sms(self, from_number, to_number, msg):  # pragma: no cover
        return


class SmsSenderFactory:
    senders = {"Dummy": DummySmsSender}

    @classmethod
    def createSender(cls, name, *args, **kwargs):
        return cls.senders[name](*args, **kwargs)


    return _security._render_json(payload, code, headers=None, user=user)


def default_want_json(req):
    if req.is_json:
        return True
    accept_mimetypes = req.accept_mimetypes
    if not hasattr(req.accept_mimetypes, "best"):  # pragma: no cover


## ... source file continues with no further JSONEncoder examples...





Sponsored By


Sentry logo
Software errors are inevitable. Chaos is not. Try Sentry for free.

AssemblyAI logo
The most accurate speech-to-text API. Built for Python developers.





Table of Contents



1. Introduction 2. Development Environments 3. Data 4. Web Development 5. Deployment 6. DevOps Changelog What Full Stack Means About the Author Future Directions Page Statuses Flask ExtensionsFlask Example Codeflask.app BadRequestflask.app Flaskflask.app Headersflask.app ImmutableDictflask.blueprints Blueprintflask.cli AppGroupflask redirectflask.cli DispatchingAppflask.cli FlaskGroupflask.cli ScriptInfoflask.cli pass_script_infoflask.cli with_appcontextflask requestflask.ctx after_this_requestflask.ctx has_app_contextflask.ctx has_request_contextflask.globals current_appflask.globals gflask.globals requestflask.globals sessionflask.helpers flashflask.helpers get_root_pathflask.helpers make_responseflask.helpers safe_joinflask.helpers send_fileflask.helpers url_forflask.json JSONEncoderflask.json jsonifyflask.sessions BadSignatureflask.sessions SessionInterfaceflask.sessions SessionMixinflask.signals Namespaceflask.signals got_request_exceptionflask.templating render_templateflask.templating render_template_stringflask.views MethodViewflask.views Viewflask.views http_method_funcsflask_sqlalchemy.SQLAlchemy Model ...or view the full table of contents.



Full Stack Python


Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.

Updates via Twitter & Facebook.



Chapters



1. Introduction 2. Development Environments 3. Data 4. Web Development 5. Deployment 6. DevOps Changelog What Full Stack Means About the Author Future Directions Page Statuses » flask.json JSONEncoder ...or view the full table of contents.

 



Matt Makai 2012-2021