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
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 #3
0
def create_app(settings_override=None):
    """Returns a `Flask` application instance configured.
    """

    app = Flask(__name__, instance_relative_config=True)

    app.config.from_object('fki_challenge.settings')
    app.config.from_pyfile('application.cfg', silent=True)
    app.config.from_object(settings_override)

    api = Api(app, prefix='/api', catch_all_404s=True)

    # ensure tables
    models.database.init(app.config['FKI_DATABASE_FILE'])
    models.database.connect()
    models.database.create_tables([models.Attribute, models.Person, models.PersonAttribute],
                                  safe=True)

    # register db request hooks
    app.before_request(_db_connect)
    app.teardown_request(_db_close)

    # wire resources
    api.add_resource(resources.Attribute, '/attributes/<int:attribute_id>')
    api.add_resource(resources.AttributeList, '/attributes/')
    api.add_resource(resources.Person, '/persons/<int:person_id>')
    api.add_resource(resources.PersonList, '/persons/')
    api.add_resource(resources.MatchList, '/matches/',
                     resource_class_kwargs={'error_rate': app.config['FKI_ERROR_RATE']})

    return app
Exemple #4
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 #5
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 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
Exemple #7
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 #8
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'))
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 #10
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 #11
0
def start(host, port, debug):
    logger.info('Start {host}:{port}'.format(host=host, port=port))
    api = Api(app)

    api.add_resource(AddJob, '/api/add')
    api.add_resource(JobStatus, '/api/status')
    api.add_resource(FileUpload, '/api/upload')
    api.add_resource(ResultData, '/api/list')
    api.add_resource(ResultDetail, '/api/detail')

    # consumer
    threads = []
    for i in range(5):
        threads.append(threading.Thread(target=consumer, args=()))

    for i in threads:
        i.setDaemon(daemonic=True)
        i.start()

    try:
        app.run(debug=debug, host=host, port=int(port), threaded=True, processes=1)
    except socket.error as v:
        if v.errno == errno.EACCES:
            logger.critical('[{err}] must root permission for start API Server!'.format(err=v.strerror))
            exit()
        else:
            logger.critical('{msg}'.format(msg=v.strerror))

    logger.info('API Server start success')
def create_api(app):
    api = Api(app, catch_all_404s=True, errors=errors)
    api.representations['application/xml'] = output_xml
    got_request_exception.connect(log_exception, app)

    api.add_resource(Recipes, '/recipes', endpoint='recipes')
    api.add_resource(Recipes, '/recipes/<int:recipe_id>', endpoint='recipe')
Exemple #13
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
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 #15
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 #16
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 #17
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)
Exemple #18
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'))
def web_app():
  app = Flask(__name__)
  app.config['DEBUG'] = DEBUG

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

  return app
Exemple #20
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 #21
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 #22
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
Exemple #23
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))
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')
Exemple #25
0
def api_init(api_endpoint) -> Blueprint:
    api_bp = Blueprint('api', __name__)
    api = Api(api_bp, catch_all_404s=True)

    api.add_resource(InfoAPI, API_PATH + '/info', resource_class_kwargs={'api_endpoint': api_endpoint})
    api.add_resource(ExecutionAPI, API_PATH + '/execution/<int:execution_id>', resource_class_kwargs={'api_endpoint': api_endpoint})
    api.add_resource(ExecutionCollectionAPI, API_PATH + '/execution', resource_class_kwargs={'api_endpoint': api_endpoint})
    api.add_resource(ServiceAPI, API_PATH + '/service/<int:container_id>', resource_class_kwargs={'api_endpoint': api_endpoint})
    api.add_resource(QueryAPI, API_PATH + '/query', resource_class_kwargs={'api_endpoint': api_endpoint})

    return api_bp
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 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
Exemple #28
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
    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 #30
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 #31
0
# Products Service

