Bladeren bron

basic REST sources

David 10 jaren geleden
bovenliggende
commit
fb131556e0
2 gewijzigde bestanden met toevoegingen van 23 en 10 verwijderingen
  1. 14 2
      db.py
  2. 9 8
      web.py

+ 14 - 2
db.py

@@ -1,12 +1,24 @@
 from pymongo import MongoClient
+from bson.objectid import ObjectId
 
 class db():
     def __init__(self):
         self.client = MongoClient('localhost', 27017)
         self.col=self.client.alexis["sources"]
 
-    def sources(self):
-        return [ p for p in self.col.find({"rss":0}) ]
+    def jsonable(self, el):
+        if el is None or "_id" not in el:
+            return el
+
+        el["_id"]=str(el["_id"])
+        return el
+
+    def sources(self,id=None):
+        if id is None:
+            return [ self.jsonable(p) for p in self.col.find() ]
+
+        ret=self.col.find_one({"_id":ObjectId(id)})
+        return self.jsonable(ret)
 
     def rss_sources(self):
         return [ p for p in self.col.find({"rss":1}) ]

+ 9 - 8
web.py

@@ -1,26 +1,27 @@
 #!/usr/bin/env python3
 
 from flask import Flask,abort,jsonify
+from db import db
 
 app = Flask(__name__)
+d = db()
+
 
 @app.route('/')
 def index():
     return "Hello, World!"
 
+@app.route('/sources/', methods=['GET'])
 @app.route('/sources', methods=['GET'])
 def get_sources():
-    sources=[]
-    return jsonify({'sources': sources})
-
+    return jsonify({'sources': d.sources()})
 
-@app.route('/sources/<int:source_id>', methods=['GET'])
+@app.route('/sources/<string:source_id>', methods=['GET'])
 def get_source(source_id):
-    sources=[]
-    source = [s for s in sources if s['id'] == source_id]
-    if len(source) == 0:
+    source=d.sources(source_id)
+    if source is None:
         abort(401)
-    return jsonify({'source': source[0]})
+    return jsonify({'source': source})
 
 
 @app.route('/add_source', methods=['POST'])