Here are the examples of the python api flask.json.dumps taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
177 Examples
3
Example 1
Project: flask-jsonrpc Source File: test_server.py
def test_batch_invalid(self):
req = json.dumps([
{'jsonrpc': '2.0','method': 'jsonrpc.echoNotFound', 'params': [], 'id': text_type(uuid.uuid4())},
{'jsonrpc': '2.0','method': 'jsonrpc.echo', 'params': [], 'id': text_type(uuid.uuid4())},
{'jsonrpc': '2.0','method': 'jsonrpc.echoNotFound', 'params': [], 'id': text_type(uuid.uuid4())}
])
resp = self._call(req)
self.assertTrue(len(resp) == 3)
self.assertNotIn('result', resp[0])
self.assertIn('error', resp[0])
self.assertEqual('Hello Flask JSON-RPC', resp[1]['result'])
self.assertNotIn('error', resp[1])
self.assertNotIn('result', resp[2])
self.assertIn('error', resp[2])
3
Example 2
Project: Flask-GAE-py27 Source File: responses.py
def api_response(
status=200, payload=None, message='success',
headers=None, mimetype='application/json'):
status = int(status)
data = json.dumps(payload)
return Response(
headers=headers,
status=status,
mimetype=mimetype,
response=data)
3
Example 3
Project: mrisa Source File: mrisa_server.py
@app.route('/search', methods = ['POST'])
# first function called
def mrisa_main():
# Detect the content type, only process if it's json, otherwise send an error
if request.headers['Content-Type'] == 'application/json':
client_json = json.dumps(request.json)
client_data = json.loads(client_json)
code = retrieve(client_data['image_url'])
return google_image_results_parser(code)
#return "JSON Message: " + json.dumps(request.json)
else:
json_error_message = "Requests need to be in json format. Please make sure the header is 'application/json' and the json is valid."
return json_error_message
3
Example 4
Project: flask-jsonrpc Source File: proxy.py
def send_payload(self, params):
"""Performs the actual sending action and returns the result
"""
data = json.dumps({
'jsonrpc': self.version,
'method': self.service_name,
'params': params,
'id': text_type(uuid.uuid4())
})
data_binary = data.encode('utf-8')
url_request = Request(self.service_url, data_binary, headers=self.headers)
return urlopen(url_request).read()
3
Example 5
Project: pyspider Source File: debug.py
@app.route('/debug/<project>/get')
def get_script(project):
projectdb = app.config['projectdb']
if not projectdb.verify_project_name(project):
return 'project name is not allowed!', 400
info = projectdb.get(project, fields=['name', 'script'])
return json.dumps(utils.unicode_obj(info)), \
200, {'Content-Type': 'application/json'}
3
Example 6
@candidates_blueprint.route('/list')
@login_required
def list():
access_token = session['access_token']
access_token = access_token[0]
logger.info('Searching for docuements: %s' % request.args)
results = google_api.search(access_token, 'title="Candidate CVs"')
return render_template('list.html', results=results, raw_json=json.dumps(results[0], indent=4))
3
Example 7
@app.route('/api/workflow', methods=['GET'])
def list_workflows():
""" Return a list of all workflows.
:resheader Content-Type: :mimetype:`application/json`
"""
workflows = Workflow.find_all(app.config['base_path'])
return make_response(json.dumps(workflows.values()),
200, {'Content-Type': 'application/json'})
3
Example 8
Project: guides-cms Source File: api.py
@app.route('/api/remove-heart/', methods=['POST'])
@login_required
def remove_heart():
"""
Remove heart to referenced article and return new heart count as JSON
"""
user = models.find_user()
if user is None:
data = {'error': 'Cannot heart unless logged in'}
return Response(response=json.dumps(data), status=401,
mimetype='application/json')
count = models.remove_heart(request.form['stack'], request.form['title'],
user.login)
return Response(response=json.dumps({'count': count}), status=200,
mimetype='application/json')
3
Example 9
def test_webhook(self):
server.convert_video.delay = MagicMock()
payload = {'api_key': '123456',
'url': 'http://media.giphy.com/media/WSqcqvTxgwfYs/giphy.gif',
'webhook': 'http://www.google.com'}
response = self.app.post('/convert', data=json.dumps(payload), follow_redirects=True)
self.assertEqual(response.status_code, 200)
server.convert_video.delay.assert_called_with(ANY, 'http://www.google.com')
3
Example 10
Project: ReproWeb Source File: views.py
@app.route('/settings/', methods=['GET', 'POST'])
def get_settings():
"""Settings view.
* If a GET request is made the settings page is returned.
* If a POST request is made, then the content of the request' form is
loaded into the settings and saved to disk."""
if request.method == 'POST':
return json.dumps(settings.save(request.form))
if request.method == 'GET':
g.breadcrumb = [ {'name': 'settings', 'url': url_for('get_settings')}, ]
settings.reload()
g.settings = settings
return render_template('settings.html')
3
Example 11
def put(self, resource, data=None, **kwargs):
headers = dict(kwargs.pop('headers', {}))
headers.setdefault('Content-Type', 'application/json')
data = json.dumps(data)
return self.request('PUT', resource, headers=headers,
data=data, **kwargs)
3
Example 12
@app.route('/counter')
def counter():
rpc = app.config['scheduler_rpc']
if rpc is None:
return json.dumps({})
result = {}
try:
data = rpc.webui_update()
for type, counters in iteritems(data['counter']):
for project, counter in iteritems(counters):
result.setdefault(project, {})[type] = counter
for project, paused in iteritems(data['pause_status']):
result.setdefault(project, {})['paused'] = paused
except socket.error as e:
app.logger.warning('connect to scheduler rpc error: %r', e)
return json.dumps({}), 200, {'Content-Type': 'application/json'}
return json.dumps(result), 200, {'Content-Type': 'application/json'}
3
Example 13
Project: sign-language-tutor Source File: app.py
@app.route('/score', methods=['POST'])
def add_score():
data = request.form
try:
record = json.dumps({'user': data['user'], 'score': int(data['score'])})
print record
result = r.lpush('scoreboard', record)
return jsonify(error=result)
except KeyError:
return jsonify(error=True)
3
Example 14
Project: flask-jsonrpc Source File: test_server.py
def test_batch_empty_json(self):
req = json.dumps([])
resp = self._call(req)
self.assertNotIn('result', resp)
self.assertIn('error', resp)
self.assertEqual('InvalidRequestError', resp['error']['name'])
3
Example 15
Project: guides-cms Source File: api.py
@app.route('/gh_rate_limit')
def gh_rate_limit():
"""Debug request to view rate limit on Github"""
return Response(response=json.dumps(remote.check_rate_limit()), status=200,
mimetype='application/json')
3
Example 16
Project: IP-ASN-history Source File: webservice.py
def history(request):
ip = request.get('ip')
if ip is None:
return json.dumps({})
return json.dumps([(line[0], line[1], line[2]) for line in
ipasn.history(ip, request.get('days_limit') or 30) if line is not None])
3
Example 17
Project: pns Source File: preprocessing_worker.py
def publish_gcm(self, gcm_devices, payload):
"""
publish gcm token list and message payload to gcm worker
:param gcm_devices:
:param payload:
:return:
"""
self.cm.basic_publish(exchange='pns_exchange',
routing_key='pns_gcm',
body=dumps({'devices': gcm_devices, 'payload': payload}, ensure_ascii=False),
mandatory=True,
properties=pika.BasicProperties(
delivery_mode=2, # make message persistent
content_type='application/json'))
3
Example 18
@app.route('/api/workflow/<workflow:workflow>/page')
def get_all_pages(workflow):
""" Get all pages for a workflow.
:param workflow: UUID or slug for a workflow
:type workflow: str
:resheader Content-Type: :mimetype:`application/json`
"""
return make_response(json.dumps(workflow.pages),
200, {'Content-Type': 'application/json'})
3
Example 19
Project: eve-elastic Source File: test_elastic.py
def test_resource_filter(self):
with self.app.app_context():
self.app.data.insert('items_with_description', [{'uri': 'foo', 'description': 'test'}, {'uri': 'bar'}])
req = ParsedRequest()
req.args = {}
req.args['source'] = json.dumps({'query': {'filtered': {'filter': {'term': {'uri': 'bar'}}}}})
self.assertEqual(0, self.app.data.find('items_with_description', req, None).count())
3
Example 20
Project: gif2html5-app Source File: test_server.py
def test_getting_mp4(self):
payload = {'url': 'http://media.giphy.com/media/WSqcqvTxgwfYs/giphy.gif',
'api_key': '123456'}
response = self.app.post('/convert', data=json.dumps(payload), follow_redirects=True)
self.assertEqual(response.status_code, 200)
data = json.loads(response.data)
self.assertRegex(data['mp4'], '\.mp4')
self.assertRegex(data['ogv'], '\.ogv')
self.assertRegex(data['webm'], '\.webm')
self.assertRegex(data['snapshot'], '\.jpg')
file_to_delete = data['mp4'].split('/')[-1]
s3Manager = S3Manager(get_config())
s3Manager.delete(file_to_delete)
3
Example 21
def save(self, meta):
data = dumps(meta.data)
return (db.update(self.table).mset(
dict(node_id=meta.node_id,
type=meta.type,
extend=meta.extend,
data=data)).condition('mid', meta.mid).execute())
3
Example 22
Project: flask-project-template Source File: manage.py
@manager.option('-d', '--destination', dest='destination', default=None, required=True, help='Output file')
def dump(destination):
dump_models = [] # List of models you want to dump
serialized = list()
for model in dump_models:
print('Dumping {}'.format(model))
serialized.append(unicode(dumps(db.session.query(model).all()), errors='ignore'))
with open(destination, 'w') as f:
f.writelines(json.dumps(serialized))
print('Done.')
3
Example 23
Project: eve-elastic Source File: test_elastic.py
def test_args_filter(self):
with self.app.app_context():
self.app.data.insert('items', [{'uri': 'foo'}, {'uri': 'bar'}])
req = ParsedRequest()
req.args = {}
req.args['filter'] = json.dumps({'term': {'uri': 'foo'}})
self.assertEqual(1, self.app.data.find('items', req, None).count())
3
Example 24
@app.route('/queues')
def get_queues():
def try_get_qsize(queue):
if queue is None:
return 'None'
try:
return queue.qsize()
except Exception as e:
return "%r" % e
result = {}
queues = app.config.get('queues', {})
for key in queues:
result[key] = try_get_qsize(queues[key])
return json.dumps(result), 200, {'Content-Type': 'application/json'}
3
Example 25
Project: ReproWeb Source File: views.py
@app.route('/api/<codename>/<component>/<architecture>/<package>/<version>/changelog')
def get_package_changelog(codename, component, architecture, package, version):
repository = Repository(settings.basedir)
try:
reference = cache(settings).read(repository, codename, component, architecture, package, version)
except:
for ref in repository.dumpreferences():
if ref['package'] == package and ref['version'] == version:
reference = ref
if 'reference' in locals():
reference['deb'] = os.path.join(repository.options.basedir, reference['deb'])
return json.dumps(repository.list_changes(reference['deb']))
return json.dumps([])
3
Example 26
def patch(self, resource, data=None, **kwargs):
headers = dict(kwargs.pop('headers', {}))
headers.setdefault('Content-Type', 'application/json')
data = json.dumps(data)
return self.request('PATCH', resource, headers=headers,
data=data, **kwargs)
3
Example 27
Project: zenodo Source File: legacyjson.py
def serialize_search(self, pid_fetcher, search_result, links=None,
item_links_factory=None):
"""Serialize as a json array."""
return json.dumps([self.transform_search_hit(
pid_fetcher(hit['_id'], hit['_source']),
hit,
links_factory=item_links_factory,
) for hit in search_result['hits']['hits']])
3
Example 28
def publish(self, data, type=None, id=None, retry=None, channel='sse'):
"""
Publish data as a server-sent event.
:param data: The event data. If it is not a string, it will be
serialized to JSON using the Flask application's
:class:`~flask.json.JSONEncoder`.
:param type: An optional event type.
:param id: An optional event ID.
:param retry: An optional integer, to specify the reconnect time for
disconnected clients of this stream.
:param channel: If you want to direct different events to different
clients, you may specify a channel for this event to go to.
Only clients listening to the same channel will receive this event.
Defaults to "sse".
"""
message = Message(data, type=type, id=id, retry=retry)
msg_json = json.dumps(message.to_dict())
return self.redis.publish(channel=channel, message=msg_json)
3
Example 29
Project: flask-jsonrpc Source File: helpers.py
def jsonify_status_code(status_code, *args, **kw):
"""Returns a jsonified response with the specified HTTP status code.
The positional and keyword arguments are passed directly to the
:func:`flask.jsonify` function which creates the response.
"""
is_batch = kw.pop('is_batch', False)
if is_batch:
response = flask_make_response(json.dumps(*args, **kw))
response.mimetype = 'application/json'
response.status_code = status_code
return response
response = jsonify(*args, **kw)
response.status_code = status_code
return response
3
Example 30
Project: guides-cms Source File: api.py
@app.route('/api/slack_stats/', methods=['GET'])
def slack_stats():
"""
Screen-scrape slack signup app since it's dynamic with node.js and grabs
from slack API.
"""
stats = ''
resp = requests.get(SLACK_URL)
if resp.status_code == 200:
user_count = re.search(r'<p class="status">(.*?)</p>', resp.content)
if user_count is not None:
stats = user_count.group(1)
return Response(response=json.dumps({'text': stats}), status=200,
mimetype='application/json')
3
Example 31
Project: flask-jsonrpc Source File: proxy.py
def send_payload(self, params):
dump = json.dumps({
'jsonrpc': self.version,
'method': self.service_name,
'params': params,
'id': text_type(uuid.uuid4())
})
dump_payload = FakePayload(dump)
response = current_app.post(self.service_url, **{'wsgi.input' : dump_payload, 'CONTENT_LENGTH' : len(dump)})
return response.content
3
Example 32
Project: FuzzFlow Source File: __init__.py
@app.route('/api/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return json.dumps({"err": "invalid request"}), 400
u_file = request.files['file']
if u_file.filename == '':
return json.dumps({"err": "invalid request"}), 400
path = os.path.join(config.UPLOAD_FOLDER, str(uuid.uuid4()))
u_file.save(path)
return json.dumps({"upload_path": path}), 200
3
Example 33
Project: flask-jsonrpc Source File: test_server.py
def test_batch_invalid_but_not_empty(self):
req = json.dumps([1])
resp = self._call(req)
self.assertTrue(len(resp) == 1)
self.assertNotIn('result', resp[0])
self.assertIn('error', resp[0])
self.assertEqual('InvalidRequestError', resp[0]['error']['name'])
3
Example 34
Project: eve-elastic Source File: test_elastic.py
def test_search_via_source_param_and_without_highlight(self):
query = {'query': {'query_string': {'query': 'foo'}}}
with self.app.app_context():
self.app.data.insert('items_with_description', [{'uri': 'foo',
'description': 'This is foo',
'name': 'foo'}])
self.app.data.insert('items_with_description', [{'uri': 'bar', 'name': 'bar'}])
req = ParsedRequest()
req.args = {'source': json.dumps(query), 'es_highlight': 0}
res = self.app.data.find('items_with_description', req, None)
self.assertEqual(1, res.count())
es_highlight = res[0].get('es_highlight')
self.assertIsNone(es_highlight)
3
Example 35
Project: flask-jsonrpc Source File: test_server.py
def test_batch_notify(self):
req = json.dumps([
{'jsonrpc': '2.0','method': 'jsonrpc.notify', 'params': ['Flask'], 'id': None},
{'jsonrpc': '2.0','method': 'jsonrpc.notify', 'params': ['JSON-RPC'], 'id': None},
])
resp = self.app.post(self.service_url, data=req).data
self.assertEqual(b(''), resp)
3
Example 36
@candidates_blueprint.route('/show')
@login_required
def show():
doc_id = request.args['docuement_id'] or request.form.get('docuement_id')
if doc_id:
access_token = session['access_token']
access_token = access_token[0]
logger.info(access_token)
file_resource = google_api.get_docuement(access_token, doc_id)
if file_resource:
return render_template('show.html', docuement=file_resource, raw=json.dumps(file_resource, indent=4))
else:
flash('No docuement found for the given Doc ID.')
return render_template('show.html')
else:
return render_template('show.html')
3
Example 37
Project: IP-ASN-history Source File: webservice.py
def aggregate_history(request):
ip = request.get('ip')
if ip is None:
return json.dumps({})
return json.dumps([(line[0], line[1], line[2], line[3])
for line in ipasn.aggregate_history(ip, request.get('days_limit') or 30)
if line is not None])
3
Example 38
Project: guides-cms Source File: api.py
@app.route('/api/add-heart/', methods=['POST'])
@login_required
def add_heart():
"""
Add heart to referenced article and return new heart count as JSON
"""
user = models.find_user()
if user is None:
data = {'error': 'Cannot heart unless logged in'}
return Response(response=json.dumps(data), status=401,
mimetype='application/json')
count = models.add_heart(request.form['stack'], request.form['title'],
user.login)
return Response(response=json.dumps({'count': count}), status=200,
mimetype='application/json')
3
Example 39
@app.route('/api/workflow/<workflow:workflow>', methods=['GET'])
def get_workflow(workflow):
""" Return a single workflow.
:param workflow: UUID or slug for a workflow
:type workflow: str
:resheader Content-Type: :mimetype:`application/json`
"""
return make_response(json.dumps(workflow),
200, {'Content-Type': 'application/json'})
3
Example 40
Project: pns Source File: preprocessing_worker.py
def publish_apns(self, apns_devices, payload):
"""
publish apns token list and message payload to apns worker
:param apns_devices:
:param payload:
:return:
"""
self.cm.basic_publish(exchange='pns_exchange',
routing_key='pns_apns',
body=dumps({'devices': apns_devices, 'payload': payload}, ensure_ascii=False),
mandatory=True,
properties=pika.BasicProperties(
delivery_mode=2, # make message persistent
content_type='application/json'))
3
Example 41
Project: learning-python Source File: decorators.py
def jsonify(func):
"""JSON decorator."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
r = func(*args, **kwargs)
if isinstance(r, tuple):
code, data = r
else:
code, data = 200, r
return Response(json.dumps(data), status=code, mimetype='application/json')
return wrapper
3
Example 42
Project: eve-elastic Source File: test_elastic.py
def test_search_via_source_param_and_schema_filter(self):
query = {'query': {'term': {'uri': 'foo'}}}
with self.app.app_context():
self.app.data.insert('items_with_description', [{'uri': 'foo', 'description': 'test', 'name': 'foo'}])
self.app.data.insert('items_with_description', [{'uri': 'bar', 'name': 'bar'}])
req = ParsedRequest()
req.args = {'source': json.dumps(query)}
res = self.app.data.find('items_with_description', req, None)
self.assertEqual(1, res.count())
3
Example 43
def dispatch_request(self, *args, **kwargs):
try:
rv = super(ServiceActionsView, self).dispatch_request(*args, **kwargs)
except ServiceError as e:
return make_response(json.dumps({"error": e.message}), e.http_code)
if isinstance(rv, Response):
return rv
# child actions can use "return" to return a value which
# can be something else than a proper Response instance.
# In this case we encode the return value to json
return marshal(rv, self.marshaller)
3
Example 44
def save(self, extend):
"""Save and update the extend"""
attributes = dumps(extend.attributes)
return (db.update(self.table).
mset(dict(type=extend.type,
label=extend.label,
key=extend.key,
attributes=attributes,
field=extend.field))
.condition('eid', extend.eid).execute())
3
Example 45
Project: pytentd Source File: flask.py
def jsonify(obj):
"""Similar to Flask's jsonify() function, but uses a single argument
and doesn't coerce the arguments into a dictionary.
Uses the mimetype of the request if possible, otherwise uses ``application/vnd.tent.v0+json``.
.. todo: Use current_app.json_encoder once Flask 0.10 is availible
"""
data = json.dumps(obj, cls=JSONEncoder, indent=2)
if request.mimetype in ['application/json', 'text/json']:
mimetype = request.mimetype
else:
mimetype = 'application/vnd.tent.v0+json'
return current_app.response_class(data, mimetype=mimetype)
3
Example 46
Project: eve-elastic Source File: test_elastic.py
def test_search_via_source_param(self):
query = {'query': {'term': {'uri': 'foo'}}}
with self.app.app_context():
self.app.data.insert('items', [{'uri': 'foo', 'name': 'foo'}])
self.app.data.insert('items', [{'uri': 'bar', 'name': 'bar'}])
req = ParsedRequest()
req.args = {'source': json.dumps(query)}
res = self.app.data.find('items', req, None)
self.assertEqual(1, res.count())
3
Example 47
Project: eve-elastic Source File: test_elastic.py
def test_search_via_source_param_and_with_highlight(self):
query = {'query': {'query_string': {'query': 'foo'}}}
with self.app.app_context():
self.app.data.insert('items_with_description', [{'uri': 'foo',
'description': 'This is foo',
'name': 'foo'}])
self.app.data.insert('items_with_description', [{'uri': 'bar', 'name': 'bar'}])
req = ParsedRequest()
req.args = {'source': json.dumps(query), 'es_highlight': 1}
res = self.app.data.find('items_with_description', req, None)
self.assertEqual(1, res.count())
es_highlight = res[0].get('es_highlight')
self.assertIsNotNone(es_highlight)
self.assertEqual(es_highlight.get('name')[0], '<span class=\"es-highlight\">foo</span>')
self.assertEqual(es_highlight.get('description')[0], 'This is <span class=\"es-highlight\">foo</span>')
3
Example 48
Project: eve-elastic Source File: test_elastic.py
def test_filters_with_filtered_query(self):
with self.app.app_context():
self.app.data.insert('items', [
{'uri': 'foo'},
{'uri': 'bar'},
{'uri': 'baz'},
])
query = {'query': {'filtered': {'filter': {'and': [
{'term': {'uri': 'foo'}},
{'term': {'uri': 'bar'}},
]}}}}
req = ParsedRequest()
req.args = {'source': json.dumps(query)}
cursor = self.app.data.find('items', req, None)
self.assertEqual(0, cursor.count())
3
Example 49
def __str__(self):
"""
Serialize this object to a string, according to the `server-sent events
specification <https://www.w3.org/TR/eventsource/>`_.
"""
if isinstance(self.data, six.string_types):
data = self.data
else:
data = json.dumps(self.data)
lines = ["data:{value}".format(value=line) for line in data.splitlines()]
if self.type:
lines.insert(0, "event:{value}".format(value=self.type))
if self.id:
lines.append("id:{value}".format(value=self.id))
if self.retry:
lines.append("retry:{value}".format(value=self.retry))
return "\n".join(lines) + "\n\n"
3
Example 50
def post(self, resource, data=None, **kwargs):
"""Shortcut for ``request('POST', resource)``.
Use this to make POST request since it will also encode ``data`` to
'application/json' format."""
headers = dict(kwargs.pop('headers', {}))
headers.setdefault('Content-Type', 'application/json')
data = json.dumps(data)
return self.request('POST', resource, headers=headers,
data=data, **kwargs)