Exemple #1
1
def main():
    cfg.CONF(sys.argv[1:])

    # If the user and/or group are specified in config file, we will use
    # them as configured; otherwise we try to use defaults depending on
    # distribution. Currently only supporting ubuntu and redhat.
    qemu_user = cfg.CONF.ml2_vpp.qemu_user
    qemu_group = cfg.CONF.ml2_vpp.qemu_group
    default_user, default_group = get_qemu_default()
    if not qemu_user:
        qemu_user = default_user
    if not qemu_group:
        qemu_group = default_group

    global vppf

    physnet_list = cfg.CONF.ml2_vpp.physnets.replace(' ', '').split(',')
    physnets = {}
    for f in physnet_list:
        (k, v) = f.split(':')
        physnets[k] = v

    vppf = VPPForwarder(app.logger,
                        physnets,
                        vxlan_src_addr=cfg.CONF.ml2_vpp.vxlan_src_addr,
                        vxlan_bcast_addr=cfg.CONF.ml2_vpp.vxlan_bcast_addr,
                        vxlan_vrf=cfg.CONF.ml2_vpp.vxlan_vrf,
                        qemu_user=qemu_user,
                        qemu_group=qemu_group)

    api = Api(app)
    api.add_resource(PortBind, '/ports/<id>/bind')
    api.add_resource(PortUnbind, '/ports/<id>/unbind')
    app.run(host='0.0.0.0', port=2704)
Exemple #2
0
class LabyrinthServer(object) :
    def __init__(self, configFile) :
        self.app = Flask(__name__)
        self.api = Api(self.app)
        logging.debug("opening config file %s for reading" % configFile)
        try :
            fp = open(configFile, 'r')
            self.config = json.load(fp)
            fp.close()
        except IOError :
            logging.critical("Unable to open the config file %s for reading" % configFile)
            exit(10)
        except ValueError :
            logging.critical("Unable to read the JSON object in the config file %s" % configFile)
            exit(10)

        try :
            for endpoint in self.config['endpoints'] :
                if self.config['endpoints'][endpoint] == "JobRunner" :
                    self.api.add_resource(JobRunner, endpoint)
                    logging.info("Created JobRunner endpoint for "+endpoint)
                elif self.config['endpoints'][endpoint] == "JobManager" :
                    self.api.add_resource(JobManager, endpoint)
                    logging.info("Created JobManager endpoint for "+endpoint)
                else :
                    logging.error("Unknown class for endpoint '%s'.  No Class '%s' exists" % (endpoint,self.config['endpoints'][endpoint]))
        except KeyError :
            logging.critical("There is a configuration problem with the endpoints in the file '%s'" % configFile)
            exit(10)

        try :
            self.app.run(port=self.config['port'])
        except KeyError :
            logging.critical("Server Configuration does not specify a port, defaulting to port 5000")
            self.app.run(port=5000)
Exemple #3
0
def create_app(config_dict={}):
    global env, config

    # Set up scruffy environment
    env = Environment(
        dir=Directory('~/.flexo', create=False,
            config=ConfigFile('config', defaults=File('default.conf', parent=PackageDirectory()), apply_env=True)
        )
    )
    config = env.config

    # Setup flask app
    app = Flask(__name__, static_url_path='/static')
    app.secret_key = config.secret
    app.config["MONGODB_SETTINGS"] = {'host': config.db_uri}
    app.config.update(config_dict)
    app.register_blueprint(main)

    # Setup database
    app.db = MongoEngine(app)

    # Setup login_manager
    login_manager.init_app(app)
    login_manager.login_view = 'login'

    # Setup API
    api = Api(app)
    api.add_resource(MetricAPI, '/api/metric')
    api.add_resource(ExerciseAPI, '/api/exercise')

    # Make sure there's at least an admin user
    if len(User.objects) == 0:
        User(name='admin', password='******').save()

    return app
Exemple #4
0
class Application(object):

    def __init__(self, conf=None):
        log.info('[%s] Init', self.__class__.__name__)
        self.conf = conf
        self.app = Flask(__name__)
        self.api = Api(self.app)
        self.debug = True
        self.init_configure()
        self.init_api()

    def init_configure(self):
        log.info('[%s] Init configure', self.__class__.__name__)
        self.app.config['SECRET_KEY'] = self.conf.get('httpd', 'secret')
        self.app.config['BUNDLE_ERRORS'] = True

    def init_api(self):
        log.info('[%s] Init api', self.__class__.__name__)
        resource.Static.static_path = self.conf.get('ui', 'html')
        self.api.add_resource(resource.Static, '/ui', '/ui/<path:path>', endpoint="ui")

        self.api.add_resource(resource.Cve,
                              '/api/cve',
                              '/api/cve/<year>',
                              '/api/cve/<year>/<cve_id>',
                              endpoint='api/cve',)

    def run(self, *a, **ka):
        return self.app.run(debug=self.debug,
                            host=self.conf.get('httpd', 'host'),
                            port=self.conf.getint('httpd', 'port'))
Exemple #5
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(DebugConfig)
    api = Api(app)
    api.add_resource(Video, '/video','/video/<int:videoid>')
    db.init_app(app)
    return app