from flask import Flask
from flask_restful import Api
from resources.product import Product
from resources.home import Home
from resources.overload import Overload
from resources.user import User

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

api.add_resource(Home, '/')
api.add_resource(Product, '/product')
api.add_resource(Overload, '/overload')
api.add_resource(User, '/user')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5050, debug=True)
Exemple #32
0
            ), 400

        if cert.endpoints:
            return dict(
                message=
                'Cannot revoke certificate. Endpoints are deployed with the given certificate.'
            ), 403

        plugin = plugins.get(cert.authority.plugin_name)
        plugin.revoke_certificate(cert, data)
        log_service.create(g.current_user, 'revoke_cert', certificate=cert)
        return dict(id=cert.id)


api.add_resource(CertificateRevoke,
                 '/certificates/<int:certificate_id>/revoke',
                 endpoint='revokeCertificate')
api.add_resource(CertificatesList, '/certificates', endpoint='certificates')
api.add_resource(Certificates,
                 '/certificates/<int:certificate_id>',
                 endpoint='certificate')
api.add_resource(CertificatesStats,
                 '/certificates/stats',
                 endpoint='certificateStats')
api.add_resource(CertificatesUpload,
                 '/certificates/upload',
                 endpoint='certificateUpload')
api.add_resource(CertificatePrivateKey,
                 '/certificates/<int:certificate_id>/key',
                 endpoint='privateKeyCertificates')
api.add_resource(CertificateExport,
Exemple #33
0
from flask import Flask
from flask_cors import CORS
from flask_restful import Api

from controller.appartment import ApartmentController
from controller.location import LocationController
from controller.recommender import RecommenderController
from controller.tags import TagController
from hello import Hello

# If `entrypoint` is not defined in app.yaml, App Engine will look for an app
# called `app` in `main.py`.
app = Flask(__name__)
CORS(app)
api = Api(app)

api.add_resource(Hello, '/hello/<name>')
api.add_resource(LocationController, '/locations')
api.add_resource(TagController, '/tags')
api.add_resource(ApartmentController, '/apartments/<neighborhood>/<pax>')
api.add_resource(RecommenderController, '/recommender')

if __name__ == '__main__':
    # This is used when running locally only. When deploying to Google App
    # Engine, a webserver process such as Gunicorn will serve the app. This
    # can be configured by adding an `entrypoint` to app.yaml.
    app.run(host='127.0.0.1', port=8080, debug=True)
# [END gae_python37_app]
        if args['type']:
            device.type = args['type']
        if args['mac_address']:
            device.mac_address = args['mac_address']

        db.session.commit()

        return {"message": "Patched successfully!"}

    def delete(self, id):
        item_to_delete = DeviceModel.query.filter_by(id=int(id)).first()
        print("Inside delete", item_to_delete)
        if item_to_delete is None:
            abort(405, message=f"Item with id: {id} doesn't exist.")
        db.session.delete(item_to_delete)
        db.session.commit()
        print("Deleted")
        return {"message": f"Item with id: {id} successfully deleted."}, 204


api.add_resource(Device, '/api/<int:id>')


@app.route('/')
def index():
    return "API to collect Device Info."


if __name__ == '__main__':
    app.run(debug=True)
        try:
            file = request.files['xlsform']
            temp_xlsx = os.path.join(temp_dir, file.filename)
            temp_xml = os.path.join(temp_dir, file.filename + '.xml')
            file.save(temp_xlsx)
            print('Converting', temp_xlsx)
            out = subprocess.check_output([
                'python', 'pyxform/pyxform/xls2xform.py', '--json',
                pythonic_path(temp_xlsx),
                pythonic_path(temp_xml)
            ])
            result = json.loads(out)
            print(result)
            if os.path.exists(temp_xml):
                with open(temp_xml, 'r') as xml:
                    result['xform'] = xml.read()
            shutil.rmtree(temp_dir)
            return result
        except Exception as e:
            shutil.rmtree(temp_dir)
            print(str(e))
            return {'code': 999, 'message': traceback.format_exc()}


app = Flask(__name__)
api = Api(app)
api.add_resource(Xls2XForm, '/api/xls2xform', '/xls2xform')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5123, debug=True)
Exemple #36
0
#!/usr/bin/env python3

