def __init__(self, server, port): self.http_header = { "Cache-Control": "no-cache", "User-Agent": "DockerRegistryUI", "Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain" } self.jsonde = json.JSONDecoder() self.jsonen = json.JSONEncoder() self.server = server self.port = port
def output_json(namespace=None, repository=None): if repository is not None: _query = namespace + '/' + repository _uri = '/v1/repositories/' + _query + '/tags' _ancestry = {} _ancestry['tableheader'] = 'Ancestry' _ancestry['data'] = registry.act(uri=_uri) _tree_json = _ancestry['data'] _d = {'name':_query} _c = [] for k, v in _tree_json.iteritems(): _c.append({'name':k, 'children':[{'name':v}]}) _d['children'] = _c _data = json.JSONEncoder().encode(_d) return add_http_header(_data,'Content-Type', 'application/json')
def trak_api(url, params={}, dev=False): username = get_setting_value('trakt_username') password = hashlib.sha1(get_setting_value('trakt_password')).hexdigest() params = json.JSONEncoder().encode(params) request = urllib2.Request(url, params) base64string = base64.encodestring('%s:%s' % (username, password)).replace( '\n', '') request.add_header("Authorization", "Basic %s" % base64string) response = urllib2.urlopen(request) response = response.read() response = json.JSONDecoder().decode(response) if dev: print url print json.dumps(response, sort_keys=True, indent=4) return response
def response_obj(self, request, D, version_hint=JSONRPC_VERSION_DEFAULT): version = version_hint response = self.empty_response(version=version) apply_version = { '2.0': self.apply_version_2_0, '1.1': self.apply_version_1_1, '1.0': self.apply_version_1_0 } try: try: # determine if an object is iterable? iter(D) except TypeError as e: raise InvalidRequestError( getattr(e, 'message', e.args[0] if len(e.args) > 0 else None)) # version: validate if 'jsonrpc' in D: if text_type(D['jsonrpc']) not in apply_version: raise InvalidRequestError( 'JSON-RPC version {0} not supported.'.format( D['jsonrpc'])) version = request.jsonrpc_version = response[ 'jsonrpc'] = text_type(D['jsonrpc']) elif 'version' in D: if text_type(D['version']) not in apply_version: raise InvalidRequestError( 'JSON-RPC version {0} not supported.'.format( D['version'])) version = request.jsonrpc_version = response[ 'version'] = text_type(D['version']) else: version = request.jsonrpc_version = JSONRPC_VERSION_DEFAULT # params: An Array or Object, that holds the actual parameter values # for the invocation of the procedure. Can be omitted if empty. if 'params' not in D or not D['params']: D['params'] = [] if 'method' not in D or 'params' not in D: raise InvalidParamsError( 'Request requires str:"method" and list:"params"') if D['method'] not in self.urls: raise MethodNotFoundError('Method not found. Available methods: {0}' \ .format('\n'.join(list(self.urls.keys())))) method = self.urls[text_type(D['method'])] if getattr(method, 'json_validate', False): validate_params(method, D) if 'id' in D and D['id'] is not None: # regular request response['id'] = D['id'] if version in ('1.1', '2.0'): response.pop('error', None) else: # notification return None, 204 R = apply_version[version](method, D['params']) if 'id' not in D or ('id' in D and D['id'] is None): # notification return None, 204 if isinstance(R, Response): if R.status_code == 200: return R, R.status_code if R.status_code == 401: raise InvalidCredentialsError(R.status) raise OtherError(R.status, R.status_code) try: # New in Flask version 0.10. encoder = current_app.json_encoder() except AttributeError: encoder = json.JSONEncoder() # type of `R` should be one of these or... if not sum([isinstance(R, e) for e in \ string_types + integer_types + \ (float, complex, dict, list, tuple, set, frozenset, NoneType, bool)]): try: rs = encoder.default( R) # ...or something this thing supports except TypeError as exc: raise TypeError( 'Return type not supported, for {0!r}'.format(R)) response['result'] = R status = 200 except Error as e: response['error'] = e.json_rpc_format if version in ('1.1', '2.0'): response.pop('result', None) status = e.status except HTTPException as e: other_error = OtherError(e) response['error'] = other_error.json_rpc_format response['error']['code'] = e.code if version in ('1.1', '2.0'): response.pop('result', None) status = e.code except Exception as e: other_error = OtherError(e) response['error'] = other_error.json_rpc_format status = other_error.status if version in ('1.1', '2.0'): response.pop('result', None) # Exactly one of result or error MUST be specified. It's not # allowed to specify both or none. if version in ('1.1', '2.0') and 'result' in response: response.pop('error', None) return response, status
from flask import current_app, request, abort, json, make_response from flask.views import MethodView import time from api.app import db, redis_connection from api.user import user_id_from_ip, user_not_banned from api.database import fetch_query_string, rowify encoder = json.JSONEncoder(indent=2, sort_keys=True) DAY = 24 * 60 * 60 ACTIVE_RANGE = 14 * DAY class PlayerRanksView(MethodView): """ """ decorators = [user_not_banned] def get(self): "" ip = request.headers.get("X-Real-IP") user = current_app.secure_cookie.get(u"user") or user_id_from_ip(ip) if user != None: user = int(user) args = {} if request.args: args.update(request.args.to_dict(flat=True)) count = args.get("count") if count == None:
def get_db_insert_str(self): encoder = json.JSONEncoder() return f"""
def index(): posts = Post.query().order(Post.date).fetch() return render_template('index.html', posts=\ json.JSONEncoder().encode([\ dict(post.to_dict(), id=post.key.urlsafe()) for post in posts]))
def get_earthquakes(): earthquakes = query_db() result = json.JSONEncoder().encode(earthquakes) return result
# BEGIN Flask Config ########################################################################## APP = Flask(__name__) # Limit overall size to 1 mb APP.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024 API = Api(APP, api_version=None, api_spec_url='/docs/swagger', description='Eloqua Webhook Integration API', terms='Apache License', title='ELQ-WEBHOOK') json.JSONEncoder(ensure_ascii=False) ########################################################################## # END Flask Config ########################################################################## ########################################################################## # BEGIN Blueprint Registration ########################################################################## APP.register_blueprint(APP_V1, url_prefix='/api/v1') ########################################################################## # END Blueprint Registration ##########################################################################