コード例 #1
0
ファイル: __init__.py プロジェクト: planlos/pl-mediaservice
def create_app(package_name=__name__, settings_override=None, **kwargs):
    app = Flask(package_name, **kwargs)
    app.config.from_object('mediaservice.config.Config')
    app.config.from_pyfile('settings.cfg', silent=True)
    app.config.from_object(settings_override)
    restapi = restful.Api(app,
                          decorators=[cors.crossdomain(origin='*', methods='*',
                                                       headers='Origin, X-Requested-With, Content-Type, Accept, Options')])
    restapi.add_resource(Media_Api, '/<cmd>', '/', endpoint='media')
    restapi.add_resource(Media_Object_Api,
                         '/o/<sha224hash>/_status',
                         '',
                         endpoint='media')
    return app
コード例 #2
0
ファイル: api.py プロジェクト: vchepeli/talks
import os

from flask import Flask
from flask_restful import Resource, Api
from flask.ext.restful.utils import cors

from db import PostgreSQL

app = Flask(__name__)
api = Api(app)
api.decorators = [cors.crossdomain(
    origin="*", headers=['accept', 'Content-Type'],
    methods=['HEAD', 'OPTIONS', 'GET', 'PUT', 'POST', 'DELETE'])]

class BlastImage(Resource):

    def __init__(self):
        if 'BLAST_IMAGE_DB_SERVICE_HOST' in os.environ:
            self._db = PostgreSQL(os.environ['POSTGRESQL_USER'], \
                os.environ['POSTGRESQL_PASSWORD'], \
                os.environ['BLAST_IMAGE_DB_SERVICE_HOST'], \
                os.environ['BLAST_IMAGE_DB_SERVICE_PORT'])
        else:
            self._db = PostgreSQL('user', 'password', 'localhost', '5432')

    def get(self, tag):
        items = []
        for obj in self._db.get(tag):
            items.append({'tag': obj['tag'], 'image': obj['image']})
        return items
コード例 #3
0
ファイル: __init__.py プロジェクト: cstaylor/maproulette
}

action_fields = {
    'task': fields.String(attribute='task_id'),
    'timestamp': fields.DateTime,
    'status': fields.String,
    'user': fields.String(attribute='user_id')
}

user_summary = {
    'id': fields.Integer,
    'display_name': fields.String
}

api = Api(app)
api.decorators = [cors.crossdomain(origin=app.config['METRICS_URL'])]

# override the default JSON representation to support the geo objects


class ApiPing(Resource):

    """a simple ping endpoint"""

    def get(self):
        return ["I am alive"]


class ApiChallenge(ProtectedResource):

    @marshal_with(challenge_summary)
コード例 #4
0
        # Handle Full convention until fields masks make it in
        if classname.endswith('Full'):
            classname = classname[:-4]

        resolved = getattr(models, classname, None)
        if not resolved or not issubclass(resolved, models.db.Document):
            raise ValueError('Model not found')
        return resolved


api = UDataApi(
    apiv1,
    ui=False,
    decorators=[csrf.exempt,
                cors.crossdomain(origin='*', credentials=True)],
    version='1.0',
    title='uData API',
    description='uData API',
    default='site',
    default_label='Site global namespace')


@api.representation('application/json')
def output_json(data, code, headers=None):
    '''Use Flask JSON to serialize'''
    resp = make_response(json.dumps(data), code)
    resp.headers.extend(headers or {})
    return resp

コード例 #5
0
    'lat': fields.Float,
    'lon': fields.Float,
    'radius': fields.Integer
}

action_fields = {
    'task': fields.String(attribute='task_id'),
    'timestamp': fields.DateTime,
    'status': fields.String,
    'user': fields.String(attribute='user_id')
}

user_summary = {'id': fields.Integer, 'display_name': fields.String}

api = Api(app)
api.decorators = [cors.crossdomain(origin=app.config['METRICS_URL'])]

# override the default JSON representation to support the geo objects


class ApiPing(Resource):
    """a simple ping endpoint"""
    def get(self):
        return ["I am alive"]


class ApiGetAChallenge(ProtectedResource):
    @marshal_with(challenge_summary)
    def get(self):
        """Return a single challenge"""
        c = None
