def fields(): return { 'id': fields.Integer, 'title': fields.String, 'completed': fields.Boolean, 'uri': fields.Url('item'), }
def get(self): # marshal() can also handle a list or tuple of objects, but it only # checks for a list or tuple, so we need to convert the queryset # to a list args = parser.parse_args() limit = min( args.get('limit') or current_app.config.get('PAGE_SIZE'), current_app.config.get('PAGE_SIZE')) offset = args.get('offset') or 0 queryset = services.location_types.find().skip(offset).limit(limit) dataset = marshal(list(queryset), LOCATION_TYPE_FIELD_MAPPER) for d in dataset: urlfield = fields.Url('locations.api.locationtype') d['uri'] = urlfield.output('uri', {'loc_type_id': d['id']}) result = { 'meta': { 'limit': limit, 'offset': offset, 'total': queryset.count(False) }, 'objects': dataset } return jsonify(result)
def post(self): """Create a new event and return the id and uri of the event.""" self.require_write_permission() # Set up the parser for the root of the object parser = reqparse.RequestParser() parser.add_argument('event', type=dict) pargs = parser.parse_args() event_args = util.add_nested_arguments(pargs, 'event', { 'name': str, 'location': str, 'action': str, 'value': str }) # Create the event in the database event = EventModel(self.client, event_args['name'], event_args['location'], event_args['action'], event_args['value']) # Save the event in the database db.session.add(event) db.session.commit() # Finally, convert the event object into our format by marshalling it, # and returning the JSON object # FIXME: Find out why the URI in marshalling causes problems # For now, manually create the URI eventMarshal = marshal(event, { 'id': fields.Integer, 'uri': fields.Url('events', absolute=True) }) eventMarshal['uri'] = '{0}/{1}'.format(eventMarshal['uri'], event.id) return { 'status': 201, 'message': 'Created Event', 'event': eventMarshal }, 201
def get(self, loc_type_id): # marshal() converts a custom object/dictionary/list using the mapper # into a Python dict data = marshal(services.location_types.get_or_404(pk=loc_type_id), LOCATION_TYPE_FIELD_MAPPER) # for the Url field, the constructor argument must be a full # path, because it will be converted using Flask's url_for(), # in the output() call, and if you don't give something it can # convert, it will fail with a BuildError # also, for a single item, you really don't need the url specced, # but whatever urlfield = fields.Url('locations.api.locationtype') data['uri'] = urlfield.output('uri', {'loc_type_id': data['id']}) return jsonify(data)
def post(self): """ Create an API key with specified permissions. Available permissions are: read - access to all GET requests (except API keys) write - access to all POST and GET requests (except API keys) admin - access to creating a API keys and everything else """ self.require_admin_permission() parser = reqparse.RequestParser() parser.add_argument('permission', type=str, required=True, location='json', help="A permission level needs to be specified") pargs = parser.parse_args() if pargs['permission'] not in ['read', 'write', 'admin']: raise InvalidPermissions() apikey = APIKeyModel(generate_apikey(), pargs['permission']) db.session.add(apikey) db.session.commit() # FIXME: Find out why the URI in marshalling causes problems # For now, manually create the URI apikeyMarshal = marshal( apikey, { 'id': fields.Integer, 'apikey': fields.String, 'permission': fields.String, 'created': fields.DateTime(dt_format='rfc822'), 'uri': fields.Url('apikeys', absolute=True) }) apikeyMarshal['uri'] = '{0}/{1}'.format(apikeyMarshal['uri'], apikey.id) return { 'status': 201, 'message': 'Created API Key', 'apikey': apikeyMarshal }, 201
__author__ = 'tauren' from flask import abort from flask_restful import Resource from flask.ext.restful import fields, marshal, reqparse from flask_login import current_user from models import User, db user_fields = { 'username': fields.String, 'id': fields.Integer, 'uri': fields.Url('user') } class UserApi(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('username', type=str, required=True, help='No username provided', location='json') self.reqparse.add_argument('password', type=str, required=True, help='No password provided', location='json') super(UserApi, self).__init__() def post(self):
from web_api.common.util import abort_if_record_doesnt_exist, get_all_records, get_record_by_ID, update_record, delete_record from web_api.models import Samples, db sample_fields = { 'vial_barcode': fields.Integer, 'experiment': fields.Integer, 'assigned_kit': fields.DateTime, 'kit': fields.Integer, 'assigned_vial': fields.DateTime, 'processed': fields.DateTime, 'received': fields.DateTime, 'analyzed': fields.DateTime, 'query_exclude': fields.Integer, 'collected': fields.DateTime, 'sequencing_revision': fields.Integer, 'uri': fields.Url('sample', absolute=True, scheme='http') } # SampleListAPI # shows a list of all samples, and lets you POST to add new sample class SampleListAPI(Resource): decorators = [auth.login_required] def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('vial_barcode', type=str) self.reqparse.add_argument('experiment', type=int) self.reqparse.add_argument('assigned_kit', type=str) self.reqparse.add_argument('kit', type=int) self.reqparse.add_argument('assigned_vial', type=str)
url = Column(Text, unique=True) descripcion = Column(Text, unique=False) #categoria_id = Column(Integer, db.ForeignKey('categoria.id')) def __init__(self, url, descripcion): self.url = url self.descripcion = descripcion db.create_all() link_fields = { 'descripcion': fields.String, 'url': fields.String, 'uri': fields.Url('link') } class LinkListAPI(Resource): def get(self): links = Link.query.all() return {'links': [marshal(link, link_fields) for link in links]} def post(self): link_url = request.json['url'] link_descripcion = request.json['descripcion'] link = Link(link_url, link_descripcion) db.session.add(link) db.session.commit() return {'link': marshal(link, link_fields)}, 201
from flask.ext.restful import reqparse from flask.ext.restful import abort from flask.ext.restful import Resource from flask.ext.restful import fields from flask.ext.restful import marshal_with from sqlalchemy import func account_fields = { 'account_id': fields.Integer, 'account_name': fields.String, 'account_type': fields.String, 'account_status': fields.String, 'account_balance': fields.String, 'create_timestamp': fields.DateTime, 'uri': fields.Url('account', absolute=True), } parser = reqparse.RequestParser() parser.add_argument('account_name', type=str) class AccountResource(Resource): @marshal_with(account_fields) def get(self, account_name): account = session.query(Account).filter( func.lower(Account.account_name) == func.lower( account_name)).first() if not account: abort(404, message="Account {} doesn't exist".format(account_name)) return account
from models import Student, Subject # from models import Todo from db import session from flask.ext.restful import reqparse from flask.ext.restful import abort from flask.ext.restful import Resource from flask.ext.restful import fields from flask.ext.restful import marshal_with todo_fields = { 'id': fields.Integer, 'task': fields.String, 'uri': fields.Url('todo', absolute=True), } student_fields = { 'id': fields.Integer, 'name': fields.String, 'subjects': fields.String, # marshal subjects into a string } parser = reqparse.RequestParser() parser.add_argument('task', type=str) class StudentResource(Resource): @marshal_with(student_fields) def get(self, id): student = session.query(Student).filter(Student.id == id).first() if not student:
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 'done': False }, 2: { 'id': 2, 'title': u'Learn Python', 'description': u'Need to find a good Python tutorial on the web', 'done': False } } task_fields = { 'title': fields.String, 'description': fields.String, 'done': fields.Boolean, 'uri': fields.Url('task') } class TaskListAPI(Resource): decorators = [auth.login_required] def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('title', type=str, required=True, help='No task title provided', location='json') self.reqparse.add_argument('description', type=str,
@auth.error_handler def unauthorized(): return make_response(jsonify({'message': 'Unauthorized access'}), 403) feature_fields = { 'title': fields.String, 'description': fields.String, 'client': fields.String, 'client_priority': fields.Integer, 'target_date': fields.DateTime(dt_format='rfc822'), 'product_area': fields.String, 'uri': fields.Url('feature') } client_fields = {'name': fields.String, 'uri': fields.Url('client')} class FeatureListAPI(Resource): decorators = [auth.login_required] def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('title', type=str, required=True, help='No feature title provided', location='json')
from flask import jsonify, url_for, request, make_response from flask.ext.restful import reqparse, abort, Api, Resource, fields, marshal from web_api.resources import auth from web_api.common.util import abort_if_record_doesnt_exist, get_all_records, get_record_by_ID, update_record, delete_record from web_api.models import Taxa, db taxa_fields = { 'tax_rank': fields.String, 'tax_name': fields.String, 'tax_color': fields.String, 'parent': fields.Integer, 'superkingdom': fields.Integer, 'reads': fields.Integer, 'uri': fields.Url('taxon', absolute=True, scheme='http') } class TaxaListAPI(Resource): decorators = [auth.login_required] def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('tax_rank', type = str) self.reqparse.add_argument('tax_name', type = str) self.reqparse.add_argument('tax_color', type = str) self.reqparse.add_argument('parent', type = int) self.reqparse.add_argument('superkingdom', type = int) self.reqparse.add_argument('reads', type = int) super(TaxaListAPI, self).__init__()
todo_id = 'todo%i' % todo_id TODO[todo_id] = {'task' :args['task']} return TODOS[todo_id], 201 api.add_resource(TodoList, '/todos', '/all_tasks') class TodoDao(object): def __init__(self, todo_id, task): self.todo_id = todo_id self.task = task self.status = 'active' resource_fields = { 'task': fields.String, 'uri' : fields.Url('todo_ep') } class Todo(Resource): @marshal_with(resource_fields): def get(self, todo_id): return TodoDao(todo_id=todo_id, task='Remeber the milk'), 200 api.add_resource(Todo, '/todos/<todo_id>', endpoint='todo_ep') if __name__ == '__main__': app.run(debug=True)
audit_containers() @auth.get_password def get_pw(username): """Returns the password specified in 'SPIN_DOCKER_PASSWORD'.""" return users.get(username) container_fields = { 'container_id': fields.String, 'name': fields.String, 'image': fields.String, 'ssh_port': fields.String, 'app_port': fields.String, 'status': fields.String, 'active': fields.String, 'uri': fields.Url('container'), } def abort_if_container_doesnt_exist(container_id): """Checks that a container is found before proceeding with a request.""" if not r.exists('containers:%s' % container_id): abort(404, message="Container %s doesn't exist" % container_id) class ImageList(Resource): decorators = [auth.login_required, ] def __init__(self): self.reqparse = reqparse.RequestParser() super(ImageList, self).__init__()
from flask.ext.restful import reqparse from flask.ext.restful import abort from flask.ext.restful import Resource from flask.ext.restful import fields from flask.ext.restful import marshal_with from sqlalchemy import func transaction_fields = { 'transaction_id': fields.Integer, 'instrument_name': fields.String, 'transaction_type': fields.String, 'transaction_dt': fields.DateTime, 'net_transaction_amt': fields.Integer, 'transaction_qty': fields.Integer, 'account_id': fields.Integer, 'uri': fields.Url('transaction', absolute=True), } parser = reqparse.RequestParser() parser.add_argument('transaction_type', type=str) parser.add_argument('account_id', type=str) class TransactionResource(Resource): @marshal_with(transaction_fields) def get(self, transaction_type): transaction = session.query(Transaction).filter( func.lower(Transaction.transaction_type) == func.lower( transaction_type)).all() if not transaction: abort(404,
from flask.ext.restful import Resource, reqparse, marshal, fields from flask.ext.httpauth import HTTPBasicAuth from flask import request from app import models, db, api from models import User, Feed auth = HTTPBasicAuth() feed_fields = { 'title': fields.String, 'uri': fields.String, 'url': fields.Url('feed'), 'id': fields.String } class FeedApi(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('title', type = str, location = 'json') self.reqparse.add_argument('description', type = str, location = 'json') self.reqparse.add_argument('done', type = bool, location = 'json') super(FeedApi, self).__init__() def post(self,id): if(authenticate_user(request.form['username'], request.form['password'])): user=models.User.query.filter_by(name=request.form['username']).first() # id = int(request.form['id']) for feed in user.feeds: if feed.id == id: return {'feed': marshal(feed,feed_fields)}
api = Api(app) CORS(app) url = os.environ.get('GRAPHENEDB_URL', 'http://localhost:7474') username = os.environ.get('NEO4J_USERNAME') password = os.environ.get('NEO4J_PASSWORD') if username and password: authenticate(url.strip('http://'), username, password) graph = Graph(url + '/db/data/') tree_fields = { 'name': fields.String, 'descr': fields.String, 'people': fields.Url('persons', absolute=True, scheme='https'), 'uri': fields.Url('tree', absolute=True, scheme='https') } person_fields = { 'name': fields.String, 'dob': fields.String, 'sex': fields.String, 'parents': fields.Url('parents', absolute=True, scheme='https'), 'siblings': fields.Url('siblings', absolute=True, scheme='https'), 'children': fields.Url('children', absolute=True, scheme='https'), 'uri': fields.Url('person', absolute=True, scheme='https') } class TreeListApi(Resource):
kit_fields = { 'user': fields.Integer, 'mailinglabel': fields.Integer, 'assembled': fields.DateTime(default=None), 'registered': fields.DateTime(default=None), 'barcode': fields.String, 'order_id': fields.Integer, 'kit_type': fields.Integer, 'survey_page': fields.Integer, 'survey_completed': fields.DateTime(default=None), 'registration_override': fields.Integer, 'tubesReceived': fields.DateTime(default=None), 'processed': fields.DateTime(default=None), 'analyzed': fields.DateTime(default=None), 'last_reminder': fields.DateTime(default=None), 'uri': fields.Url('kit', absolute=True, scheme='http') } # KitListAPI # shows a list of all kits, and lets you POST to add new kit class KitListAPI(Resource): decorators = [auth.login_required] def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('user', type=int) self.reqparse.add_argument('mailinglabel', type=int) self.reqparse.add_argument('assembled', type=str) self.reqparse.add_argument('registered', type=str) self.reqparse.add_argument('barcode', type=str)
return value.isoformat() user = { 'id': fields.Integer, 'image': fields.String, 'name': fields.String, 'updated_at': DateTimeField, 'created_at': DateTimeField } event = { 'id': fields.Integer, 'url': fields.Url('event'), 'title': fields.String, 'image': fields.String, 'images': fields.List(fields.String), 'summary': fields.List(fields.Nested({ 'sentence': fields.String, 'source': fields.String, 'url': fields.String }), attribute='summary_sentences'), 'score': fields.Float,
from models import Team from flask_restful import Resource from flask import abort from flask.ext.restful import fields, marshal athlete_fields = { 'id': fields.Integer, 'name': fields.String, 'uri': fields.Url('athletes') } team_fields = { 'id': fields.Integer, 'name': fields.String, 'captain': fields.String, 'athletes': fields.List(fields.Nested(athlete_fields)), 'uri': fields.Url('teams_list') } class TeamsListAPI(Resource): def __init__(self): super(TeamsListAPI, self).__init__() def get(self): team_records = Team.query.all() if not team_records: return abort(404) return {'results': marshal(team_records, team_fields)}
places = [{ 'id': 1, 'title': u'Your House', 'description': u'Where we go to play!' }, { 'id': 2, 'title': u'My House', 'description': u'Where we go to stay!' }] #db.collection.insert(places)#seed database place_fields = { 'title': fields.String, 'description': fields.String, 'uri': fields.Url('place'), '_id': fields.String } class PlaceListAPI(Resource): # decorators = [auth.login_required] def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('title', type=str, required=True, help='No place title provided', location='json') self.reqparse.add_argument('description',
from models import Athlete from flask_restful import Resource from flask import abort from flask.ext.restful import fields, marshal import json athlete_fields = { 'id': fields.Integer, 'name': fields.String, 'uri': fields.Url('athletes') } class StrongestAthletesAPI(Resource): def __init__(self): super(StrongestAthletesAPI, self).__init__() def get(self): athlete_records = Athlete.query.all() for athlete in athlete_records: total_pounds = 0 if athlete.clean_and_jerk: total_pounds += int(athlete.clean_and_jerk) if athlete.snatch: total_pounds += int(athlete.snatch) if athlete.deadlift: total_pounds += int(athlete.deadlift) if athlete.back_squat: total_pounds += int(athlete.back_squat)
import datetime from flask import request from flask.ext.restful import reqparse, fields, marshal import cred.config from cred.exceptions import ClientNotFound from cred.common import util from cred.models.client import Client as ClientModel full_client_fields = { 'id': fields.Integer, 'device': fields.String, 'location': fields.String, 'uri': fields.Url('clients_item', absolute=True), } simple_client_fields = { 'id': fields.Integer, 'uri': fields.Url('clients_item', absolute=True), } class Clients(util.AuthenticatedResource): """Methods going to the /clients route.""" def get(self): """ Get a list of all active clients, based on pingtimeout configuration. Also accepts query parameters: full=<bool>
'ExtractStorageTime': fields.String, 'ThermocycleStartTime': fields.String, 'PCRProductTubeId': fields.String, 'PCRProductScanTime': fields.String, 'qBitData': fields.String, 'DCCPlateStorageTime': fields.String, 'labChippedTubeId': fields.String, 'labChippedProductScanTime': fields.String, 'PCRProductTubeStorageTime': fields.Integer, 'FinalLibraryAliquatTime': fields.String, 'labChippedTubeStorageTime': fields.String, 'seqRunName': fields.String, 'seqRunId': fields.Integer, 'active_at_robot': fields.Integer, 'uri': fields.Url('lab_pipeline_tracking', absolute=True, scheme='http') } # LabPipelineTracingListAPI # shows a list of all lab_pipeline_tracking, and lets you POST to add new lab_pipeline_tracking class LabPipelineTracingListAPI(Resource): decorators = [auth.login_required] def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('PRID', type = str) self.reqparse.add_argument('StartTime', type = str) self.reqparse.add_argument('primerPlateId', type = str) self.reqparse.add_argument('PCRSetupStartTime', type = str) self.reqparse.add_argument('PCRPlateBarcode', type = str)
""" Here we define marshaling, which map python dicts to JSON """ from flask.ext.restful import fields comment_fields = { "id": fields.String, "body": fields.String, "upvotes": fields.Integer, "downvotes": fields.Integer, "myvote": fields.Integer, "upvote_url": fields.Url(endpoint="upvote_ep"), "downvote_url": fields.Url(endpoint="downvote_ep"), 'url': fields.Url(endpoint='comment_ep') } post_fields = { "id": fields.String, "title": fields.String, "body": fields.String, "author": fields.String, "upvotes": fields.Integer, "myvote": fields.Integer, "downvotes": fields.Integer, "comments": fields.List(fields.Nested(comment_fields)), "upvote_url": fields.Url(endpoint="upvote_ep"), "downvote_url": fields.Url(endpoint="downvote_ep"), 'url': fields.Url(endpoint='post_ep') } subreddit_fields = {
from ngssm import app, auth, api from flask import request, url_for, abort from flask.ext.restful import Resource, reqparse, fields, marshal from math import ceil from ngssm.entities.run import Run run_fields = { 'type': fields.String, 'mid_set': fields.String, 'plate': fields.String, 'uri': fields.Url('run') } run_uris = { 'uri': fields.Url('run') } class RunAPI(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('type', type = str, location = 'json') self.reqparse.add_argument('mid_set', type = str, location = 'json') self.reqparse.add_argument('plate', type = str, location = 'json') super(RunAPI, self).__init__(); @auth.login_required def get(self, id): session = app.session_maker() run = session.query(Run).filter_by(id=id).first(); print "Run id: ", id, " Run: ", run if run == None:
from web_api.resources import auth from web_api.models import UserSurvey, db from web_api.common.util import abort_if_record_doesnt_exist, get_all_records, get_record_by_ID, update_record, delete_record user_fields = { 'user': fields.Integer, 'dob': fields.String, 'city_and_country': fields.String, 'gender': fields.String, 'race': fields.String, 'allow_data_comparison': fields.String, 'term_of_service': fields.String, 'privacy_policy': fields.String, 'induction_completed': fields.String, 'service_consent': fields.String, 'uri': fields.Url('user_survey', absolute=True, scheme='http') } # UserSurveyListAPI # shows a list of all user surveys, and lets you POST to add new user user survey class UserSurveyListAPI(Resource): #decorators = [auth_token_required] def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('user', type=int) self.reqparse.add_argument('dob', type=str) self.reqparse.add_argument('city_and_country', type=str) self.reqparse.add_argument('gender', type=str) self.reqparse.add_argument('race', type=str)
from ngssm import app, auth, api from flask import request, url_for, abort from flask.ext.restful import Resource, reqparse, fields, marshal from ngssm.entities.sample import Sample sample_fields = { 'run_id': fields.Integer, 'mid': fields.String, 'target': fields.String, 'sff': fields.String, 'location': fields.String, 'sample': fields.String, 'primer_forward': fields.String, 'primer_reverse': fields.String, 'uri': fields.Url('sample') } sample_uris = {'uri': fields.Url('sample')} class SampleAPI(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('run_id', type=int, location='json') self.reqparse.add_argument('mid', type=str, location='json') self.reqparse.add_argument('target', type=str, location='json') self.reqparse.add_argument('sff', type=str, location='json') self.reqparse.add_argument('location', type=str, location='json') self.reqparse.add_argument('sample', type=str, location='json') self.reqparse.add_argument('primer_forward', type=str, location='json')
from web_api.common.util import abort_if_record_doesnt_exist, get_all_records, get_record_by_ID, update_record, delete_record from web_api.models import LabSampleLoading, db lab_sample_loading_fields = { 'tubeId': fields.String, 'PRID': fields.String, 'Extraction_Rack_Number': fields.String, 'Extraction_Rack_Loaction': fields.String, 'Extraction_Rack_Scan_Time': fields.String, 'pipeline_tracking_record': fields.Integer, 'originFileName': fields.String, 'sample': fields.Integer, 'taxondata_loaded': fields.DateTime, 'pipeline_rev': fields.Integer, 'latestRev2': fields.Integer, 'uri': fields.Url('lab_sample_loading', absolute=True, scheme='http') } # LabSampleLoadingListAPI # shows a list of all lab_sample_loading, and lets you POST to add new lab_sample_loading class LabSampleLoadingListAPI(Resource): decorators = [auth.login_required] def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('tubeId', type=str) self.reqparse.add_argument('PRID', type=str) self.reqparse.add_argument('Extraction_Rack_Number', type=str) self.reqparse.add_argument('Extraction_Rack_Loaction', type=str) self.reqparse.add_argument('Extraction_Rack_Scan_Time', type=str)