import logging
from flask import Flask
from flask_restful import Api
from member import MemberApi

handler = logging.FileHandler('/var/log/xroad/csapi.log')
handler.setFormatter(logging.Formatter('%(asctime)s - %(process)d - %(levelname)s: %(message)s'))

# Member module logger
logger_m = logging.getLogger('member')
logger_m.setLevel(logging.INFO)
logger_m.addHandler(handler)

# Application logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(handler)

app = Flask(__name__)
api = Api(app)
api.add_resource(MemberApi, '/member')

logger.info('Starting Central Server API')
Exemple #37
0
        parser.add_argument('year', type=str)
        parser.add_argument('month', type=str)
        parser.add_argument('day', type=str)
        args = parser.parse_args()
        year = args['year']
        month = args['month']
        day = args['day']
        res = ps.get_credit_days_sales(year, month, day)
        return {'result': res}


"""""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """
 ****************************** Uri Path 설정 *********************************
""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """"""

api.add_resource(StartThread, '/start_thread')  # 메인 쓰레드 실행

api.add_resource(GetReaderConfig,
                 '/get_reader_config')  # 리더기 매트 설정 (PCB->DB->POS)
api.add_resource(SetReaderConfig,
                 '/set_reader_config')  # 리더기 매트 설정 (POS->DB->PCB)

api.add_resource(GetTouchConfig,
                 '/get_touch_config')  # 터치 충전기 설정 (device->DB->POS)
api.add_resource(SetTouchConfig,
                 '/set_touch_config')  # 터치 충전기 설정 (POS->DB->device)

api.add_resource(GetKioskConfig, '/get_kiosk_config')  # 키오스크 설정 (DB->POS)
api.add_resource(SetKioskConfig, '/set_kiosk_config')  # 키오스크 설정 (POS->DB)

api.add_resource(GetPosConfig, '/get_pos_config')  # 포스 설정 (DB->POS)
Exemple #38
0

class ItemList(Resource):
    def get(self):
        return {'items': items}


class Item(Resource):
    def get(self, name):
        item = next(filter(lambda x: x['name'] == name, items), None)
        return {'message': item}, 200 if item else 404

    def post(self, name):
        if next(filter(lambda x: x['name'] == name, items), None):
            return {
                'message': 'an item with name {} already exists'.format(name)
            }, 400

        request_data = request.get_json()
        try:
            new_item = {'name': name, 'price': request_data['price']}
            items.append(new_item)
            return new_item, 201
        except:
            return {'message': 'could not create item'}, 400


api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')

app.run(port=5000, debug=True)
Exemple #39
0
def create_api(app):
    api = Api(app)
    api.add_resource(resources.NoteResource, '/api/users/me/notes', '/api/users/me/notes/<int:note_id>')
    api.add_resource(resources.SharedNoteResource, '/api/users/me/shared_notes', '/api/users/me/shared_notes/<int:note_id>')
    api.add_resource(resources.NoteSharingResource, '/api/users/me/notes/<int:note_id>/share')
    api.add_resource(resources.UserResource, '/api/users')
    api.add_resource(resources.LoginResource, '/api/login')
    api.add_resource(resources.AvatarResource, '/api/users/me/avatar')
    api.add_resource(resources.HealthCheckResource, '/api/healthcheck')
