From a3e4610ad97c68d0d3d698ed26be5f377d4100b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Denis=20Nut=CC=A6iu?= Date: Thu, 13 Apr 2017 08:49:05 +0300 Subject: [PATCH] Adding the ability to post JSON --- README.md | 8 ++++++++ src/application.py | 18 ++++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f5a1e55..d11f232 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,14 @@ This is a simple web app used for an university projects. It should provide a simple score board display for some benchmarking data which is gathered from another application. +## Posting data + +For now, you can post data using curl. + +''' +curl -H "Content-Type: application/json" -X POST -d '{"text":"Hello Darkness","score": 5000}' http://localhost:5000/upload +''' + ## Requires: * nosetests diff --git a/src/application.py b/src/application.py index 760503a..5e67deb 100644 --- a/src/application.py +++ b/src/application.py @@ -18,6 +18,7 @@ from src.models import Result from src.models import db import flask +import json import os @@ -43,9 +44,22 @@ def create_test_databases(): db.session.commit() -@app.route("/upload") +@app.route("/upload", methods=['POST']) def upload(): - return "Upload" + content = flask.request.get_json() + try: + text = flask.escape(content['text']) + score = int(content['score']) + except KeyError: # Json doesn't contain the keys we need. + return json.dumps({'success': False}), 400, {'ContentType': 'application/json'} + except TypeError: # The types from the json object are not correct. + return json.dumps({'success': False}), 400, {'ContentType': 'application/json'} + + entry = Result(text=text, score=score) + db.session.add(entry) + db.session.commit() + + return json.dumps({'success': True}), 200, {'ContentType': 'application/json'} @app.route("/")