def create_app(config):
    app = Flask(__name__)

    app.config['SQLALCHEMY_DATABASE_URI'] = get_meta_db_config_path(config)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['BUNDLE_ERRORS'] = True
    app_config = get_application_config(config)

    for key in app_config:
        app.config[key.upper()] = int(app_config[key]) if key.upper() in INT_OPTIONS else app_config[key]
    app.config['SENTRY_INCLUDE_PATHS'] = [
        'postgraas_server',
    ]
    app.config['SENTRY_RELEASE'] = postgraas_server.__version__
    sentry.init_app(app)

    restful_api = Api(app)
    restful_api.add_resource(DBInstanceResource, "/api/v2/postgraas_instances/<int:id>")
    restful_api.add_resource(DBInstanceCollectionResource, "/api/v2/postgraas_instances")
    db.init_app(app)
    app.postgraas_backend = get_backend(config)

    @app.route('/health')
    def health():
        return "ok"

    return app
class JSONPTestCase(MyTestCase):

    callback_arg_name = 'jsonp_callback'
    js_callback = 'doIt'
    return_data = 'custom_result'

    def setUp(self):
        self.setup_app()

        testcase = self

        class Routes(Resource):
            def get(self):
                return testcase.return_data

        self.api = Api(self.app)
        self.api.add_resource(Routes, '/')

    def verify(self):
        rv = self.client.get('/?{}={}'.format(self.callback_arg_name, self.js_callback))
        self.assertEqual(rv.content_type, 'application/json')
        self.assertEqual(rv.data.decode("utf-8"), '{}("{}")'.format(self.js_callback, self.return_data))

        rv = self.client.get('/')
        self.assertEqual(rv.content_type, 'application/json')
        self.assertEqual(rv.data.decode("utf-8"), '"{}"'.format(self.return_data))

    def test_str_source(self):
        restful_extend.support_jsonp(self.api, self.callback_arg_name)
        self.verify()

    def test_fn_source(self):
        restful_extend.support_jsonp(self.api, lambda: request.args.get(self.callback_arg_name, False))
        self.verify()
Exemple #8
0
class MultivacApi(object):

    def __init__(self, redis_host, redis_port, debug=False):
        app_dir = os.path.dirname(os.path.realpath(__file__))
        static_dir = app_dir + '/static'
        template_dir = app_dir + '/templates'

        self.app = Flask('multivac',
                         template_folder=template_dir,
                         static_folder=static_dir)
        self.api = Api(self.app)

        self.app.config['DEBUG'] = debug
        self.app.config['db'] = JobsDB(redis_host, redis_port)

        for resource, path in resource_map.items():
            self.api.add_resource(resource, path)

        @self.app.route('/', methods=['GET'])
        def main():
            db = self.app.config['db']

            return render_template('index.html',
                                   actions=db.get_actions(),
                                   version=version)

    def start_server(self, listen_port=8000):
        print('Starting Multivac API v%s' % version)
        http_server = WSGIServer(('0.0.0.0', listen_port), self.app)
        http_server.serve_forever()
Exemple #9
0
 def setUp(self):
     super(self.__class__, self).setUp()
     app = flask.Flask(__name__)
     api = Api(app)
     api.add_resource(SetCookieView, '/set_cookie')
     api.add_resource(DontSetCookieView, '/dont_set_cookie')
     self.app = app.test_client()
Exemple #10
0
def add_routes(app):
    """Add the routes to an app"""
    for (prefix, routes) in API_SECTIONS:
        api = Api(app, prefix=prefix)
        for ((pattern, resource, *args), kwargs) in routes:
            kwargs.setdefault('strict_slashes', False)
            api.add_resource(resource, pattern, *args, **kwargs)
Exemple #11
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('over_achiever.config')
    db = SQLAlchemy(app, metadata=models.metadata)
    db.create_all()
    resources.db = app.db = db

    oauth = OAuth(app)
    github = oauth.remote_app(
        'github',
        consumer_key='507e57ab372adeb8051b',
        consumer_secret='08a7dbaa06ac16daab00fac53724ee742c8081c5',
        request_token_params={'scope': 'user:email'},
        base_url='https://api.github.com/',
        request_token_url=None,
        access_token_method='POST',
        access_token_url='https://github.com/login/oauth/access_token',
        authorize_url='https://github.com/login/oauth/authorize'
    )

    # set the token getter for the auth client
    github._tokengetter = lambda: session.get('github_token')
    resources.github = app.github = github

    api = Api(app)
    resource_map = (
        (User, '/v1.0/users'),
        (Goal, '/v1.0/goals'),
    )

    for resource, route in resource_map:
        api.add_resource(resource, route)

    return app
def main():
    app.debug = True

#    logger = logging.getLogger('werkzeug')
#    logger.setLevel(logging.INFO)

    # Basic log config
    app.logger.debug('Debug logging enabled')
    # TODO(ijw) port etc. should probably be configurable.

    cfg.CONF(sys.argv[1:])
    global vppf
    vppf = VPPForwarder(flat_network_if=cfg.CONF.ml2_vpp.flat_network_if,
                        vlan_trunk_if=cfg.CONF.ml2_vpp.vlan_trunk_if,
                        vxlan_src_addr=cfg.CONF.ml2_vpp.vxlan_src_addr,
                        vxlan_bcast_addr=cfg.CONF.ml2_vpp.vxlan_bcast_addr,
                        vxlan_vrf=cfg.CONF.ml2_vpp.vxlan_vrf)



    api = Api(app)

    api.add_resource(PortBind, '/ports/<id>/bind')
    api.add_resource(PortUnbind, '/ports/<id>/unbind')


    app.run(host='0.0.0.0',port=2704)