Exemple #40
0
def MinutosdeTardanza(llegada):
	horallegada = datetime.now()
	horaentrada = horallegada.replace(hour=9, minute=0, second=0)
	diferencia = horallegada - horaentrada

	days, seconds = diferencia.days, diferencia.seconds
	hours = days * 24 + seconds // 3600
	minutes = (seconds % 3600) // 60
	seconds = seconds % 60

	if horallegada > horaentrada:
		#print("El empleado llego: " + str(hours) +" hora(s) " + "y " + str(minutes) + " minuto(s) tarde")
		return (hours*60 + minutes)
	else:
		return 0



api.add_resource(UsersList, '/users')
api.add_resource(User, '/users/<idUser>')
api.add_resource(Login, '/users/login/<username>/<password>')


api.add_resource(UsuarioTrabajadorList, '/usuariotrabajador')
api.add_resource(UsuarioTrabajador, '/usuariotrabajador/<dni>')
api.add_resource(HistorialAsistencia, '/asistencia')

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)
Exemple #41
0

# @app.route('/allbooks', methods=['GET'])
# def allBooks():
#     return jsonify(books)

# @app.route('/getbook', methods=['GET'])
# def getBook():

#     if 'id' in request.args:
#         id=int(request.args['id'])
#     else:
#         return 'no id'

#     for book in books:
#         if book['id']==id:
#             return jsonify(book)

# # api.add_resource(GetBook, '/getbook')
# api.add_resource(GetAllBooks, '/allbooks')
api.add_resource(CheckLogin, '/checklogin')
api.add_resource(Register, '/register')
api.add_resource(CreateGroup, '/creategroup')
api.add_resource(CheckGroup, '/checkgroup')
api.add_resource(GetUserGroups, '/getusergroups')
api.add_resource(JoinGroup, '/joingroup')
api.add_resource(GetGroupMembers, '/getgroupmembers')
api.add_resource(AddTransaction, '/addtransaction')

if __name__ == '__main__':
    app.run(debug=True)
Exemple #42
0
        abort_if_video_id_not_found(video_id)
        return videos[video_id]

    # what put method should do
    def put(self, video_id):
        '''put video'''
        # don't create video that already exists
        abort_if_video_exists(video_id)

        args = video_put_args.parse_args()

        # if successfully got the args, then store
        videos[video_id] = args

        # print(request.form['likes'])
        # return {video_id: args}

        return videos[video_id], 201  # status code 201 = worked

    def delete(self, video_id):
        '''delete the video'''
        abort_if_video_id_not_found(video_id)
        del videos[video_id]
        return '', 204  # deleteion successful


api.add_resource(Video, "/video/<int:video_id>")

if __name__ == "__main__":
    app.run(debug=True)
Exemple #43
0
            y_hat = model.predict(features)

            labels = {
                0: 'zero',
                1: 'one',
                2: 'two',
                3: 'three',
                4: 'four',
                5: 'five',
                6: 'six',
                7: 'seven',
                8: 'eight',
                9: 'nine'
            }

            data['prediction'] = labels[y_hat[0]]
            data['success'] = True  # Indicate that the request was a sucess

            return jsonify(data)  # Response


api.add_resource(Prediction, '/predict')

if __name__ == "__main__":
    print('Loading model and Flask starting server...')
    print('please wait until server has fully started')

    app.run(debug=True, host='0.0.0.0',
            port=5000)  # Debug mode and open to all connections in port 5000
Exemple #44
0
from flask import Flask, request, jsonify,Response
from flask_restful import Resource, Api
import random


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

class Partner(Resource):

     def get(self):
        rand_number = random.randint(1,10000000000000000)
        return jsonify(NumberValue= rand_number)


api.add_resource(Partner, '/partner/v1')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5055,debug=True)


Exemple #45
0
from flask import Flask
from flask_restful import Resource, abort, Api
import json

app = Flask(__name__)
api = Api(app, prefix='/api/v1')

data = json.load(open('data/csv/data.json'))

def dataKosong(data_id):
    if data_id not in data:
        abort(404, message="data {} doesn't exist".format(data_id))

