def create_app(): from .model import Data app = Flask(__name__) app.config.from_mapping(config) db.init_app(app) db.app = app db.create_all() cache.init_app(app) admin = Admin(app, name='covid19', template_mode='bootstrap3') admin.add_view(ModelView(Data, db.session)) def add_cors_headers(response): response.headers['Access-Control-Allow-Origin'] = '*' return response manager = APIManager(app, flask_sqlalchemy_db=db) blueprint = manager.create_api_blueprint( Data, app=app, results_per_page=-1, max_results_per_page=-1, postprocessors={'GET_MANY': [cache_postprocessor]}) blueprint.after_request(add_cors_headers) toolbar = DebugToolbarExtension(app) @app.before_request def preprocess_request(): return cache.get(get_cache_key()) return app
class MyPlaceService(): """ A RESTful service, exposing the MyPlace model, interacting with a persistence tier (using SQLAlchemy for persistence). C Currently delegates some validations to the model and can further implement auth/authz Handles exceptions Handles some pagination Exposes a blueprint that can be used for embedding this service in different apps """ # define the application as a class obj app = flask.Flask("mypoiservice") def __init__(self): """ Initialize the application, its context, and the API manager """ self.app.config.from_object(config) # init the logging and context self.setup_logging(); self.app.test_request_context().push() # grab the database from the model, init the service db.init_app(self.app) # Create the Flask-Restless API manager. self.manager = APIManager(self.app, flask_sqlalchemy_db=db) # define the blueprint self.myplaceServiceBlueprint = self.manager.create_api_blueprint( MyPlace, # if a custom URL prefix is desired: url_prefix='/api/', methods=['GET', 'POST', 'PUT', 'DELETE'], preprocessors=dict(GET_MANY=[self.preprocessor])) self.app.logger.info('MyService blueprint created') def setup_logging(self): """ Set up some rudimentary logging for production *and* for hosting situations It might be better to move this to the tools package, as it can be reused, but will need more configuration for usage by different services (TODO) """ #if not config.DEBUG: # file_handler = RotatingFileHandler('logs/myservice.log', 'a', 1 * 1024 * 1024, 10) # file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')) # self.app.logger.setLevel(logging.INFO) # file_handler.setLevel(logging.INFO) # self.app.logger.addHandler(file_handler) # self.app.logger.info("App hosting logging started...") if config.HOSTING is not None: stream_handler = logging.StreamHandler() self.app.logger.addHandler(stream_handler) self.app.logger.setLevel(logging.INFO) self.app.logger.info("App hosting logging started...") def get_blueprint(self): """ Return the service blueprint for inclusion in apps """ return self.myplaceServiceBlueprint; def preprocessor(self, search_params=None, **kw): """ Preprocessor can be used for auth if needed for now, let it remain unused """ return def run_standalone(self): """ For when the library needs to be up and running on its own """ self.app.register_blueprint(self.myplaceServiceBlueprint) self.app.run(config.API_SERVICE_HOST, config.API_SERVICE_PORT) def shutdown_server(self): """ In case we want to shut down the standalone service (a hook can be implemented to trigger this) """ func = request.environ.get('werkzeug.server.shutdown') if func is None: raise RuntimeError('Not running with the Werkzeug Server') func() return
saldo.lagersaldo = nytt_saldo db.session.commit() else: nytt_lagersaldo = Lagersaldon(result['vara'], result['stad'], result['antal']) db.session.add(nytt_lagersaldo) db.session.commit() # creates if not created, uncomment drop_all if database should be cleared # db.drop_all() db.create_all() api_manager = APIManager(app, flask_sqlalchemy_db=db) lagersaldo_blueprint = api_manager.create_api_blueprint(Lagersaldon, methods=['GET']) lagersaldo_blueprint.after_request(add_cors_headers) leveranser_blueprint = api_manager.create_api_blueprint( Leveranser, methods=['POST', 'OPTIONS'], validation_exceptions=[AssertionError], postprocessors={'POST': [add_to_lagersaldon]}) leveranser_blueprint.after_request(add_cors_headers) app.register_blueprint(lagersaldo_blueprint) app.register_blueprint(leveranser_blueprint) @app.route('/') def index():
from flask_restless import APIManager from application import app, db from .models import Author, Book manager = APIManager(app, flask_sqlalchemy_db=db) author_bp = manager.create_api_blueprint(Author, methods=['GET', 'POST', 'PUT', 'DELETE']) book_bp = manager.create_api_blueprint(Book, methods=['GET', 'POST', 'PUT', 'DELETE']) library_bp = manager.create_api_blueprint(Book, methods=['GET'], url_prefix='', collection_name='library/')
PATCH_MANY = [commit_session], DELETE_SINGLE = [commit_session], DELETE_MANY = [commit_session] )) def add_cors_headers(response): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Control-Allow-Headers'] = 'Apikey,Content-Type' response.headers['Access-Control-Allow-Methods'] = 'GET,POST,HEAD,OPTIONS,PUT,DELETE,PATCH' return response # Create API endpoints, which will be available at /api/<tablename> by # default. Allowed HTTP methods can be specified as well. blueprint1 = manager.create_api_blueprint(Tarea, methods=['GET', 'PATCH', 'POST', 'DELETE', 'OPTIONS']) blueprint1.after_request(add_cors_headers) app.register_blueprint(blueprint1) @app.teardown_appcontext def shutdown_session ( exception=None ): db.session.commit() db.session.close() print("Commiting") if __name__ == "__main__": app.run(host="0.0.0.0",port=5000)
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # not using sqlalchemy event system, hence disabling it config[config_name].init_app(app) # Set up extensions mail.init_app(app) db.init_app(app) login_manager.init_app(app) csrf.init_app(app) compress.init_app(app) RQ(app) with app.app_context(): from .models import User, Role, Campus, Location, Department, Equipment_Type, Condition, Equipment, Equipment_Reservation, Space_Type, Space, Ammenity_Type, Space_Ammenity, Space_Reservation flask_manager = APIManager(app, flask_sqlalchemy_db=db) flask_manager.create_api(User, methods=[], results_per_page=0) flask_manager.create_api(Ammenity_Type, methods=['GET'], results_per_page=0) flask_manager.create_api(Campus, methods=['GET'], results_per_page=0) location_blueprint = flask_manager.create_api_blueprint(Location, methods=['GET', 'POST'], results_per_page=0) csrf.exempt(location_blueprint) app.register_blueprint(location_blueprint) flask_manager.create_api(Department, methods=['GET'], results_per_page=0) equipment_blueprint = flask_manager.create_api_blueprint(Equipment, methods=['GET', 'POST'], results_per_page=0) csrf.exempt(equipment_blueprint) app.register_blueprint(equipment_blueprint) flask_manager.create_api(Equipment_Reservation, methods=['GET'], results_per_page=0) flask_manager.create_api(Equipment_Type, methods=['GET'], results_per_page=0) flask_manager.create_api(Role, methods=['GET'], results_per_page=0) flask_manager.create_api(Space_Ammenity, methods=['GET'], results_per_page=0) flask_manager.create_api(Space_Reservation, methods=['GET'], results_per_page=0) flask_manager.create_api(Space_Type, methods=['GET'], results_per_page=0) space_blueprint = flask_manager.create_api_blueprint(Space, methods=['GET', 'POST'], results_per_page=0) csrf.exempt(space_blueprint) app.register_blueprint(space_blueprint) # Register Jinja template functions from .utils import register_template_utils register_template_utils(app) # Set up asset pipeline assets_env = Environment(app) dirs = ['assets/styles', 'assets/scripts'] for path in dirs: assets_env.append_path(os.path.join(basedir, path)) assets_env.url_expire = True assets_env.register('app_css', app_css) assets_env.register('app_js', app_js) assets_env.register('vendor_css', vendor_css) assets_env.register('vendor_js', vendor_js) # Configure SSL if platform supports it if not app.debug and not app.testing and not app.config['SSL_DISABLE']: from flask_sslify import SSLify SSLify(app) # Create app blueprints from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .account import account as account_blueprint app.register_blueprint(account_blueprint, url_prefix='/account') from .admin import admin as admin_blueprint app.register_blueprint(admin_blueprint, url_prefix='/admin') from .reserve import reserve as reserve_blueprint app.register_blueprint(reserve_blueprint, url_prefix='/reserve') from .api import api as api_blueprint print("api should be exempt") app.register_blueprint(api_blueprint, url_prefix='/api') csrf.exempt(api_blueprint) return app
'project_extended', engine, tables, models) # Register all the blueprints for blueprint in [ sum_obs_blue, project_view_blue, filter_blue, zone_facts, project_extended ]: application.register_blueprint(blueprint) # Register Flask Restless blueprints for model in models: # https://github.com/jfinkels/flask-restless/pull/436 model.__tablename__ = model.__table__.name blueprint = manager.create_api_blueprint(model, url_prefix='/api/raw', results_per_page=100, max_results_per_page=10000, methods=['GET']) application.register_blueprint(blueprint) ####################### #Real endpoints ####################### @application.route('/api/meta', methods=['GET']) @cross_origin() def get_meta(): ''' Outputs the meta.json to the front end '''