Exemple #13
0
def main():
    app = Flask(__name__)
    api = Api(app, default_mediatype='application/xml')
    api.representations['application/xml'] = output_xml
    api.representations['application/json'] = output_xml
    api.add_resource(home, '/')

    app.run(host='0.0.0.0', port=8000, debug=True)
def web_app():
  app = Flask(__name__)
  app.config['DEBUG'] = DEBUG

  api = Api(app)
  api.add_resource(RandomName, '/getnames/<int:total_name>')

  return app
Exemple #15
0
def create_app(debug=False):
    app = Flask(__name__)
    app.debug = debug

    api = Api(app)
    api.add_resource(BasicApi, '/basic_api/<todo_id>')

    return app
Exemple #16
0
def main(config):
    prepare_gpio()
    app = Flask(__name__)

    api = Api(app)
    api.add_resource(Led, '/led/<string:state>')

    app.run(host=config.get('server', 'host'), port=config.getint('server', 'port'), debug=config.getboolean('server', 'debug'))
Exemple #17
0
class SearchApp(object):
    def __init__(self, db_conn_creator):
        self.app = Flask(__name__)
        self.api = Api(self.app)
        self.db_conn = None

        app = self

        class Voters(Resource):
            def __init__(self):
                if not app.db_conn:
                    app.db_conn = db_conn_creator()

                self.db_conn = app.db_conn

            def get(self, last, first, middle, zipcode, dob):
                c = self.db_conn.cursor()

                first = first.strip().upper()
                last = last.strip().upper()
                middle = middle.strip().upper()

                print("GET query: {}".format(",".join([last, first, middle, zipcode, dob])))

                c.execute("SELECT first_name, last_name, middle_name, zip_code, voter_status, status_reason, purged_date, inactive_date FROM voters WHERE first_name=? AND last_name=? AND zip_code=? AND DOB=?",
                          (first, last, zipcode[:5], dob))
                results = [{"first_name": first_name,
                            "last_name": last_name,
                            "middle_name": middle_name[:1],
                            "dob": _prettyfy_date(dob),
                            "zip": zip_code,
                            "status": _strip(status),
                            "status_why": _strip(status_reason) if _strip(status_reason) else 'NA',
                            "purged": _prettyfy_date(purged_date) if purged_date else 'NA',
                            "inactive": _prettyfy_date(inactive_date) if inactive_date else 'NA'}
                           for first_name, last_name, middle_name, zip_code, status, status_reason, purged_date, inactive_date, in c.fetchall()
                           if (not middle_name) or (middle and middle[0] == middle_name[0])]

                return {"matches": results[:SEARCH_LIMIT],
                        "count": len(results)}

        self.api.add_resource(Voters, '/voterapi/search/<string:last>/<string:first>/<string:middle>/<string:zipcode>/<string:dob>')

        @self.app.route('/search.html')
        def search_page():
            return app.app.send_static_file('search.html')

        @self.app.route('/js/<path:p>')
        def send_js(p):
            return send_from_directory('static/js', p)

        @self.app.route('/images/<path:p>')
        def send_images(p):
            return send_from_directory('static/images', p)

    def start(self, port, debug=False):
        self.app.run(port=port, debug=debug)
Exemple #18
0
def main(port, debug, run_command):
        app = Flask('roomservice')
        api = Api(app)

        api.add_resource(Mysql, '/app/mysql/<cmd>')
        api.add_resource(MysqlDatabase, '/app/mysql/databases/<dbname>')

        app.register_blueprint(system.blueprint)

        app.run(port=port, debug=debug)
Exemple #19
0
def setup_endpoint(api: FlaskAPI, inst: Module, name: str) -> None:
    """
    Binds module to API
    :param api: Flask-Restful
    :param inst: module instance
    :param name: end-point name
    """

    params = "/".join(["<{0}>".format(param) for param in get_identity(inst)])
    api.add_resource(inst, "/{0}".format(name), "/{0}/{1}/".format(name, params))
Exemple #20
0
def new_restful_api(blueprint):
    """
    Flask-Restful asks for authentication on 401 error through http basic-auth. Since
    we're not using http basic-auth, we have to disable this default handler.
    :param blueprint:
    :return:
    """
    api = Api(blueprint)
    api.unauthorized = _unauthorized_override
    return api
Exemple #21
0
def get_app():
    app = Flask(__name__)

    # routing
    api = Api(app)
    api.add_resource(Test1, '/test1')
    api.add_resource(Test2, '/test2')
    api.add_resource(Test3, '/test3')

    return app