class kaka(Resource):
    def get(self,data_id):
        dataKosong(data_id)
        return data[data_id]

api.add_resource(kaka,'/<data_id>')

if __name__ == '__main__':
    app.run(debug=True)
Exemple #46
0
            es.indices.delete("groups")
        if es.indices.exists("policyGames"):
            es.indices.delete("policyGames")
        if es.indices.exists("similarityweights"):
            es.indices.delete("similarityweights")
        print("HAVE DELETED ALL ES INDICES")


class Healthcheck(Resource):
    def get(self):
        # TODO: Do some checking
        print("Healthcheck")


# Similarities APIs
api.add_resource(PostList, api_url + '/posts/<cluster_id>/<post_id>')
api.add_resource(PointList, api_url + '/points/<cluster_id>/<point_id>')
api.add_resource(DomainList, api_url + '/domains/<cluster_id>/<domain_id>')
api.add_resource(CommunityList,
                 api_url + '/communities/<cluster_id>/<community_id>')
api.add_resource(GroupList, api_url + '/groups/<cluster_id>/<group_id>')

api.add_resource(FindSimilarPosts,
                 api_url + '/find_similar_posts/<cluster_id>')

api.add_resource(
    GetCommunityPostsWithWeights,
    api_url + '/similarities_weights/community/<cluster_id>/<community_id>')
api.add_resource(
    GetGroupPostsWithWeights,
    api_url + '/similarities_weights/group/<cluster_id>/<group_id>')
Exemple #47
0
def init_resources(app):
    api = Api(app)
    api.add_resource(Document_CRUD, '/document')
    return app
Exemple #48
0
from flask_restful import Api
from flask_mongoengine import MongoEngine
from flasgger import Swagger

import constants
from resources import MeasurementList, MeasurementDetail, ReportDetail

app = Flask(__name__)

app.config['MONGODB_SETTINGS'] = {
    'host': constants.DB_HOST,
    'db': constants.DB_NAME,
    'connect': False,
    'username': constants.DB_USER,
    'password': constants.DB_PASSWORD,
    'authentication_source': 'admin'
}

app.config['SWAGGER'] = {'title': 'AHM API', 'uiversion': 2}

api = Api(app)
db = MongoEngine(app)
swagger = Swagger(app)

api.add_resource(MeasurementDetail, '/v1/measurements/<string:id>')
api.add_resource(MeasurementList, '/v1/measurements')
api.add_resource(ReportDetail, '/v1/report/<string:period>')

if __name__ == '__main__':
    app.run(host=constants.API_HOST)
Exemple #49
0
                shared_vars.on = control['on']
                if shared_vars.on:
                    change_mode()
                else:
                    kill_threads()
        if control['mode'] is not None:
            if shared_vars.mode is not control['mode']:
                shared_vars.mode = control['mode']
                change_mode()
        return shared_vars.list_control(), 200, {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': '*'
        }


flaskApi.add_resource(HelloWorld, '/', resource_class_args=('test', ))
flaskApi.add_resource(Settings, '/settings')
flaskApi.add_resource(Control, '/control')
flaskApi.add_resource(PongControl, '/pong', resource_class_args=(pong_game, ))


def main():
    try:
        t_flask = threading.Thread(target=flaskApp.run,
                                   args=(
                                       '192.168.120.13',
                                       80,
                                   ),
                                   daemon=True)
        t_flask.start()
Exemple #50
0
app.config["MONGO_URI"] = "mongodb://localhost:27017/election"

CORS(app)

api = Api(app)
mongo = PyMongo(app)


# List of candidates
class Candidates(Resource):
    def get(self):
        return json.loads(
            dumps(
                mongo.db.people_key.find({}, {
                    "_id": 0,
                    "person_id": 1,
                    "name": 1
                }).distinct("name")))


