class Server(object): """ Setup and configure flask application. """ def __init__(self): self.app = Flask(__name__) def config_app(self): self.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database/test1.db' self.app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False def setup_database(self): self.db = SQLAlchemy(self.app) def get_db(self): return self.db def get_api(self): return self.api def drop_all_tables(self): self.db.drop_all() def create_all_tables(self): self.db.create_all() def start(self, debug_=False, host_ ='0.0.0.0', port_=8080): self.app.run(debug=debug_, host=host_, port=port_) def setup_api(self): self.api = Api(self.app, version='1.0', title='Starwars films.', description='get all the starwars films.') from services.films import Films from services.characters import Characters self.api.add_resource(Films, '/films', endpoint='films') self.api.add_resource(Characters, '/characters', endpoint='characters')
def create_app(): app = Flask(__name__) app.config.update(A='B') api = Api(app) api.add_resource(TodoResource, '/todo') FlaskInjector(app=app, modules=[AppModule]) return app
def test_will_prettyprint_json_in_debug_mode(self): self.app.config['DEBUG'] = True api = Api(self.app) class Foo1(Resource): def get(self): return {'foo': 'bar', 'baz': 'asdf'} api.add_resource(Foo1, '/foo', endpoint='bar') with self.app.test_client() as client: foo = client.get('/foo') # Python's dictionaries have random order (as of "new" Pythons, # anyway), so we can't verify the actual output here. We just # assert that they're properly prettyprinted. lines = foo.data.splitlines() lines = [line.decode() for line in lines] self.assertEquals("{", lines[0]) self.assertTrue(lines[1].startswith(' ')) self.assertTrue(lines[2].startswith(' ')) self.assertEquals("}", lines[3]) # Assert our trailing newline. self.assertTrue(foo.data.endswith(b'\n'))
def test_will_prettyprint_json_in_debug_mode(self): self.app.config["DEBUG"] = True api = Api(self.app) class Foo1(Resource): def get(self): return {"foo": "bar", "baz": "asdf"} api.add_resource(Foo1, "/foo", endpoint="bar") with self.app.test_client() as client: foo = client.get("/foo") # Python's dictionaries have random order (as of "new" Pythons, # anyway), so we can't verify the actual output here. We just # assert that they're properly prettyprinted. lines = foo.data.splitlines() lines = [line.decode() for line in lines] self.assertEquals("{", lines[0]) self.assertTrue(lines[1].startswith(" ")) self.assertTrue(lines[2].startswith(" ")) self.assertEquals("}", lines[3]) # Assert our trailing newline. self.assertTrue(foo.data.endswith(b"\n"))
def get_api(app): base_path = app.crudcast_config['swagger']['basePath'] api = Api(app, doc=False) mr = ModelResource mr.set_app(app) ir = InstanceResource ir.set_app(app) api.add_resource(mr, '%s/<string:model_name>/' % base_path) api.add_resource(ir, '%s/<string:model_name>/<string:_id>/' % base_path) for path, method in app.methods.items(): resource = method.get_resource() resource.set_app(app) api.add_resource(resource, '%s/%s' % (base_path, path)) if app.user_manager: umr = UserModelResource umr.set_app(app) uir = UserInstanceResource uir.set_app(app) api.add_resource(umr, '%s/user/' % app.crudcast_config['swagger']['basePath']) api.add_resource(uir, '%s/user/<string:_id>/' % app.crudcast_config['swagger']['basePath'])
def get_api(app): api = Api(app, doc=False) api.add_resource( ModelResource, '%s/<string:model_name>/' % app.crudcast_config['swagger']['basePath']) api.add_resource( InstanceResource, '%s/<string:model_name>/<string:_id>/' % app.crudcast_config['swagger']['basePath'])
def make_port(): """Creates api access port.""" app = Flask(__name__) api = Api(app) api.add_resource(CreateUser, '/auth/register') api.add_resource(LogUserIn, '/auth/login') return app
def make_port(): """Creates api access port.""" app = Flask(__name__) api = Api(app) api.add_resource(ItemsResource, '/bucketlists/<int:bucketlist_id>/items') api.add_resource(ItemsList, '/bucketlists/<int:bucketlist_id>/items/<int:item_id>') return app
def register_resources(app): api = Api(app) api.add_resource(MovieListResource, '/movies') api.add_resource(MovieResource, '/movies/<string:movie_name>') api.add_resource(UserListResource, '/users') api.add_resource(UserResource, '/users/<string:username>') api.add_resource(TokenResource, '/token')
def test_no_crossdomain(self, app, client): class Foo(Resource): def get(self): return "data" api = Api(app) api.add_resource(Foo, '/test/') res = client.get('/test/') assert res.status_code == 200 assert 'Access-Control-Allow-Origin' not in res.headers assert 'Access-Control-Allow-Methods' not in res.headers assert 'Access-Control-Max-Age' not in res.headers
def test_no_crossdomain(self): class Foo(Resource): def get(self): return "data" api = Api(self.app) api.add_resource(Foo, '/test/') res = self.get('/test/') self.assertEqual(res.status_code, 200) self.assertNotIn('Access-Control-Allow-Origin', res.headers) self.assertNotIn('Access-Control-Allow-Methods', res.headers) self.assertNotIn('Access-Control-Max-Age', res.headers)
def test_access_control_expose_headers(self, app, client): class Foo(Resource): @cors.crossdomain(origin='*', expose_headers=['X-My-Header', 'X-Another-Header']) def get(self): return "data" api = Api(app) api.add_resource(Foo, '/test/') res = client.get('/test/') assert res.status_code == 200 assert 'X-MY-HEADER' in res.headers['Access-Control-Expose-Headers'] assert 'X-ANOTHER-HEADER' in res.headers['Access-Control-Expose-Headers']
def test_json_float_marshalled(self, app, client): api = Api(app) class FooResource(Resource): fields = {'foo': fields.Float} def get(self): return marshal({"foo": 3.0}, self.fields) api.add_resource(FooResource, '/api') resp = client.get('/api') assert resp.status_code == 200 assert resp.data.decode('utf-8') == '{"foo": 3.0}\n'
def test_access_control_expose_headers(self): class Foo(Resource): @cors.crossdomain(origin='*', expose_headers=['X-My-Header', 'X-Another-Header']) def get(self): return "data" api = Api(self.app) api.add_resource(Foo, '/test/') res = self.get('/test/') self.assertEqual(res.status_code, 200) self.assertIn('X-MY-HEADER', res.headers['Access-Control-Expose-Headers']) self.assertIn('X-ANOTHER-HEADER', res.headers['Access-Control-Expose-Headers'])
def test_json_float_marshalled(self): api = Api(self.app) class FooResource(Resource): fields = {"foo": fields.Float} def get(self): return marshal({"foo": 3.0}, self.fields) api.add_resource(FooResource, "/api") app = self.app.test_client() resp = app.get("/api") self.assertEquals(resp.status_code, 200) self.assertEquals(resp.data.decode("utf-8"), '{"foo": 3.0}\n')
def test_json_float_marshalled(self): api = Api(self.app) class FooResource(Resource): fields = {'foo': fields.Float} def get(self): return marshal({"foo": 3.0}, self.fields) api.add_resource(FooResource, '/api') app = self.app.test_client() resp = app.get('/api') self.assertEquals(resp.status_code, 200) self.assertEquals(resp.data.decode('utf-8'), '{"foo": 3.0}\n')
def test_no_stream_also_marshalled(self, app, client): api = Api(app) class FooResource(Resource): fields = {'foo': fields.Float} @marshal_as_stream_with(fields) def get(self): return {"foo": 6.0} api.add_resource(FooResource, '/api') resp = client.get('/api') assert resp.status_code == 200 assert resp.data.decode('utf-8') == '{"foo": 6.0}\n'
def test_access_control_expose_headers(self, app, client): class Foo(Resource): @cors.crossdomain( origin='*', expose_headers=['X-My-Header', 'X-Another-Header']) def get(self): return "data" api = Api(app) api.add_resource(Foo, '/test/') res = client.get('/test/') assert res.status_code == 200 assert 'X-MY-HEADER' in res.headers['Access-Control-Expose-Headers'] assert 'X-ANOTHER-HEADER' in res.headers[ 'Access-Control-Expose-Headers']
def test_access_control_expose_headers(self): class Foo(Resource): @cors.crossdomain( origin='*', expose_headers=['X-My-Header', 'X-Another-Header']) def get(self): return "data" api = Api(self.app) api.add_resource(Foo, '/test/') res = self.get('/test/') self.assertEqual(res.status_code, 200) self.assertIn('X-MY-HEADER', res.headers['Access-Control-Expose-Headers']) self.assertIn('X-ANOTHER-HEADER', res.headers['Access-Control-Expose-Headers'])
def test_crossdomain(self): class Foo(Resource): @cors.crossdomain(origin='*') def get(self): return "data" api = Api(self.app) api.add_resource(Foo, '/test/') res = self.get('/test/') self.assertEqual(res.status_code, 200) self.assertEqual(res.headers['Access-Control-Allow-Origin'], '*') self.assertEqual(res.headers['Access-Control-Max-Age'], '21600') self.assertIn('HEAD', res.headers['Access-Control-Allow-Methods']) self.assertIn('OPTIONS', res.headers['Access-Control-Allow-Methods']) self.assertIn('GET', res.headers['Access-Control-Allow-Methods'])
def test_crossdomain(self, app, client): class Foo(Resource): @cors.crossdomain(origin='*') def get(self): return "data" api = Api(app) api.add_resource(Foo, '/test/') res = client.get('/test/') assert res.status_code == 200 assert res.headers['Access-Control-Allow-Origin'] == '*' assert res.headers['Access-Control-Max-Age'] == '21600' assert 'HEAD' in res.headers['Access-Control-Allow-Methods'] assert 'OPTIONS' in res.headers['Access-Control-Allow-Methods'] assert 'GET' in res.headers['Access-Control-Allow-Methods']
def register(cls, app, route_prefix=None): api = Api(app) if route_prefix: cls.route_prefix = route_prefix for item in dir(cls.model): item_cls = getattr(getattr(cls.model, item), "__class__", None) if item_cls is None: continue if issubclass(item_cls, (Index, )): item_obj = getattr(cls.model, item) index_cls = indexresource_factory(item_obj, item) index_cls.route_prefix = cls.route_prefix api.add_resource(index_cls, *index_cls.build_routes()) api.add_resource(cls, *cls.build_routes())
def create_app(): """ Initialize the core application. :return app: """ app = Flask(__name__) app.config.from_object('config.Config') api = Api(app) with app.app_context(): from app.resources.users import User api.add_resource(User, "/api/v1/users") return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(configs[config_name]) app.add_url_rule('/', 'index', index) app.add_url_rule('/<path:path>', 'index', index) api = Api(doc='/doc') api.add_resource(UserList, '/api/users/') api.add_resource(User, '/api/users/<email>/') db.init_app(app) api.init_app(app) flask_bcrypt.init_app(app) return app
def run_server(config): app = Flask(__name__) api = Api(app) if config['main']['enable_cors']: logging.info("Enabling CORS for all routes") CORS(app) adapters = setup_adapters(config) api.add_resource(RetrieveAPIv1, '/v1/retrieve', '/retrieve', endpoint='v1_retrieve', resource_class_kwargs={ 'gamefeed_adapter': adapters['gamefeed_adapter'] }) app.run(host='0.0.0.0', port=config['main']['port'], debug=config['main']['debug'])
def test_stream_marshalled_apidecorator(self, app, client): api = Api(app) class FooResource(Resource): fields = {'foo': fields.Float} @marshal_as_stream_with(fields) def get(self): def generate(): yield {"foo": 3.0} return generate() api.add_resource(FooResource, '/api') resp = client.get('/api') assert resp.status_code == 200 assert resp.data.decode('utf-8') == '[{"foo": 3.0}]'
def create_app(test_config=None): """Create and configure an instance of the Flask application.""" app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( # a default secret that should be overridden by instance config SECRET_KEY='dev', # store the database in the instance folder DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.update(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass @app.route('/hello') def hello(): return 'Hello, World!' # register the database commands from .db import db app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL db.init_app(app) api = Api(app) cors = CORS(app) app.add_url_rule('/', endpoint='index') api.add_resource(Mine, '/mine/<string:mine_no>') api.add_resource(MineList, '/mines') return app
def create_app(environment): """Factory Method that creates an instance of the app with the given config.""" app = Flask(__name__) app.config.from_object(configs.Local) db.init_app(app) api = Api(app=app, default='Api', title='Works Single View', version='1.0.0', description="Works Single View API") # enable cross origin resource sharing CORS(app) api.add_resource(RetrieveMusicWork, "/api/v1/<iswc>", endpoint="single_music_work") api.add_resource(UploadMusicWorks, "/upload", endpoint="music_work_upload") # handle default 404 exceptions @app.errorhandler(404) def resource_not_found(error): response = jsonify( dict(error='Not found', message='The requested URL was not found on the server.')) response.status_code = 404 return response # handle default 500 exceptions @app.errorhandler(500) def internal_server_error(error): response = jsonify( dict(error='Internal server error', message="The server encountered an internal error.")) response.status_code = 500 return response return app
def test_will_prettyprint_json_in_debug_mode(self, app, client): api = Api(app) class Foo1(Resource): def get(self): return {'foo': 'bar', 'baz': 'asdf'} api.add_resource(Foo1, '/foo', endpoint='bar') foo = client.get('/foo') # Python's dictionaries have random order (as of "new" Pythons, # anyway), so we can't verify the actual output here. We just # assert that they're properly prettyprinted. lines = foo.data.splitlines() lines = [line.decode() for line in lines] assert "{" == lines[0] assert lines[1].startswith(' ') assert lines[2].startswith(' ') assert "}" == lines[3] # Assert our trailing newline. assert foo.data.endswith(b'\n')
def create_app(config_name): app = Flask(__name__) app.config.from_object(configs[config_name]) gzip = Gzip(app) app.add_url_rule('/', 'index', index) app.add_url_rule('/<path:path>', 'index', index) app.add_url_rule('/_nuxt/<file>', 'staticfiles', staticfiles) api = Api(doc='/doc') api.add_resource(DailyReport, '/api/reports/<date>/') api.add_resource(DailyReport, '/api/reports/') api.add_resource(Stats, '/api/stats/') api.add_resource(Trends, '/api/trends/') api.add_resource(Summary, '/api/summary/') db.init_app(app) api.init_app(app) flask_bcrypt.init_app(app) return app
df.fillna('', inplace=True) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~FINAL DETAILS, SENDING JOB LOG~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # log stream sent off to the data lake #product_to_lake(pdl.name) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~TO SQL~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ engine = create_engine( 'mssql+pyodbc://user:[email protected]/trax-api-data-dev?driver=ODBC+Driver+13+for+SQL+Server' ) df.to_sql("LoadedProduct", engine, if_exists='append', chunksize=None, index=False) except Exception as e: print("Exception in get_product: {}".format(e)) ################################################################################################################################################################## ################################################################################################################################################################## ################################################################################################################################################################## api.add_resource(RecognizedItems, '/RecognizedItems') api.add_resource(Images, '/Images') api.add_resource(Products, '/Products') if __name__ == '__main__': app.run(port=5000, debug=True)
t1.start() print("starting") print(t1) elif (request.args.get('start') == "false"): print("stopping") print(threading.enumerate()) sleep(3) t1.stop() t1.join() print("done") return None, 200 api.add_resource(base, '/') api.add_resource(RecordEndpoint, '/record', methods=['GET']) # Route_Record api.add_resource(StreamEndpoint, '/stream') api.add_resource(paramRecord, '/param/record') api.add_resource(paramBackend, '/param/backend') if __name__ == "__main__": global t1 t1 = None config = Configuration() config.load() t_before = config.get('record', 't_before') t_after = config.get('record', 't_after') t1 = Record(t_before, t_after) t1.start() app.run(host='0.0.0.0', port='2001')
from flask_restplus import Api from run import APP from .auth.views import Auth API = Api(APP) API.add_resource(Auth, '/auth')
parse.add_argument('Auhtorization', location='headers', required=True) parse.add_argument('stoken', dest='stoken', required=True) args = parse.parse_args() if args['Auhtorization'] != "58ff72d1-25e6-441b-8638-49b2dd6d8e8c": return jsonify(error="Unauthorized") globaldb = DBCon() search = globaldb.cursor(buffered=True) try: search.execute("UPDATE Search SET searching=0 where stoken='%s'" % (args['stoken'])) globaldb.commit() search.close() globaldb.close() return jsonify(status="ok") except: return jsonify(error="Unknown stoken") if __name__ == '__main__': api.add_resource(BarQR, '/service/barcode/identify') api.add_resource(uploadImages, '/service/peoplefinder/train') api.add_resource(FaceSearcher, '/service/peoplefinder/search') api.add_resource(Tstatus, '/service/peoplefinder/status') api.add_resource(Taken, '/service/peoplefinder/report') api.add_resource(report_cancel, '/service/peoplefinder/report/cancel') api.add_resource(unmatch, "/service/peoplefinder/unmatch") api.add_resource(status, "/service/peoplefinder/search/status") api.add_resource(stop_searching_person, "/service/peoplefinder/search/unsearch") app.run(host="0.0.0.0", port=int("5002"), debug=True, threaded=True)
abort(404) return data # Blueprint is needed to avoid swagger ui static assets 404 error app = Flask(__name__) # register swagger ui static assets to avoid 404 error when use nginx # as reverse proxy server with sub path app.register_blueprint(apidoc.apidoc, url_prefix='/api/starhistory/1.0') blueprint = Blueprint('starhistory', __name__, url_prefix='/api/starhistory/1.0') api = Api(blueprint, version='1.0', title='Github star history api', description='API for getting star history', doc='/doc/') api.add_resource(StarHistoryAPI, '/<user>/<repo>/', endpoint='starhistory') app.register_blueprint(blueprint) @app.after_request def after_request(response): """ Handle CORS Requests """ # TODO remove CORS support after blog using domain? response.headers.add('Access-Control-Allow-Origin', '*') return response if __name__ == '__main__': app.run()