class JSONEncoderTestCase(MyTestCase):
    def setUp(self):
        self.setup_app()

        testcase = self
        testcase.json_data = None

        class Routes(Resource):
            def get(self):
                return testcase.json_data

        self.api = Api(self.app)
        self.api.add_resource(Routes, '/')

        restful_extend.enhance_json_encode(self.api)

    def verify(self, data, expect_text_result):
        self.json_data = data
        rv = self.client.get('/')
        self.assertEqual(rv.content_type, 'application/json')
        self.assertEqual(expect_text_result, rv.data.decode("utf-8"))

    def test_basic(self):
        def gen():
            l = [1, 2, 3]
            for i in l:
                yield i

        now = datetime.now()

        samples = [
            (105.132, '105.132'),
            ('abc', '"abc"'),
            (u'你好', u'"你好"'),
            (True, 'true'),
            (None, 'null'),

            ([1, 'a', 10.5], '[1, "a", 10.5]'),

            (now, str(time.mktime(now.timetuple()))),
            (Decimal(10.5), '10.5'),
            (gen(), '[1, 2, 3]'),
        ]

        for data, result in samples:
            self.verify(data, result)

    def test_custom_encoder(self):
        class CustomDataType(object):
            def __init__(self, a, b):
                self.a = a
                self.b = b

        self.api.json_encoder.register(lambda obj: obj.a + obj.b, CustomDataType)
        self.verify(CustomDataType(Decimal(10.5), 1), '11.5')
def api_urls(app):
    urls = Blueprint('api', __name__)

    api = Api()
    api.init_app(urls)

    # URLs
    # Tokens
    # api.add_resource(FooResource, '/foo')

    return urls
def HTTP_ROUTER():
    app = Flask(__name__)
    api = Api(app)

    class HelloWorld(Resource):
        def get(self):
            test = phorbet.hello()
            return test

    api.add_resource(HelloWorld, '/')
    return app
def main():
    """
    Start the app server.
    :return:
    """
    app = Flask(__name__)
    api = Api(app)
    api.add_resource(ArticleServiceMeta, '/articles')
    api.add_resource(ArticleService, '/article/<int:article_id>', '/article')
    db.create_all()
    app.run(debug=True)
    def serve_rest_api(self, debug=True):
        """
        serve the rest endpoint using flask rest
        """
        app = Flask(__name__)
        api = Api(app)

        search_game = self.search_game
        games_to_list = self.games_to_list

        def abort_if_game_doesnt_exist(game):
            """
            404 if game not in top game list

            @param game: game to search 
            """
            if game.lower() not in self.topgames:
                    abort(404, message="Game {} doesn't exist".format(game), status=404)

        class Status(Resource):
            """
            status rest endpoint
            """
            def get(self):
                return {
                    'status': 200,
                    'message': "success"
                    }

        class Games(Resource):
            """
            game information rest endpoint
            """
            def get(self, game=None):
                if game is None:
                    return {
                        'status': 200,
                        'message': "success",
                        'data': games_to_list()
                    }
                else:
                    abort_if_game_doesnt_exist(game)
                    game = search_game(game)
                    return {
                        'status': 200,
                        'message': "success",
                        'data': game
                    }

        api.add_resource(Status, '/')
        api.add_resource(Games, '/games/', '/games/<string:game>/')

        app.run(debug=debug, port=self.port)
Exemple #27
0
def create_api(app):
    api = Api(app)

    TODOS = {
        'todo1': {'task': 'build an API'},
        'todo2': {'task': '?????'},
        'todo3': {'task': 'profit!'},
    }

    def abort_if_todo_doesnt_exist(todo_id):
        if todo_id not in TODOS:
            abort(404, message="Todo {} doesn't exist".format(todo_id))

    parser = reqparse.RequestParser()
    parser.add_argument('task')

    # Todo
    # shows a single todo item and lets you delete a todo item
    class Todo(Resource):
        def get(self, todo_id):
            abort_if_todo_doesnt_exist(todo_id)
            return TODOS[todo_id]

        def delete(self, todo_id):
            abort_if_todo_doesnt_exist(todo_id)
            del TODOS[todo_id]
            return '', 204

        def put(self, todo_id):
            args = parser.parse_args()
            task = {'task': args['task']}
            TODOS[todo_id] = task
            return task, 201

    # TodoList
    # shows a list of all todos, and lets you POST to add new tasks
    class TodoList(Resource):
        def get(self):
            return TODOS

        def post(self):
            args = parser.parse_args()
            todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
            todo_id = 'todo%i' % todo_id
            TODOS[todo_id] = {'task': args['task']}
            return TODOS[todo_id], 201

    ##
    ## Actually setup the Api resource routing here
    ##
    api.add_resource(TodoList, '/todos')
    api.add_resource(Todo, '/todos/<todo_id>')
    return app
Exemple #28
0
class ArtifactsApplication:
    def __init__(self):
        self.application = Flask(__name__)
        self.api = Api(self.application)
        self.defaultModelPath = "model.tar.gz"

    def run(self, debug=False):
        with Model(self.defaultModelPath) as model:
            DescribeAudioWithModel = DescribeAudio.create(model)
            self.api.add_resource(DescribeAudioWithModel, "/audio/describe")

            self.application.run(debug=debug)
Exemple #29
0
def create_app():
    app = Flask(__name__)
    api = Api(app)
    api.add_resource(DareResource, '/dare')
    api.add_resource(ContactFormResource, '/contact')
    api.add_resource(PublicTprDaresResource, '/dares')
    api.add_resource(DareCountResource, '/dare-count')
    api.add_resource(ReportResource, '/reports')
    return app