# individual candidate
# class Candidate(Resource):
#     def get(self,person_id):
#         return json.loads(
#             dumps(mongo.db.people_key
#                 .find({"person_id":person_id},{'_id':0,'text':1,'value':1})
#             )
#         )

api.add_resource(Candidates, '/people')
Exemple #51
0
    @jwt_required()
    def delete(self, name):
        global items
        items = list(filter(lambda x: x['name'] != name, items))
        return {'message': 'Item deleted'}

    @jwt_required()
    def put(self, name):
        data = request.get_json()
        item = next(filter(lambda x: x['name'] == name, items), None)
        if item is None:
            item = {'name': name, 'price': data['price']}
            items.append(item)
        else:
            item.append(data)
        return item


class ItemList(Resource):
    def get(self):
        return {'items': items}


api.add_resource(Item,
                 '/item/<string:name>')  # http://127.0.0.1:5000/student/Rolf
api.add_resource(ItemList, '/items')

if __name__ == "__main__":
    app.run(debug=True)
Exemple #52
0
import os

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'] = os.environ.get('DATABASE_URL',
                                                       'sqlite://data.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'avasystem'
api = Api(app)

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
    db.init_app(app)
    app.run(debug=True)
Exemple #53
0
def load_resources():
    # API v1
    from .resources.v1 import api_v1
    from .resources.v1 import Greeting, Exam, ExamList, Verification
    from .resources.v1 import UserLogin, UserLogoutAccess, UserLogoutRefresh, TokenRefresh, ProtectedResource, UserRegistration

    api = Api(api_v1)

    api.add_resource(Greeting, '/')

    # Exams
    api.add_resource(Exam, '/exams/<name>')
    api.add_resource(ExamList, '/exams/list')
    api.add_resource(Verification, '/verify')

    # Admin
    api.add_resource(UserRegistration, '/account/registration')
    api.add_resource(UserLogin, '/account/login')
    api.add_resource(UserLogoutAccess, '/account/logout/access')
    api.add_resource(UserLogoutRefresh, '/account/logout/refresh')
    api.add_resource(TokenRefresh, '/account/token/refresh')
    api.add_resource(ProtectedResource, '/account/protected')
Exemple #54
0
            if (self.__check(feature)):
                self.node_data.append(self.__set(node.surface, feature))
            node = node.next
        print(self.node_data)

    def __words(self, data):
        if (len(data) > 0):
            self.target = data

    def __node(self, data):
        mecab.parse("")
        return mecab.parseToNode(data)

    def __feature(self, data):
        return data.feature.split(",")

    def __check(self, data):
        return (data[0] == self.CONST_PARTS_NOUN)

    def __set(self, surface, feature):
        data = {"surface": surface, "feature": feature}
        print(data)
        return data

api.add_resource(Morphologic, '/targetwords/<string:words>')

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


Exemple #55
0
from flask import Flask
from flask_restful import Resource, Api
from chatbot import ChatBot

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


class Response(Resource):
    def get(self, text):
        return ChatBot(text).get_response()


api.add_resource(Response, '/res/<text>')

if __name__ == '__main__':
    app.run()
Exemple #56
0
api = Api(app)
db = SQLAlchemy(app)

# api routers. apis package need to use db object:, import after db's init
from apis.user import User
from apis.session import Session
from apis.policy import Policies, Policy
from apis.task import Task, Tasks
from apis.host import Host, Hosts
from apis.vul import Vul, Vuls
from apis.task_status import TaskStatus
from apis.admin import AdminSession
from apis.scanner import Scanner, Scanners
from apis.scanner_status import ScannerStatus

