rascunho

commit 2d5cadbe18e6aedf4b53f5385fb5bbb78de12f8e

Author: Pedro Lucas Porcellis <pedrolucasporcellis@gmail.com>

Add the public API

 core/app.py | 2 +
 core/blueprints/api.py | 46 ++++++++++++++++++++++++++++++++++++++++++++


diff --git a/core/app.py b/core/app.py
index c5c4cbcc1573e744ca9c883a95413eb50b3fdbc5..b35d7be7e67836b407de6221373cd7886a7614de 100644
--- a/core/app.py
+++ b/core/app.py
@@ -25,8 +25,10 @@             pass
 
 
         from core.blueprints.basic import basic
+        from core.blueprints.api import api
 
         self.register_blueprint(basic)
+        self.register_blueprint(api)
 
         @self.template_filter()
         def human_date(d):




diff --git a/core/blueprints/api.py b/core/blueprints/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..2354c5a9d8fc5abc3a2aefcad53e41390407fca6
--- /dev/null
+++ b/core/blueprints/api.py
@@ -0,0 +1,46 @@
+from flask import Blueprint, abort, request
+from hashlib import sha1
+from core.types.document import Document
+from core.database import db
+import json
+
+api = Blueprint("api.v1", __name__)
+
+@api.route('/api/v1', methods = ['POST'])
+def create():
+    params = json.loads(request.data.decode('utf-8'))
+
+    doc = None
+    content = params.get('text')
+
+    if not content:
+        abort(422)
+
+    sha = sha1()
+    sha.update(content.encode())
+    sha.update(request.remote_addr.encode())
+
+    existing_doc = Document.query.filter(Document.sha == sha.hexdigest()).one_or_none()
+
+    if existing_doc:
+        doc = existing_doc
+    else:
+        doc = Document()
+
+    doc.sha = sha.hexdigest()
+    doc.content = content
+
+    db.add(doc)
+    db.commit()
+    db.flush()
+
+    return doc.to_dict(), 201
+
+@api.route('/api/v1/<sha>', methods = ['GET'])
+def show(sha):
+    doc = Document.query.filter(Document.sha == sha).one_or_none()
+
+    if not doc:
+        abort(404)
+
+    return doc.to_dict(), 200