Python flask.json.JSONEncoder.default() Examples
The following are 22
code examples of flask.json.JSONEncoder.default().
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
flask.json.JSONEncoder
, or try the search function
.
Example #1
Source File: utils.py From flask-security with MIT License | 6 votes |
def get_url(endpoint_or_url, qparams=None): """Returns a URL if a valid endpoint is found. Otherwise, returns the provided value. :param endpoint_or_url: The endpoint name or URL to default to :param qparams: additional query params to add to end of url :return: URL """ try: return transform_url(url_for(endpoint_or_url), qparams) except Exception: # This is an external URL (no endpoint defined in app) # For (mostly) testing - allow changing/adding the url - for example # add a different host:port for cases where the UI is running # separately. if _security.redirect_host: url = transform_url( endpoint_or_url, qparams, netloc=_security.redirect_host ) else: url = transform_url(endpoint_or_url, qparams) return url
Example #2
Source File: api.py From multiscanner with Mozilla Public License 2.0 | 6 votes |
def get_file_task(task_id): ''' Download a single sample. Either raw binary or enclosed in a zip file. ''' # try to get report dict report_dict, success = get_report_dict(task_id) if not success: return jsonify(report_dict) # okay, we have report dict; get sha256 sha256 = report_dict.get('Report', {}).get('SHA256', '') if re.match(r'^[a-fA-F0-9]{64}$', sha256): return files_get_sha256_helper( sha256, request.args.get('raw', default='f')) else: return jsonify({'Error': 'sha256 invalid or not in report!'})
Example #3
Source File: api.py From multiscanner with Mozilla Public License 2.0 | 6 votes |
def get_report(task_id): ''' Return a JSON dictionary corresponding to the given task ID. ''' download = request.args.get('d', default='False', type=str)[0].lower() report_dict, success = get_report_dict(task_id) if success: if download == 't' or download == 'y' or download == '1': # raw JSON response = make_response(jsonify(report_dict)) response.headers['Content-Type'] = 'application/json' response.headers['Content-Disposition'] = 'attachment; filename=%s.json' % task_id return response else: # processed JSON intended for web UI report_dict = _pre_process(report_dict) return jsonify(report_dict) else: return jsonify(report_dict)
Example #4
Source File: app.py From pogom with MIT License | 6 votes |
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
Source File: serializers.py From kqueen with MIT License | 6 votes |
def default(self, obj): if hasattr(obj, 'get_dict'): return obj.get_dict() elif hasattr(obj, 'serialize'): return obj.serialize() try: return JSONEncoder.default(self, obj) except TypeError: print('Unserialized') print('class', obj.__class__) print('bases', dir(obj)) print(type(obj)) return {'__{}__'.format(obj.__class__.__name__): obj.__dict__}
Example #6
Source File: utils.py From fabric8-analytics-server with Apache License 2.0 | 5 votes |
def default(self, obj): """Implement the custom JSON encoder.""" try: if isinstance(obj, datetime.datetime): return json_serial(obj) iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
Example #7
Source File: api.py From multiscanner with Mozilla Public License 2.0 | 5 votes |
def get_stix2_bundle_from_report(task_id): ''' Generates a STIX2 Bundle with indicators generated of a JSON report. custom labels must be comma-separated. ''' report_dict, success = get_report_dict(task_id) if not success: return jsonify(report_dict) formatting = request.args.get('pretty', default='False', type=str)[0].lower() custom_labels = request.args.get('custom_labels', default='', type=str).split(",") if formatting == 't' or formatting == 'y' or formatting == '1': formatting = True else: formatting = False # If list is empty or any entry in the list is empty -> clear labels if custom_labels or all(custom_labels) is False: custom_labels = [] # If the report has no key/value pairs that we can use to create # STIX representations of this data. The default behavior is to return # an empty bundle. bundle = stix2_generator.parse_json_report_to_stix2_bundle(report_dict, custom_labels) # Setting pretty=True can be an expensive operation! response = make_response(bundle.serialize(pretty=formatting)) response.headers['Content-Type'] = 'application/json' response.headers['Content-Disposition'] = 'attachment; filename=%s_bundle_stix2.json' % task_id return response
Example #8
Source File: utils.py From flask-security with MIT License | 5 votes |
def hash_password(password): """Hash the specified plaintext password. Unless the hash algorithm (as specified by `SECURITY_PASSWORD_HASH`) is listed in the configuration variable `SECURITY_PASSWORD_SINGLE_HASH`, perform a double hash - first create an HMAC from the plaintext password and the value of `SECURITY_PASSWORD_SALT`, then use the configured hashing algorithm. This satisfies OWASP/ASVS section 2.4.5: 'provide additional iteration of a key derivation'. .. versionadded:: 2.0.2 :param password: The plaintext password to hash """ if use_double_hash(): password = get_hmac(password).decode("ascii") # Passing in options as part of hash is deprecated in passlib 1.7 # and new algorithms like argon2 don't even support it. return _pwd_context.hash( password, **config_value("PASSWORD_HASH_OPTIONS", default={}).get( _security.password_hash, {} ), )
Example #9
Source File: utils.py From flask-security with MIT License | 5 votes |
def config_value(key, app=None, default=None): """Get a Flask-Security configuration value. :param key: The configuration key without the prefix `SECURITY_` :param app: An optional specific application to inspect. Defaults to Flask's `current_app` :param default: An optional default value if the value is not set """ app = app or current_app # protect against spelling mistakes config = get_config(app) if key.upper() not in config: raise ValueError(f"Key {key} doesn't exist") return config.get(key.upper(), default)
Example #10
Source File: api.py From multiscanner with Mozilla Public License 2.0 | 5 votes |
def search(params, get_all=False): # Pass search term to Elasticsearch, get back list of sample_ids search_term = params.get('search[value]') search_type = params.pop('search_type', 'default') if not search_term: es_result = None else: es_result = handler.search(search_term, search_type) # Search the task db for the ids we got from Elasticsearch if get_all: return db.search(params, es_result, return_all=True) else: return db.search(params, es_result)
Example #11
Source File: api.py From multiscanner with Mozilla Public License 2.0 | 5 votes |
def index(): ''' Return a default standard message for testing connectivity. ''' return jsonify({'Message': 'True'})
Example #12
Source File: api.py From multiscanner with Mozilla Public License 2.0 | 5 votes |
def default(self, obj): if isinstance(obj, datetime): if obj.utcoffset() is not None: obj = obj - obj.utcoffset() return str(obj) else: return JSONEncoder.default(self, obj)
Example #13
Source File: utils.py From flask-security with MIT License | 5 votes |
def default(self, obj): if is_lazy_string(obj): return str(obj) else: return JSONEncoder.default(self, obj)
Example #14
Source File: json_encoder.py From renku-python with Apache License 2.0 | 5 votes |
def default(self, obj): """Overrides default json encoder with datetime iso format.""" try: if isinstance(obj, datetime): return isoformat(obj) iterable = iter(obj) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, obj)
Example #15
Source File: utils.py From fabric8-analytics-server with Apache License 2.0 | 5 votes |
def get_user_email(user_profile): """Get user e-mail address or the default address if user profile does not exist.""" # fallback address default_email = 'bayesian@redhat.com' if user_profile is not None: return user_profile.get('email', default_email) else: return default_email
Example #16
Source File: patch.py From white with GNU General Public License v2.0 | 5 votes |
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 #17
Source File: webutil.py From restpie3 with MIT License | 5 votes |
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)
Example #18
Source File: reports.py From qtpylib with Apache License 2.0 | 5 votes |
def load_cli_args(self): """ Parse command line arguments and return only the non-default ones :Retruns: dict a dict of any non-default args passed on the command-line. """ parser = argparse.ArgumentParser(description='QTPyLib Reporting', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--port', default=self.args["port"], help='HTTP port to use', type=int) parser.add_argument('--host', default=self.args["host"], help='Host to bind the http process to') parser.add_argument('--blotter', help='Use this Blotter\'s MySQL server settings') parser.add_argument('--nopass', help='Skip password for web app (flag)', action='store_true') # only return non-default cmd line args # (meaning only those actually given) cmd_args, _ = parser.parse_known_args() args = {arg: val for arg, val in vars( cmd_args).items() if val != parser.get_default(arg)} return args # ---------------------------------------
Example #19
Source File: reports.py From qtpylib with Apache License 2.0 | 5 votes |
def __init__(self, blotter=None, port=5000, host="0.0.0.0", password=None, **kwargs): # return self._password = password if password is not None else hashlib.sha1( str(datetime.datetime.now()).encode()).hexdigest()[:6] # initilize class logger self.log = logging.getLogger(__name__) # override args with any (non-default) command-line args self.args = {arg: val for arg, val in locals().items( ) if arg not in ('__class__', 'self', 'kwargs')} self.args.update(kwargs) self.args.update(self.load_cli_args()) self.dbconn = None self.dbcurr = None self.host = self.args['host'] if self.args['host'] is not None else host self.port = self.args['port'] if self.args['port'] is not None else port # blotter / db connection self.blotter_name = self.args['blotter'] if self.args['blotter'] is not None else blotter self.blotter_args = load_blotter_args(self.blotter_name) self.blotter = Blotter(**self.blotter_args) # connect to mysql using blotter's settings self.dbconn = pymysql.connect( host=str(self.blotter_args['dbhost']), port=int(self.blotter_args['dbport']), user=str(self.blotter_args['dbuser']), passwd=str(self.blotter_args['dbpass']), db=str(self.blotter_args['dbname']), autocommit=True ) self.dbcurr = self.dbconn.cursor() # ---------------------------------------
Example #20
Source File: reports.py From qtpylib with Apache License 2.0 | 5 votes |
def default(self, obj): if isinstance(obj, datetime.datetime) | \ isinstance(obj, datetime.date) | \ isinstance(obj, datetime.time): return int(timetime()) return JSONEncoder.default(self, obj)
Example #21
Source File: base_definitions.py From flask-base-api with MIT License | 5 votes |
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 #22
Source File: utils.py From fabric8-analytics-server with Apache License 2.0 | 4 votes |
def create_directory_structure(root=os.getcwd(), struct=dict()): """Create a directory structure. root: String path to root directory struct: Dict object describing dir structure an example: { 'name': 'parentdir', 'type': 'dir', 'contains': [ { 'name': 'hello.txt', 'type': 'file', 'contains': "Some text" }, { 'name': 'childdir', 'type': 'dir', } ] } """ _root = os.path.abspath(root) if isinstance(struct, list): for item in struct: create_directory_structure(_root, item) else: # default type is file if not defined _type = struct.get('type', 'file') _name = struct.get('name') _contains = struct.get('contains', '') if _name: _root = os.path.join(_root, _name) if _type == 'file': with open(_root, 'wb') as _file: if not isinstance(_contains, (bytes, bytearray)): _contains = _contains.encode() _file.write(_contains) else: os.makedirs(_root, exist_ok=True) if isinstance(_contains, (list, dict)): create_directory_structure(_root, _contains)