api.add_resource(User, '/user/<int:user_id>', endpoint='user_get')      # get user info by id
api.add_resource(User, '/user', endpoint='user_post')       # register
api.add_resource(Session, '/session', endpoint='session_post')      # login
api.add_resource(Policies, '/policies', endpoint='policies_get')
api.add_resource(Policy, '/policy/<policy_id>', endpoint='policy_get')      # get certain policy
api.add_resource(Policy, '/policy', endpoint='policy_post')     # create a policy
api.add_resource(Task, '/task', endpoint='task_post')   # create a task
api.add_resource(Task, '/task/<int:task_id>', endpoint='task_delete')     # delete certain task
api.add_resource(Task, '/task/<int:task_id>', endpoint='task_put')   # launch a task
api.add_resource(Tasks, '/tasks', endpoint='tasks_get')   # all tasks of user
api.add_resource(Host, '/host/<int:host_id>', endpoint='host_get')   # scan result query
api.add_resource(Host, '/host/<int:host_id>', endpoint='host_put')   # scan result store
api.add_resource(Hosts, '/task/<int:task_id>/hosts', endpoint='hosts_get')  # get hosts list
api.add_resource(Vul, '/vul', endpoint='vul_post')  # create new vul
api.add_resource(Vuls, '/host/<int:host_id>/vuls', endpoint='vuls_get')
api.add_resource(TaskStatus, '/task/<int:task_id>/status', endpoint='t_status_put')
Exemple #57
0
import os
from flask import Flask
from flask_restful import Resource, Api

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


def arrayAppend(index, array):
    if (index <= array.shape[0]):
        return array
    newArray = np.zeros([index + 1, index + 1], dtype=int)
    newArray[:array.shape[0], :array.shape[0]] = array
    return newArray


class Register(Resource):
    def get(self):
        sql = 'select max(member_no) from member'
        dbc.cursor.execute(sql)
        member_no = dbc.cursor.fetchone()['max(member_no)']
        similarity = np.load(os.getcwd() + '\\..\\Recommend.npy')
        similarity = arrayAppend(member_no, similarity)
        np.save(os.getcwd(), similarity)
        return {'status': 'success'}


api.add_resource(Register, '/register')

if __name__ == '__main__':
    app.run(debug=True)
Exemple #58
0
from func import *
from ast import literal_eval

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

hostgroups = {}
num_of_hostgroups = int(environ['NUM_OF_HOSTGROUPS'])
for x in xrange(1, num_of_hostgroups + 1):
    value = environ['HG' + str(x)].split(":")
    hostgroups[value[0]] = literal_eval(value[1])


class Show_Status(Resource):
    def get(self):
        stat = {}
        for x in hostgroups.keys():
            stat[x] = check_stat(hostgroups[x])
        return {"status": stat}


@app.route("/")
def main():
    return "Welcome"


api.add_resource(Show_Status, '/status')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=False)
Exemple #59
0
from objects.esxhost import EsxHost
from objects.windowshost import WindowsHost
from objects.trident import Trident
from objects.testbed import Testbed
from objects.inventory import StorageInventory, HostInventory
from pprint import pprint
from flask import Flask
from flask_restful import Api, Resource, reqparse

if __name__ == "__main__":

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

    api.add_resource(Testbed, "/testbed/<string:target>")
    api.add_resource(StorageInventory, "/inventory/storage/<string:target>")
    api.add_resource(HostInventory, "/inventory/host/<string:target>")

    app.run(debug=True)
Exemple #60
0
        user = Users.query.filter_by(email=email).first()
        if user == None:
            response = make_response(jsonify({"message": "invalid username"}))
            response.status_code = 401
            return response
        #print '******hash: ' + generate_password_hash(password)
        if check_password_hash(user.password, password):
            token = create_token(user)
            return {'token': token}
        else:
            response = make_response(jsonify({"message": "invalid password"}))
            response.status_code = 401
            return response


api.add_resource(Auth, 'login.json')


class AlchemyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj.__class__, DeclarativeMeta):
            # an SQLAlchemy class
            fields = {}
            for field in [
                    x for x in dir(obj)
                    if not x.startswith('_') and x != 'metadata'
            ]:
                data = obj.__getattribute__(field)
                try:
                    json.dumps(
                        data