Exemple #30
0
def setup_api(app):
    api = Api(app)

    api.add_resource(HelloWorld, '/api/')
    api.add_resource(api_randomdates, '/api/randomdates/')
    api.add_resource(api_randomevents, '/api/randomevents/')
    api.add_resource(api_shortitems, '/api/shotitems/')

    return api
from flask import Flask, Blueprint
from flask_restful import Api, Resource

app = Flask(__name__)
api_bp = Blueprint(
    'api',
    "flask-restful with blueprint",
    url_prefix="/api",
)
api = Api(api_bp)


class TodoItem(Resource):
    def get(self, id):
        return {'task': 'Say "Hello, World!" for {}'.format(id)}


api.add_resource(TodoItem, '/todos/<int:id>')
app.register_blueprint(api_bp)

if __name__ == '__main__':
    app.run(debug=True)

# call like
"""
curl -X GET "http://localhost:5000/api/todos/10"
"""
# RESTful API creation using Flask.
# Based off of the below tutorial but with changes to use MySQL
# https://codeburst.io/this-is-how-easy-it-is-to-create-a-rest-api-8a25122ab1f3
# For MySQL changes, see https://codehandbook.org/python-web-application-flask-mysql/
from flask import Flask
from flask_restful import Api, Resource, reqparse
from flaskext.mysql import MySQL

app = Flask(__name__)
api = Api(app)

mysql = MySQL()

# MySQL configurations.
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'flask_test'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

# Make MYSQL init call with app.
mysql.init_app(app)


class User(Resource):
    def get(self, name):
        # MySQL connection.
        conn = mysql.connect()
        cursor = conn.cursor()
        user_query = "SELECT * FROM user WHERE name = %s"
        cursor.execute(user_query, (name, ))
        user = cursor.fetchone()
Exemple #33
0
from flask_restful import Resource, Api, reqparse

from .lib.storageinterfaces import StorageInterface
from .lib import determine_identifier_type, sane_transform_args, \
    should_transform, general_transform
from .exceptions import Error, Omitted

__author__ = "Brian Balsamo"
__email__ = "*****@*****.**"
__version__ = "0.2.0"

BLUEPRINT = Blueprint('digcollretriever', __name__)

BLUEPRINT.config = {}

API = Api(BLUEPRINT)

log = logging.getLogger(__name__)


