class Tarefa(restful.Resource): def get(self, Tarefa_id): task = Task.objects(id = Tarefa_id) return task.as_pymongo() def delete(self, Tarefa_id): task = Task.objects(id = Tarefa_id).delete() return ("Tarefa " + Tarefa_id + " excluida.") def put(self, Tarefa_id): self.parser = reqparse.RequestParser() self.parser.add_argument('tarefa', type=str) self.parser.add_argument('prioridade', type=str) args = self.parser.parse_args() if not args['tarefa']: abort(400) Task(id = Tarefa_id, tarefa = args['tarefa'], prioridade = args['prioridade']).save() return args class Root(restful.Resource): def get(self): return { 'status': 'OK', 'mongo': str(mongo), } api.add_resource(Root, '/') api.add_resource(ListaTarefa, '/tarefa/') api.add_resource(Tarefa, '/tarefa/<Tarefa_id>')
" for (index in values) {" " count += values[index];" " }" " return count;" " };") result = mongo.db.products.map_reduce(map, reduce, "allergens_products") res = [] for doc in result.find({"_id": {'$regex' : query, '$options' : '-i'}}): res.append(doc['_id']) if request.args.get('count') and count == 1: return len(res) else: return res else: if request.args.get('count') and count == 1: return len(mongo.db.products.distinct('allergens_tags')) else: return mongo.db.products.distinct('allergens_tags') api.add_resource(ProductsList, '/products') api.add_resource(ProductsStats, '/products/stats/info') api.add_resource(ProductId, '/product/<string:barcode>') api.add_resource(ProductsBrands, '/products/brands') api.add_resource(ProductsCategories, '/products/categories') api.add_resource(ProductsCountries, '/products/countries') api.add_resource(ProductsAdditives, '/products/additives') api.add_resource(ProductsAllergens, '/products/allergens')
import json from flask import request, abort from flask.ext import restful from flask.ext.restful import reqparse from flask_rest_service import app, api, mongo from bson.objectid import ObjectId class Trip(restful.Resource): def __init__(self, *args, **kwargs): self.parser = reqparse.RequestParser() self.parser.add_argument('tripID', type=str) super(Trip, self).__init__() def get(self): # grab trip return None def post(self): # save trip return None class Root(restful.Resource): def get(self): return { 'status': 'OK', 'mongo': str(mongo.db), } api.add_resource(Root, '/') api.add_resource(Trip, '/Trip/<ObjectId:tripID>')
beers_summed = beers_summed.sort_values(ascending=False) # only show the ranked beers that are not part of the initial request list ranked_beers = beers_summed.index[beers_summed.index.isin(beers)==False] ranked_beers = ranked_beers.tolist() if n is None: return ranked_beers else: return ranked_beers[:n] # Just a dummy class to show the setup of different classes in Flask class Root(restful.Resource): def get(self): return { 'status': 'OK', } api.add_resource(Root, '/') api.add_resource(BeerList, '/beers/<int:n>')
class TagJQuery(restful.Resource): def __init__(self, *args, **kwargs): self.parser = reqparse.RequestParser() self.parser.add_argument('term', type=str, location='args') super(TagJQuery, self).__init__() def get(self): args = self.parser.parse_args() tags = mongo.db.tags.find({"$and":[{'value': {'$regex': args['term']}},{"type":{"$ne":"title"}}]}) tags.sort('value',1) titles = mongo.db.tags.find({'value': {'$regex': args['term']}},{"type":"title"}); tags.sort('value',1) return {'tags':tags,"titles":titles} class Root(restful.Resource): def get(self): return { 'status': 'OK', 'mongo': str(mongo.db), } api.add_resource(Root, '/') api.add_resource(TagList, '/tags/') api.add_resource(Tag, '/tags/<ObjectId:tag_id>') api.add_resource(RemoveTag,'/removeTag/') api.add_resource(TagSearch, '/tags/search/<word>') api.add_resource(TagJQuery, '/frontend/jquery')
def getdata(self, tree): jsondata = {} for meal in tree.findall(".//*[@class='shortmenumeals']"): curr_meal = meal.text jsondata[curr_meal] = {} mealparent = meal.find("../../../../../../..") for foodtype in mealparent.findall(".//*[@class='shortmenucats']/span"): curr_foodtype = foodtype.text[3:-3] jsondata[curr_meal][curr_foodtype] = [] for food in foodtype.xpath("../../../following-sibling::tr"): newname = food.text_content().strip() if newname is not None: if re.match("-- .* --", newname): break if newname not in regulars[hallname][curr_meal]: jsondata[curr_meal][curr_foodtype].append(newname) return jsondata class Ingredients(Resource): def get(self, food): food = food.replace('+', ' ').lower() indb = mongo.db.ingredients.find_one({"name": food}) if indb is not None: return indb else: return {"error": "Food not found."} api.add_resource(Menu, '/menus/<hall>/<day>/<month>/<year>') api.add_resource(RelevantMenu, '/rmenus/<hall>/<day>/<month>/<year>') api.add_resource(Ingredients, '/ingredients/<food>')
@app.route('/getFeedback/') def getFeedback(): res = {'status':0, 'entries':[x for x in mongo.db.feedbacks.find()]} print(res) return res class MyFeedback(restful.Resource): def get(self): res = {'status':0, 'entries':[x for x in mongo.db.feedbacks.find()]} return res api.add_resource(MyFeedback, '/myfeedback/') api.add_resource(ReadingList, '/readings/') api.add_resource(Reading, '/readings/<ObjectId:reading_id>') from urlparse import urljoin from werkzeug.contrib.atom import AtomFeed def make_external(url): return urljoin(request.url_root, url) @app.route('/recent.atom') def recent_feed(): feed = AtomFeed('dailyfx summary',
def get(self): return [x for x in mongo.db.readings.find()] def post(self): args = self.parser.parse_args() if not args['reading']: abort(400) with open('pylog.txt', 'w') as file_: file_.write(args['reading']) jo = json.loads(args['reading']) reading_id = mongo.db.readings.insert(jo) return mongo.db.readings.find_one({"_id": reading_id}) class Reading(restful.Resource): def get(self, reading_id): return mongo.db.readings.find_one_or_404({"_id": reading_id}) def delete(self, reading_id): mongo.db.readings.find_one_or_404({"_id": reading_id}) mongo.db.readings.remove({"_id": reading_id}) return '', 204 api.add_resource(Root, '/') api.add_resource(ReadingList, '/readings/') api.add_resource(Reading, '/readings/<ObjectId:reading_id>') api.add_resource(Finder, '/find') api.add_resource(Inserter, '/ins')
import json import pymongo from flask import request, abort, json, Flask, render_template from flask.ext import restful from flask.ext.restful import reqparse from flask_rest_service import app, api, mongo from bson.objectid import ObjectId from bson.code import Code # ----- / returns status OK and the MongoDB instance if the API is running ----- class Root(restful.Resource): # ----- GET Request ----- def get(self): return { 'status': 'OK', 'mongo': str(mongo.db), } api.add_resource(Root, '/')
return dbobj def getdata(self, tree): jsondata = {} print "hi" for meal in tree.findall(".//*[@class='shortmenumeals']"): curr_meal = meal.text jsondata[curr_meal] = {} mealparent = meal.find("../../../../../../..") for foodtype in mealparent.findall(".//*[@class='shortmenucats']/span"): curr_foodtype = foodtype.text[3:-3] jsondata[curr_meal][curr_foodtype] = [] for food in foodtype.xpath("../../../following-sibling::tr"): if food.find(".//*[@name='Recipe_Desc']") is None: break newname = food.find(".//*[@name='Recipe_Desc']").text if newname: jsondata[curr_meal][curr_foodtype].append(cgi.escape(newname)) return jsondata class Ingredients(restful.Resource): def get(self, food): food = food.replace('+', ' ').lower() indb = mongo.db.ingdata.find_one({"name": food}) if indb is not None: return indb else: return {"error": "Food not found."} api.add_resource(Menu, '/menus/<hall>/<day>/<month>/<year>') api.add_resource(Ingredients, '/ingredients/<food>')
from flask.ext import restful from flask.ext.restful import reqparse from flask_rest_service import app, api import httplib def output_json(data, code, headers=None): resp = make_response(json.dumps(data), code) resp.headers.extend(headers or {}) return resp class Root(restful.Resource): def get(self): # return {'status':'OK'} return make_response("",200) class Imgflip(restful.Resource): def get(self): qs = request.query_string createUrl = '/caption_image?username=memegen15478742&password=test' + '&' + qs conn = httplib.HTTPSConnection("api.imgflip.com") conn.request("GET", createUrl, headers={}) response = conn.getresponse() data = response.read() result = json.loads( data ) if result["success"] == True : return make_response('imgflip_jsonp( "' + result["data"]["url"]+ '" )',200) else: return output_json({'error': result["error_message"]}, 400) api.add_resource(Root, '/') api.add_resource(Imgflip, '/imgflip')
if args['prev'] != None: return period_prev(user) if args['get_list'] != None: return stats_get_list(user) if args['get_symptoms'] != None: return stats_get_symptoms(user) if args['get_all'] != None: return stats_get_all(user) if args['mood'] != None: return stats_mood(user, args['mood']) if args['sensor'] != None: return stats_sensor(user, args['sensor']) if args['symptoms'] != None: return stats_symptoms(user, args['symptoms']) else: return None # Return status information about the server class Root(restful.Resource): def get(self): return { 'status': 'OK', 'oneweek': 'winners', 'Best Coders': 'Jesse and Chad', 'mongo': str(mongo.db), } api.add_resource(Root, '/') api.add_resource(Users, '/users/<username>')
import json from flask import Flask from flask_restful import Resource, Api from flask_rest_service import app, api class Root(Resource): def get(self): return { 'status': 'OK', 'hello': 'world' } class Blond(Resource): def get(self): return { 'status': 'OK', 'blond': 'dumb' } ''' Add REST Resources here ''' # finally add these resources like so api.add_resource(Root, '/') api.add_resource(Blond, '/blond')
# def get(self): # return [x for x in mongo.db.readings.find()] # # def post(self): # args = self.parser.parse_args() # if not args['reading']: # abort(400) # # jo = json.loads(args['reading']) # reading_id = mongo.db.readings.insert(jo) # return mongo.db.readings.find_one({"_id": reading_id}) class Root(restful.Resource): def get(self): return { 'status': 'OK', 'mongo': str(mongo.db), } class Add(restful.Resource): def get(self): return { 'status': 'OK', 'mongo': str(mongo.db), } api.add_resource(Root, '/') api.add_resource(ReadingList, '/readings/') api.add_resource(Reading, '/readings/<ObjectId:reading_id>')
import json import pymongo from flask import request, abort, json, render_template, Response from flask.ext import restful from flask.ext.restful import reqparse from flask_rest_service import app, api, mongo from bson.objectid import ObjectId from bson.code import Code # ----- /stats ----- class Stats(restful.Resource): # ----- GET Request ----- def get(self): return Response(render_template("index.html"), mimetype='text/html') api.add_resource(Stats, '/stats')
abort(400) jo = json.loads(args['reading']) reading_id = mongo.db.readings.insert(jo) return mongo.db.readings.find_one({"_id": reading_id}) class Reading(Resource): # gets objectID as a param and returns reading with that id when receiving an HTTP GET # deletes reading with that ID when receiving an HTTP DELETE def get(self, reading_id): return mongo.db.readings.find_one_or_404({"_id": reading_id}) def delete(self, reading_id): mongo.db.readings.find_one_or_404({"_id": reading_id}) mongo.db.readings.remove({"_id": reading_id}) return '', 204 class Root(Resource): # returns dictionary with info on MongoDB connection def get(self): return { 'status': 'OK', 'mongo': str(mongo.db), } api.add_resource(Root, '/') api.add_resource(ReadingList, '/readings/') api.add_resource(Reading, '/readings/<ObjectId:reading_id>')
import json import pymongo from flask import request, abort, json, render_template, Response from flask.ext import restful from flask.ext.restful import reqparse from flask_rest_service import app, api, mongo from bson.objectid import ObjectId from bson.code import Code # ----- /stats ----- class Stats(restful.Resource): # ----- GET Request ----- def get(self): return Response(render_template("index.html") , mimetype='text/html') api.add_resource(Stats, '/stats')
class Reading(restful.Resource): def get(self, test_id): return mongo.db.testFeed.find_one_or_404({"_id": test_id}) def delete(self, test_id): mongo.db.testFeed.find_one_or_404({"_id": test_id}) mongo.db.testFeed.remove({"_id": test_id}) return '', 204 class Root(restful.Resource): def get(self): return { 'status': 'OK', 'mongo': str(mongo.db), } class Add(restful.Resource): def get(self): return { 'status': 'OK', 'mongo': str(mongo.db), } api.add_resource(Root, '/') api.add_resource(ReadingList, '/testFeed/') api.add_resource(Reading, '/testFeed/<ObjectId:test_id>')
@app.route('/getFeedback/') def getFeedback(): res = {'status': 0, 'entries': [x for x in mongo.db.feedbacks.find()]} print(res) return res class MyFeedback(restful.Resource): def get(self): res = {'status': 0, 'entries': [x for x in mongo.db.feedbacks.find()]} return res api.add_resource(MyFeedback, '/myfeedback/') api.add_resource(ReadingList, '/readings/') api.add_resource(Reading, '/readings/<ObjectId:reading_id>') from urlparse import urljoin from werkzeug.contrib.atom import AtomFeed def make_external(url): return urljoin(request.url_root, url) @app.route('/recent.atom') def recent_feed(): feed = AtomFeed('dailyfx summary', feed_url=request.url,
return mongo.db.person.find_one({"_id": person_id}) class Person(restful.Resource): def get(self, person_id): return mongo.db.person.find_one_or_404({"_id": person_id}) def delete(self, person_id): mongo.db.person.find_one_or_404({"_id": person_id}) mongo.db.person.remove({"_id": person_id}) return '', 204 def put(self, person_id): mongo.db.person.find_one_or_404({"_id": person_id}) args = parser.parse_args() print args mongo.db.person.update({"_id": person_id}, args); return args, 201 class Root(restful.Resource): def get(self): return { 'status': 'OK', 'mongo': str(mongo.db), } api.add_resource(Root, '/') api.add_resource(Persons, '/persons') api.add_resource(Person, '/persons/<ObjectId:person_id>')
import json from flask import request, abort from flask.ext import restful from flask.ext.restful import reqparse from flask_rest_service import app, api from src.models.accommodation.image.AccommodationImageService import AccommodationImageService class Root(restful.Resource): def get(self): return { 'status': 'OK' } class AccommodationImageServiceEndPoint(restful.Resource): def __init(self): self.service = AccommodationImageService() def get(self): parser = reqparse.RequestParser() parser.add_argument('img') args = parser.parse_args() prediction = self.service.predict(args['img']) return { 'status': 'OK', 'args': args, 'prediction': prediction } api.add_resource(Root, '/') api.add_resource(AccommodationImageServiceEndPoint, '/accommodation/image/classify/') #api.add_resource(Reading, '/readings/<ObjectId:reading_id>')