コード例 #6
0
from data.models import Kodemon

from elasticsearch import Elasticsearch
from flask.ext.restful.utils import cors
"""
Flask server runs default on port: 5000
"""

# Get access to database
session = Session()

# Create an instance of Flask
app = Flask(__name__)
api = restful.Api(app)
api.decorators = [
    cors.crossdomain(origin='*', headers=['accept', 'Content-Type'])
]

# Set up elasticsearch connection
es = Elasticsearch()


# Format SQL query to list
def kodemonToList(qr):
    result = []

    #for every row found in the query we construct a dictionary and add to the result list
    for i in range(0, len(qr)):
        result.append({
            'id': qr[i].id,
            'execution_time': qr[i].execution_time,
コード例 #7
0
class TalksAPI(Resource):
    """
    PUT, PATCH, and DELETE will return 405 Method Not Allowed
    """

    def get(self):
        return jsonify({"data": talks})

    def post(self):
        json_data = json.loads(request.data)
        new_id = uuid.uuid4()
        json_data['id'] = new_id
        talks.append(json_data)
        return jsonify({"id": json_data['id']})

    def options(self):
        """
        Only referenced here to account for a possible pre-flight being asked
        for by browsers
        """
        return ""


api.decorators = [cors.crossdomain(origin='*', headers=['accept', 'Content-Type', 'X-Requested-With'])]
api.add_resource(TalksAPI, '/api/talks', endpoint='talks')
api.add_resource(TalksEntryAPI, '/api/talks/<id>', endpoint='talks_entry')


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
コード例 #8
0
#!flask/bin/python

"""Alternative version of the ToDo RESTful server implemented using the
Flask-RESTful extension."""

from flask import Flask, jsonify, abort, request, make_response, url_for
from flask.views import MethodView
from flask.ext.restful import Api, Resource, reqparse, fields, marshal
from flask.ext.httpauth import HTTPBasicAuth
from flask.ext.restful.utils import cors

app = Flask(__name__, static_url_path = "")
api = Api(app)
api.decorators=[cors.crossdomain(origin='*')]
auth = HTTPBasicAuth()
 
@auth.get_password
def get_password(username):
    if username == 'miguel':
        return 'python'
    return None
 
@auth.error_handler
def unauthorized():
    return make_response(jsonify( { 'message': 'Unauthorized access' } ), 403)
    # return 403 instead of 401 to prevent browsers from displaying the default auth dialog
    
tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
コード例 #9
0
ファイル: __init__.py プロジェクト: joalisson/flask-bcrypt-2
#-*-encoding:utf-8-*-
from flask import Flask, request
from flask import Blueprint
from flask.ext import restful
from flask.ext.restful.utils import cors
from database import db


api = restful.Api()
blueprint = Blueprint('hello_blueprint', __name__)
api.init_app(blueprint)
blueprint.config = {}
api.decorators = [cors.crossdomain(origin='*', headers=["Authorization", "Content-Type"])]


class UserModule:

    def __init__(self, *args, **kwargs):
        if len(args) > 0:
            url_prefix = kwargs.get('url_prefix', '/api')
            self.init_app(args[0], url_prefix=url_prefix)

    def init_app(self, app, url_prefix='/api'):
        db.init_app(app)
        app.register_blueprint(blueprint, url_prefix=url_prefix)


# Declaração das Rotas da API

from users import ListUsersRest
コード例 #10
0
ファイル: app.py プロジェクト: gonboy/flask-user-api
from api.profileAPI import ProfileAPI, ProfileIconAPI, SearchProfileAPI
from api.friendsAPI import FriendsListAPI, FriendsRequestAPI
from api.passwordAPI import ChangePasswordAPI, ForgetPasswordAPI
from api.postAPI import PostAPI

# load configuration and bootstrap flask
app = Flask(__name__)
app.config.from_object('config')

db.init_app(app)
bcrypt.init_app(app)
redis_store.init_app(app)
mail = Mail(app)

api = Api(app)
api.decorators = [cors.crossdomain(origin='*',
                                   headers='my-header, accept, content-type, token')]

# add endpoints to flask restful api 
api.add_resource(UserAPI, '/create_user')
api.add_resource(LoginAPI, '/login')
api.add_resource(FBUserAPI, '/fb_create_user')
api.add_resource(FBLoginAPI, '/fb_login')
api.add_resource(ActivateAPI, '/activate_account')

api.add_resource(ChangePasswordAPI, '/change_password')
api.add_resource(ForgetPasswordAPI, '/forget_password')

api.add_resource(ProfileAPI, '/profile')
api.add_resource(ProfileIconAPI, '/upload_profile_icon')
api.add_resource(SearchProfileAPI, '/search_profile')
コード例 #11
0
ファイル: appcli.py プロジェクト: sadig/DC2
#!/usr/bin/env python

import xmlrpclib

from dc2.web.live.startup import app
from dc2.web.live.startup import socketio
from flask.ext.restful.utils import cors


from dc2.web.live.api.v1.rest_dhcp import *  # noqa
from dc2.web.live.api.v1.rest_events import *  # noqa
from dc2.web.live.socket_handlers.clients import *  # noqa
from dc2.web.live.socket_handlers.commands import *  # noqa

app.config["DC2Backend"] = xmlrpclib.ServerProxy("http://dc2db.lax-stg1.stg.gaikai.net/RPC", allow_none=True)

if __name__ == "__main__":

    api.init_app(app)
    api.method_decorators = [cors.crossdomain(origin="*", automatic_options=True)]

    socketio.init_app(app)
    socketio.run(app, heartbeat_interval=2, heartbeat_timeout=5)
コード例 #12
0
ファイル: extensions.py プロジェクト: Regner/evecomments
""" Each extension is initialized in the application factory. """

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from flask.ext.restful import Api
from flask.ext.restful.utils.cors import crossdomain
api = Api(decorators=[crossdomain(origin='*')])

from flask.ext.login         import LoginManager
login_manager = LoginManager()

from flask_oauthlib.client import OAuth
oauth  = OAuth()
from api.tournamentAPI import CreateTournamentAPI, JoinTournamentAPI, TournamentResultAPI, ViewTournamentAPI
from api.reportAPI import LolReportAPI
from api.postAPI import PlayerPostAPI, TeamPostAPI
from api.challongeAPI import ChallongeAPI,ChallongeJoinAPI,ChallongeResultAPI
from util.exception import InvalidUsage

app = Flask(__name__)
app.config.from_object('config') 

db.init_app(app)
bcrypt.init_app(app)
redis_store.init_app(app)
mail = Mail(app)

api = Api(app)
api.decorators = [cors.crossdomain(origin='*',
                                   headers='my-header, accept, content-type, token')]

api.add_resource(UserAPI, '/create_user')
api.add_resource(LoginAPI, '/login')
api.add_resource(FBUserAPI, '/fb_create_user')
api.add_resource(FBLoginAPI, '/fb_login')
api.add_resource(ActivateAPI, '/activate_account')

api.add_resource(ChangePasswordAPI, '/change_password')
api.add_resource(ForgetPasswordAPI, '/forget_password')

api.add_resource(ProfileAPI, '/profile')
api.add_resource(ProfileIconAPI, '/upload_profile_icon')
api.add_resource(FindProfileAPI, '/search_profile')
api.add_resource(ViewProfileAPI, '/view_profile/<int:profileID>')
コード例 #14
0
ファイル: __init__.py プロジェクト: sftech2013/live
Twitter
"""

from twitter.service import Twitter
TW_Client = Twitter(config=app.config)


"""
Configuration API Flask-Restful
"""

DEFAULT_REPRESENTATIONS = {'application/json': output_json}

api = Api(app)
api.representations = DEFAULT_REPRESENTATIONS
api.decorators=[cors.crossdomain('*')]

from resources.prefs import Preferences
from resources.message import Msg, MsgList, Sms
from resources.race import Race, RaceList
from resources.dumber import Dumber, DumberList
from resources.theme import ThemeList, Themer, ThemeUpload, ThemeS3, ThemeS3List
# from resources.timeline import Timeline

# @FIXME: les endpoints c juste n'importe quoi ...
api.add_resource(Preferences, 	'/admin/prefs/', endpoint = 'prefs')
api.add_resource(MsgList, 		'/messages/<string:race_id>', endpoint='messages')
api.add_resource(Msg, 			'/message/<string:msg_id>', endpoint='message')
api.add_resource(Sms, 			'/messages/sms/')  	# POST
api.add_resource(RaceList, 		'/races/', endpoint = 'races')
api.add_resource(Race, 			'/races/<string:race_id>', endpoint = 'race')
コード例 #15
0
ファイル: web.py プロジェクト: wragge/closedaccess-web
from flask_restful import fields, marshal_with, reqparse, inputs
from flask.ext.restful.utils import cors
from flask.ext.paginate import Pagination
import random
from bson.son import SON
import os
import datetime
from dateutil.parser import *


MONGOLAB_URL = os.environ['MONGOLAB_URL']
DEFAULT_HARVEST_DATE = datetime.datetime(2016, 1, 1, 0, 0, 0)

app = Flask(__name__)
api = Api(app)
api.decorators = [cors.crossdomain(origin='*', methods=['GET'],)]

REASONS = {
    '33(1)(a)': {'definition': 'contains information or matter the disclosure of which under this Act could reasonably be expected to cause damage to the security, defence or international relations of the Commonwealth', 'source': 'act'},
    '33(1)(b)': {'definition':  'contains information or matter: (i) that was communicated in confidence by, or on behalf of, a foreign government, an authority of a foreign government or an international organisation (the foreign entity) to the Government of the Commonwealth, to an authority of the Commonwealth or to a person who received the communication on behalf of the Commonwealth or an authority of the Commonwealth (the Commonwealth entity); and (ii) which the foreign entity advises the Commonwealth entity is still confidential; and (iii) the confidentiality of which it would be reasonable to maintain', 'source': 'act'},
    '33(1)(c)': {'definition': 'contains information or matter the disclosure of which under this Act would have a substantial adverse effect on the financial or property interests of the Commonwealth or of a Commonwealth institution and would not, on balance, be in the public interest', 'source': 'act'},
    '33(1)(d)': {'definition': 'contains information or matter the disclosure of which under this Act would constitute a breach of confidence', 'source': 'act'},
    '33(1)(e)(i)': {'definition': 'contains information or matter the disclosure of which under this Act would, or could reasonably be expected to prejudice the conduct of an investigation of a breach, or possible breach, of the law, or a failure, or possible failure, to comply with a law relating to taxation or prejudice the enforcement or proper administration of the law in a particular instance', 'source': 'act'},
    '33(1)(e)(ii)': {'definition': 'contains information or matter the disclosure of which under this Act would, or could reasonably be expected to disclose, or enable a person to ascertain, the existence or identity of a confidential source of information in relation to the enforcement or administration of the law', 'source': 'act'},
    '33(1)(e)(iii)': {'definition': 'contains information or matter the disclosure of which under this Act would, or could reasonably be expected to endanger the life or physical safety of any person', 'source': 'act'},
    '33(1)(f)(ii)': {'definition': 'contains information or matter the disclosure of which under this Act would, or could reasonably be expected to disclose lawful methods or procedures for preventing, detecting, investigating, or dealing with matters arising out of, breaches or evasions of the law the disclosure of which would, or would be reasonably likely to, prejudice the effectiveness of those methods or procedures', 'source': 'act'},
    '33(1)(f)(iii)': {'definition': 'contains information or matter the disclosure of which under this Act would, or could reasonably be expected to prejudice the maintenance or enforcement of lawful methods for the protection of public safety', 'source': 'act'},
    '33(1)(g)': {'definition': 'contains information or matter the disclosure of which under this Act would involve the unreasonable disclosure of information relating to the personal affairs of any person (including a deceased person)', 'source': 'act'},
    '33(1)(h)': {'definition': 'contains information or matter relating to trade secrets, or any other information or matter having a commercial value that would be, or could reasonably be expected to be, destroyed or diminished if the information or matter were disclosed', 'source': 'act'},
    '33(1)(j)': {'definition': 'contains information or matter (other than information or matter referred to in paragraph (h)) concerning a person in respect of his or her business or professional affairs or concerning the business, commercial or financial affairs of an organization or undertaking, being information or matter the disclosure of which would, or could reasonably be expected to, unreasonably affect that person adversely in respect of his or her lawful business or professional affairs or that organization or undertaking in respect of its lawful business, commercial or financial affairs', 'source': 'act'},
    '33(2)(a)': {'definition': 'of such a nature that it would be privileged from production in legal proceedings on the ground of legal professional privilege', 'source': 'act'},
コード例 #16
0
ファイル: api.py プロジェクト: bjarniegill/CodeMon
from data.models import Kodemon

from elasticsearch import Elasticsearch
from flask.ext.restful.utils import cors

"""
Flask server runs default on port: 5000
"""

# Get access to database
session = Session()

# Create an instance of Flask
app = Flask(__name__)
api = restful.Api(app)
api.decorators = [cors.crossdomain(origin='*', headers=['accept', 'Content-Type'])]

# Set up elasticsearch connection
es = Elasticsearch()


# Format SQL query to list
def kodemonToList(qr):
    result = []

    #for every row found in the query we construct a dictionary and add to the result list
    for i in range(0, len(qr)):
        result.append({'id': qr[i].id,
                       'execution_time': qr[i].execution_time,
                       'timestamp': qr[i].timestamp,
                       'token': qr[i].token,
コード例 #17
0
ファイル: api.py プロジェクト: janakmayer/ScalingUp
from flask import Flask
from flask.ext.restful import Api, Resource, reqparse
from flask.ext.restful.utils import cors
from flask.ext.runner import Runner
from api_functions import download_parse
import os
import json

app = Flask(__name__)
runner = Runner(app)
api = Api(app)
api.decorators = [cors.crossdomain(origin='*')]

parser = reqparse.RequestParser()
parser.add_argument('start', type=int)
parser.add_argument('end', type=int)
parser.add_argument('api_key', type=str)
parser.add_argument('word', type=str)

bi_gram = None


def load_bigram():
    with open('bi_gram.json', 'r') as json_file:
        global bi_gram
        bi_gram = json.load(json_file)
        json_file.close()


# API CLASSES
class GetData(Resource):
コード例 #18
0
ファイル: webmc.py プロジェクト: thpani/webmc-server
#!/usr/bin/env python

from uuid import uuid4

from flask import Flask, request
from flask.ext.restful import abort, Api, Resource
from flask.ext.restful.utils import cors

from tools import Echo, Minisat

app = Flask(__name__)
api = Api(app)
api.decorators = [
    cors.crossdomain(origin='*', headers='Content-Type')
]

JOBS = {}
TOOLS = [ Echo(), Minisat() ]

def abort_if_tool_doesnt_exist(tool_id):
    try:
        return next( t for t in TOOLS if t.name == tool_id )
    except StopIteration:
        abort(404, message="Tool {} doesn't exist".format(tool_id))

def abort_if_job_doesnt_exist(job_id):
    try:
        return JOBS[job_id]
    except KeyError:
        abort(404, message="Job {} doesn't exist".format(job_id))
コード例 #19
0
ファイル: __init__.py プロジェクト: grouan/udata
        response.headers['WWW-Authenticate'] = challenge
        return response

    def page_parser(self):
        parser = self.parser()
        parser.add_argument('page', type=int, default=1, location='args',
                            help='The page to fetch')
        parser.add_argument('page_size', type=int, default=20, location='args',
                            help='The page size to fetch')
        return parser


api = UDataApi(
    apiv1, ui=False,
    decorators=[csrf.exempt, cors.crossdomain(origin='*', credentials=True)],
    version='1.0', title='uData API',
    description='uData API', default='site',
    default_label='Site global namespace'
)


@api.representation('application/json')
def output_json(data, code, headers=None):
    '''Use Flask JSON to serialize'''
    resp = make_response(json.dumps(data), code)
    resp.headers.extend(headers or {})
    return resp


@apiv1.before_request
コード例 #20
0
ファイル: app.py プロジェクト: sv10/calllog211
from flask import Flask
from flask.ext.restful import Api
from flask.ext.restful.utils import cors

from api import config
from api.calllog.CallLogAPI import CallLogAPI, CallLogQuery

app = Flask(__name__)
app.config.from_object(config)

api = Api(app, decorators=[cors.crossdomain(origin='*')])

# public services
api.add_resource(CallLogAPI, CallLogAPI.route())
api.add_resource(CallLogQuery, CallLogQuery.route())