@BLUEPRINT.errorhandler(Error)
def handle_errors(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response


def statter(storageKls, identifier):
    # TODO
    # Without more class introspection this gets a little wonky if classes
    # are making their own decisions about whether or not to let dynamic
Exemple #34
0
from flask import Blueprint
from flask_restful import Api
from critterpedia import (Health, Fish, Bugs)

api_bp = Blueprint('api', __name__)
api = Api(api_bp)

api.add_resource(Health, '/health')
api.add_resource(Fish, '/fish')
api.add_resource(Bugs, '/bugs')
Exemple #35
0
from flask import Blueprint, Flask
from config import Config
from flask_restful import Api
from resources.hello_world import HelloWorld
from resources.demo import Demo
from resources.user import *
from resources.post import *
from resources.home import *
from resources.hashtag import *
from resources.location import *
from resources.photos import photos

api_bp = Blueprint('api', __name__)
api = Api(api_bp)

# Routes
api.add_resource(HelloWorld, '/')
api.add_resource(Demo, '/demo')

api.add_resource(UserResource, '/User')
api.add_resource(UserRegisterResource, '/User/register')
api.add_resource(UserLoginResource, '/User/login')
api.add_resource(UserProfileResource, '/User/profile/<username>')
api.add_resource(UserFollowResource, '/User/follow/<username>')

api.add_resource(PostResource, '/Post')
api.add_resource(PostItemResource, '/Post/<pid>')
api.add_resource(PostLikeResource, '/Post/<pid>/like')

api.add_resource(PostItemCommentResource, '/Post/<pid>/comment')
api.add_resource(PostItemCommentItemResource,
    Main view for REST API to display all available experiments
    '''
    def get(self):
        experiment_json = app.experiments
        return experiment_json

class apiExperimentSingle(Resource):
    '''apiExperimentSingle
    return complete meta data for specific experiment
    :param exp_id: exp_id for experiment to preview
    '''
    def get(self, exp_id):
        return {exp_id: app.experiment_lookup[exp_id]}

app = EFServer(__name__)
api = Api(app)    
api.add_resource(apiExperiments,'/experiments')
api.add_resource(apiExperimentSingle,'/experiments/<string:exp_id>')


# WEB INTERFACE VIEWS ##############################################

app.config['ALLOWED_EXTENSIONS'] = set(['png', 'jpg', 'jpeg','gif'])
    
# For a given file, return whether it's an allowed type or not
def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']

def get_field(request,fields,value):
    """
Exemple #37
0
import os

from flask import Flask, jsonify, send_from_directory
from flask_cors import CORS
from flask_restful import reqparse, Api, Resource

import classifier

app = Flask(__name__, static_folder='build')
app.config['SECRET_KEY'] = 'supersecretkey'
api = Api(app)
CORS(app)

parser = reqparse.RequestParser()
parser.add_argument('month')
parser.add_argument('startDay')
parser.add_argument('endDay')
parser.add_argument('hour')
parser.add_argument('crime')
parser.add_argument('location')
parser.add_argument('day')


@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def index(path):
    if path != "" and os.path.exists("build/" + path):
        return send_from_directory('build', path)
    else:
        return send_from_directory('build', 'index.html')
Exemple #38
0
from pymongo import MongoClient, GEO2D

DB_HOST = os.environ.get('DB_HOST', 'mongodb')
DB_NAME = os.environ.get('DB_NAME', 'mongodb')

DB_USERNAME = os.environ.get('DB_USERNAME', 'mongodb')
DB_PASSWORD = os.environ.get('DB_PASSWORD', 'mongodb')

DB_URI = 'mongodb://%s:%s@%s:27017/%s' % (DB_USERNAME, DB_PASSWORD, DB_HOST,
                                          DB_NAME)

DATASET_FILE = 'nationalparks.json'

application = Flask(__name__)

api = Api(application)


class HealthCheck(Resource):
    def get(self):
        return 'OK'


api.add_resource(HealthCheck, '/ws/healthz/')


class Info(Resource):
    description = {
        'id': 'nationalparks-py',
        'displayName': 'My cool Parks (PY)',
        'type': 'cluster',
Exemple #39
0
from flask import Blueprint,g,current_app,jsonify
from flask_restful import Resource,marshal_with,Api,fields
from models import Article
from flask_httpauth import HTTPBasicAuth #导入认证类
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
article_bp = Blueprint('article',__name__)

api = Api(article_bp)
auth = HTTPBasicAuth()  #实例化一个认证对象



@auth.verify_password
def verify_password(username_or_token,password):
    #如果传入用户名和密码 然后进行相关的验证
    if username_or_token == 'kangbazi' and password == '123456':
        g.username = username_or_token
        return True

    #当你传过来的是一个token

    s = Serializer(current_app.config['SECRET_KEY'],expires_in=3600) #验证token是否合法
    try:
        data = s.loads(username_or_token)
        g.username = data.get('username')
        return True
    except:
        return False


Exemple #40
0
from app.mod_interaction.resources.UserResource import CompatibleUserResource
from app.mod_interaction.resources.LatestResource import LatestResource
from app.mod_interaction.resources.UnreadResource import UnreadResource
from app.mod_interaction.resources.CarpoolResource import CarpoolSResource, CarpoolResource
from app.mod_interaction.resources.PassengerResource import PassengerResource
from app.mod_interaction.resources.ActivityResource import ActivityResource
from app.mod_interaction.resources.CollectorResource import CollectorResource
from app.mod_interaction.resources.SyllabusCollectionResource import SyllabusCollectionResource

interaction_blueprint2_1 = Blueprint(
    "interaction2",
    __name__,
    url_prefix="/interaction",
    template_folder='templates')  # url 必须以 / 开头

api_v2_1 = Api(interaction_blueprint2_1, prefix="/api/v2.1")


# http://flask-restful-cn.readthedocs.io/en/0.3.5/extending.html
@api_v2_1.representation("application/json")
def output_json(data, code, headers=None):
    response_data = ResultResponse.ResultResponse()
    response_data.code = code
    # response_data.data = data
    if "error" in data:
        response_data.message = data["error"]
        response_data.data = {}
    else:
        response_data.data = data
        if 200 < code or code > 300:
            response_data.message = 'fail'
Exemple #41
0
from flask import Flask, jsonify
from flask_restful import reqparse, abort, Api, Resource
import pickle
import numpy as np
from joblib import load
from waitress import serve
import os

app = Flask(__name__)
api = Api(app)

model = load('lib/models/model.joblib')

# argument parsing
parser = reqparse.RequestParser()
parser.add_argument('fat', required=True, type=float)
parser.add_argument('age', required=True, type=int)
parser.add_argument('bmi', required=True, type=float)


class PredictWorkout(Resource):
    def get(self):
        # use parser and find the user's query
        args = parser.parse_args()
        fat = args['fat']
        age = args['age']
        bmi = args['bmi']

        query = [fat, age, bmi]
        print("Query: Fat: {} Age: {} BMI: {} ".format(fat, age, bmi))
Exemple #42
0
from flask_restful import Api, Resource
from http_status import HttpStatus
from models import orm, NotificationCategory, NotificationCategorySchema, Notification, NotificationSchema
from sqlalchemy.exc import SQLAlchemyError
from helpers import PaginationHelper
from flask_httpauth import HTTPBasicAuth
from flask import g
from models import User, UserSchema

auth = HTTPBasicAuth()

service_blueprint = Blueprint('service', __name__)
notification_category_schema = NotificationCategorySchema()
notification_schema = NotificationSchema()
user_schema = UserSchema()
service = Api(service_blueprint)


@auth.verify_password
def verify_user_password(name, password):
    user = User.query.filter_by(name=name).first()
    if not user or not user.verify_password(password):
        return False
    g.user = user
    return True


class AuthenticationRequiredResource(Resource):
    method_decorators = [auth.login_required]
    user_schema = UserSchema()
Exemple #43
0
from flask import Flask
from flask import Blueprint
from flask_restful import Api
from resources.CaptionGenerator import CaptionGeneration

app = Flask(__name__)
api_bp = Blueprint('api', __name__)
api = Api(api_bp)

# Route
api.add_resource(CaptionGeneration, '/process_image')
Exemple #44
0
from flask import Flask
from flask_restful import Resource, Api
import tools as tt

app = Flask(__name__)
api = Api(app)


class Searchlink(Resource):
    def get(self, name):
        person = tt.linkedin(name)
        return person


api.add_resource(Searchlink, '/searchlink/<name>')

if __name__ == '__main__':
    app.run(debug=True)
Exemple #45
0
from flask import Flask, request
from flask_restful import Resource, Api
from json import dumps
from flask.ext.jsonpify import jsonify

app = Flask(__name__)
api = Api(app)


class Test(Resource):
    def get(self):
        return {'test': [1, 2, 5]}


api.add_resource(Test, '/test')

if __name__ == '__main__':
    app.run(port='8500')
# -*- coding: utf-8 -*-

# -*- coding: utf-8 -*-
"""
Created on Mon Mar 23 09:31:30 2020

@author: James Ang
"""
from flask import Flask, request, jsonify, flash, redirect
from flask_restful import Resource, Api
import sys
import pandas as pd
from vaccine_drp_lib import Hospital, Demand_Centre, Supplier, Dry_Ice_Supplier

app = Flask(__name__)
api = Api(app)

#%% Set Upload Folder and Secret Key

if sys.platform == "win32":    
    UPLOAD_FOLDER = r'C:\Users\User\Documents\James\E_BL_LC\LC\alfred\upload'
else:    
    # UPLOAD_FOLDER = r'/home/alfred/uploads'
    UPLOAD_FOLDER = r'/home/alfred/Documents/deploy/lc_bl_inv/uploads'


#%% Endpoint '/' - to test connection

class index(Resource):
    def get(self):
        return request.url
Exemple #47
0
from flask import Flask, jsonify, request
from flask_cors import CORS
from flask_restful import Api, Resource, abort
from functions import *

application = app = Flask(__name__)
CORS(app)
api = Api(app)


def abort_if_not_authorized():
    token = request.headers['Authorization']
    if token:
        return token
    else:
        abort(400, message="Authorization header missing.")


class Index(Resource):
    def get(self):
        return {"message": "Server running OK."}


class RepoSummary(Resource):
    def get(self, owner, repo):
        token = abort_if_not_authorized()
        data = repository_summary(token, f'{owner}/{repo}')
        return data


class Top10Contributors(Resource):
Exemple #48
0
#     app.config.from_object(app_config[configuration])
#     db.init_app(app)
#     return app

template = {
    "swagger":
    "2.0",
    "info": {
        "title": "BUCKETLIST API",
        "description": "API for managing your bucketlists",
        "contact": {
            "responsibleDeveloper": "Jackson Onyango",
            "email": "*****@*****.**",
        },
        "version": "1.0"
    },
    "schemes": ["http", "https"],
    "produces": [
        "application/x-www-form-urlencoded", "application/json",
        "application/txt"
    ],
    "operationId":
    "getmyData",
    "content-type":
    "text"
}

# heroku = Heroku(app)
api = Api(app=app, prefix="/api/v1")
swagger = Swagger(app, template=template)
Exemple #49
0
from bs4 import BeautifulSoup
import urllib.request as request
import urllib.error
from flask import Flask
from flask_restful import Resource, Api
from flask_jsonpify import jsonify
import os
import platform
from PIL import Image

app = Flask(__name__)
api = Api(app)


# API that pings pond5 website. Returns "Pong" if successful
class Ping(Resource):
    def get(self):
        URL = "www.pond5.com"
        ping = os.system(" ping -c 1 " + URL)
        # Success
        if ping == 0:
            return "Pong"
        # Failure
        else:
            return "Unable to ping"


# API that returns information about the system running in JSON format
class System(Resource):
    def get(self):
        data = {
Exemple #50
0
from flask import Blueprint
from flask_restful import Api, reqparse, Resource, marshal, inputs
from sqlalchemy import desc

from flask_jwt_extended import jwt_required, get_jwt_claims
from blueprints import admin_required, user_required

from .model import Points
from ..posting.model import TopLevels, SecondLevels
from ..user.model import Users
from blueprints import db, app

bp_point = Blueprint('point', __name__)
api = Api(bp_point)


class PointCRU(Resource):
    #CORS
    def options(self, *args, **kwargs):
        return {}, 200

    @jwt_required
    @user_required
    def get(self):

        user_id = get_jwt_claims()['user_id']

        # parser =reqparse.RequestParser()
        # parser.add_argument("content_type", location="args", choices=('article','question','answer','comment'))
        # parser.add_argument('locator_id',location='args')
        # args = parser.parse_args()
Exemple #51
0
    UserConfirm,
)
from resources.item import Item, ItemList
from resources.store import Store, StoreList

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ["DATABASE_URL"]
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["PROPAGATE_EXCEPTIONS"] = True
app.config["JWT_BLACKLIST_ENABLED"] = True  # enable blacklist feature
app.config["JWT_BLACKLIST_TOKEN_CHECKS"] = [
    "access",
    "refresh",
]  # allow blacklisting for access and refresh tokens
app.secret_key = os.environ["SECRET_KEY"]
api = Api(app)


@app.before_first_request
def create_tables():
    db.create_all()


@app.errorhandler(ValidationError)
def handler_marshmallow_validation(err):
    return jsonify(err.messages), 400


jwt = JWTManager(app)

from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_restful import Api
from flask_jwt_extended import JWTManager
from flask_marshmallow import Marshmallow
from flask_cors import CORS


api = Api()
cors = CORS()
db = SQLAlchemy()
jwt = JWTManager()
ma = Marshmallow()
migrate = Migrate()
Exemple #53
0
# -*- coding: utf-8 -*-
# @Time    : 2019-06-14 15:21
# @Author  : Woko
# @File    : restful.py

from flask_restful import Api, Resource, reqparse

api = Api()

data = ['Woko', 'Liu']


class User(Resource):

    def get(self, user_id: int = None):
        if user_id is None:
            return data

        try:
            return data[user_id]
        except IndexError:
            return 'no such user', 400

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username', location='form')
        args = parser.parse_args()
        username = args.username

        if username in data:
            return 'duplicate username', 400
Exemple #54
0

optimizer = Adam()
expirience_replay = ExpirienceReplay(50000)
agent = DDQNAgent(expirience_replay, NUM_STATES, NUM_ACTIONS, optimizer,
                  DoLoadH5)
agent_trainer = AgentTrainer(agent, environment)
agent_trainer.train(EPISODES)

# agent.primary_network.save_weights(h5_file)
# show(results, size=int(EPISODES / 20))

app = Flask(__name__)
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
api = Api(app)
seperator = ','


class GetMoves(Resource):
    def get(self, request):
        requests = request.split('X')
        moves1 = requests[0].split(seperator)
        moves2 = requests[1].split(seperator)
        round = int(requests[2])
        environment.reset()
        if (moves1):
            for m1 in moves1:
                if m1:
                    environment.step((1, int(m1)))
        if (moves2):
Exemple #55
0
from flask import Flask

from flask_restful import Api

from flask_restful_swagger import swagger

from flask_sqlalchemy import SQLAlchemy

from config import Config

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

db = SQLAlchemy(app)

api = swagger.docs(Api(app), apiVersion='0.1')

from blog import models

from blog.resources.categories import Categories
from blog.resources.comments import Comments
from blog.resources.posts import Posts
from blog.resources.statistic import Statistic

api.add_resource(Categories, '/api/v1/categories')
api.add_resource(Comments, '/api/v1/comments')
api.add_resource(Posts, '/api/v1/posts')
api.add_resource(Statistic, '/api/v1/statistic')
Exemple #56
0
import json
import sqlite3

from flask import Flask, jsonify
from flask_restful import Resource, Api, reqparse

from text_similarity_model.model import Model
from database import Database

app = Flask(__name__)
api = Api(app)

db = Database()

model = Model.deserialize("../models/model_1.0.0.pkl")
version = model.version

parser = reqparse.RequestParser()
parser.add_argument("title", required=True)
parser.add_argument("description", required=True)
parser.add_argument("n_results", required=False)

class Version(Resource):
    def get(self):
        return jsonify({"model_version": version})

class Predict(Resource):
    def post(self):
        palestras = None
        args = parser.parse_args()
        title = args["title"]
Exemple #57
0
# See the License for the specific language governing permissions and
# limitations under the License.
# ============LICENSE_END=========================================================
###

import logging
import subprocess
import os
from subprocess import check_output, CalledProcessError
from flask import Flask
from flask_restful import Resource, Api, reqparse
from werkzeug.datastructures import FileStorage
import time

app = Flask(__name__)
api = Api(app)
logger = logging.getLogger("yang-loader")
logger.addHandler(logging.StreamHandler())
KAFKA_BROKER_NAME = "kafka1"
KAFKA_TOPIC_NAME = "config"


class YangLoaderHelper(object):
    @classmethod
    def save_file(cls, yang_model_file: FileStorage) -> str:
        path = "/tmp/" + yang_model_file.filename
        yang_model_file.save(path)
        return path

    @classmethod
    def install_new_model(cls, yang_model_path: str):
Exemple #58
0
from flask import Flask, request
from flask_restful import Resource, Api, reqparse

app = Flask(__name__)
api = Api(app)

basePath = '/api/v1'

# Initialize util

# Utility functions

# Resources Classes


# api.add_resource("", f'{basePath}/')


if __name__ == "__main__":
    app.run(host='127.0.0.1', debug=True)
from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)


class HelloWorld(Resource):
    def get(self):
        return {'message': 'Hello World!'}

    def post(self):
        some_data = request.get_json()
        return {'you sent': some_data}


class Mult(Resource):
    def get(self, num):
        return {'result': num * num}


api.add_resource(HelloWorld, '/')
api.add_resource(Mult, '/mult/<int:num>')

if __name__ == '__main__':
    app.run()
Exemple #60
0
from flask import Flask
from flask_restful import Api
from flask_jwt import JWT

from security import authenticate, identity
from resources.user import UserRegister
from resources.item import Item, ItemList
from resources.store import Store, StoreList

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'jose'
api = Api(app)


@app.before_first_request
def create_tables():
    db.create_all()


jwt = JWT(app, authenticate, identity)

api.add_resource(Store, '/store/<string:name>')
api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')
api.add_resource(StoreList, '/stores')
api.add_resource(UserRegister, '/register')

if __name__ == "__main__":
    from db import db