response.headers.add( self.header_mapping[HEADERS.REMAINING], str(window_stats[1]) ) response.headers.add( self.header_mapping[HEADERS.RESET], str(window_stats[0]) ) return response cache = Cache() compress = Compress() limiter = JSONLimiter(headers_enabled=True, global_limits=["1000 per minute"], key_func=get_remote_address) api = APIManager() jwt = JWT() celery = Celery() mail = Mail() from croplands_api.models import db, User def add_cors_headers(response): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Headers'] = request.headers.get( 'Access-Control-Request-Headers', '*') response.headers['Access-Control-Allow-Methods'] = request.headers.get( 'Access-Control-Request-Method', '') # Do nothing for post, patch, delete etc.. try:
def test_init_app(self): manager = APIManager(flask_sqlalchemy_db=self.db) manager.create_api(self.Person) manager.init_app(self.flaskapp) response = self.app.get('/api/person') assert response.status_code == 200
def add_cors_header(response): response.headers['Access-Control-Allow-Origin'] = '*' response.headers[ 'Access-Control-Allow-Methods'] = 'HEAD, GET, POST, PATCH, PUT, OPTIONS, DELETE' response.headers[ 'Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept' response.headers['Access-Control-Allow-Credentials'] = 'true' return response # Flask-Restless API endpoints # note: GET preprocessors pulled in via review.authn.auth_func manager = APIManager(app, session=db_session, preprocessors=dict(GET_SINGLE=[auth_func], GET_MANY=[auth_func])) collection_blueprint = manager.create_api( Collection, methods=['GET', 'DELETE', 'PATCH', 'POST', 'PUT'], collection_name='collection', url_prefix='/v1', max_results_per_page=600) decision_blueprint = manager.create_api( Decision, methods=['GET', 'DELETE', 'PATCH', 'POST', 'PUT'], collection_name='decision', url_prefix='/v1', max_results_per_page=600) entry_blueprint = manager.create_api( Entry,
return True def is_active(self): return True def is_anonymous(self): return True def get_id(self): return self.id def __repr__(self): return '<User {0}>'.format(self.email) manager = APIManager(app, flask_sqlalchemy_db=db) @app.route('/') def index(): return app.send_static_file('index.html') @app.route('/api/register', methods=['POST']) def register(): json_data = request.json user = User(email=json_data['email'], password=json_data['password']) try: db.session.add(user) db.session.commit() status = 'success'
{%- if cookiecutter.use_sql == 'yes' %} from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() {% endif %} {%- if cookiecutter.use_nosql == 'yes' %} from flask.ext.mongoengine import MongoEngine nosql = MongoEngine() {% endif %} {%- if cookiecutter.use_restless == 'yes' %} try: from flask.ext.restless import APIManager apimanager = APIManager(flask_sqlalchemy_db=db) except ImportError: print ('restless extension not available.') {% endif %} {%- if cookiecutter.use_restless == 'yes' %} try: from flask.ext.admin import Admin admin = Admin(template_mode='bootstrap3') except ImportError: print ('admin extension not available.') {% endif %}
def create_api(app): manager = APIManager(app, flask_sqlalchemy_db=db) manager.create_api(Reports, methods=['GET'], results_per_page=None, url_prefix='/reportgen/api')
def configure_api(app, api_models): api_manager = APIManager(app, flask_sqlalchemy_db=db) for api in api_models: api_manager.create_api(api)
result['start'] = dt.strptime(result['start'], '%Y-%m-%dT%H:%M:%S') \ .strftime('%m/%d/%Y %H:%M:%S') if result['end']: result['end'] = dt.strptime(result['end'], '%Y-%m-%dT%H:%M:%S') \ .strftime('%m/%d/%Y %H:%M:%S') result['html'] = render_template('parts/game.jinja', game=Game.get(result['id'])) def post_submit_single(result=None, **kw): if result: result['html'] = render_template('parts/game.jinja', game=Game.get(result['id'])) restless = APIManager(app, session=db_session) restless.create_api(Game, methods=['GET', 'POST', 'DELETE', 'PATCH'], preprocessors=dict(GET_SINGLE=[check_api_auth], GET_MANY=[check_api_auth], PATCH_SINGLE=[check_api_auth], POST_SINGLE=[check_api_auth]), postprocessors=dict(GET_SINGLE=[post_get_single], POST_SINGLE=[post_submit_single], PATCH_SINGLE=[post_submit_single])) @app.template_global() def get_page_div(page, request_page, *args): 'Creates a div element for a page and sets the requested page visible' classes = "".join([arg for arg in args])
def test_constructor(self): """Tests that no error occurs on instantiation without any arguments to the constructor. """ APIManager()
from flask import Flask, render_template, request from flask.ext.sqlalchemy import * from flask.ext.restless import APIManager from flask.ext.cache import Cache CACHE_TIMEOUT = 60 * 5 application = Flask(__name__) application.config.from_object('config') db = SQLAlchemy(application) manager = APIManager(application, flask_sqlalchemy_db=db) cache = Cache(application) @application.errorhandler(404) def not_found(error): return render_template('404.html'), 404 @application.template_filter('startswith') def startswith_filter(s, l): return s.startswith(l) @application.before_request def return_cached(): # if GET and POST not empty if not request.values and not request.path.startswith( '/static') and not request.path.startswith('/search'):
def create_app(config_mode=None, config_file=None): """ Creates the Flask application Kwargs: config_mode (str): The configuration mode. Must be a `class` in `config.py`. One of ('Production', 'Development', 'Test', 'Docker') config_file (str): The configuration file. Returns: (obj): Flask application Examples: >>> create_app('Test') <Flask 'app'> """ app = Flask(__name__) app.register_blueprint(blueprint) mgr = APIManager(app, flask_sqlalchemy_db=db) cache_config = {} if config_mode: app.config.from_object(getattr(config, config_mode)) elif config_file: app.config.from_pyfile(config_file) else: app.config.from_envvar('APP_SETTINGS', silent=True) memcached_servers = getenv('MEMCACHIER_SERVERS', getenv('MEMCACHE_SERVERS')) if app.config['PROD'] and app.config['MEMCACHE']: cache_config['CACHE_TYPE'] = 'spreadsaslmemcachedcache' cache_config['CACHE_MEMCACHED_SERVERS'] = [memcached_servers] cache_config['CACHE_MEMCACHED_USERNAME'] = getenv( 'MEMCACHIER_USERNAME') cache_config['CACHE_MEMCACHED_PASSWORD'] = getenv( 'MEMCACHIER_PASSWORD') elif app.config['MEMCACHE']: cache_config['CACHE_TYPE'] = 'memcached' cache_config['CACHE_MEMCACHED_SERVERS'] = [memcached_servers] else: cache_config['CACHE_TYPE'] = 'simple' cache.init_app(app, config=cache_config) db.init_app(app) CORS(app) Compress(app) @app.route('/') def home(): return 'Welcome to the HDX Age API!' kwargs = { 'methods': app.config['API_METHODS'], 'validation_exceptions': API_EXCEPTIONS, 'allow_functions': app.config['API_ALLOW_FUNCTIONS'], 'allow_patch_many': app.config['API_ALLOW_PATCH_MANY'], 'max_results_per_page': app.config['API_MAX_RESULTS_PER_PAGE'], 'url_prefix': app.config['API_URL_PREFIX'] } # Create API endpoints from `models.py`. Each model is available at # the endpoint `/<tablename>`. create_api = partial(mgr.create_api, **kwargs) with app.app_context(): map(create_api, _get_tables()) return app
def test_init_app_split_initialization(self): manager = APIManager(session=self.session) manager.init_app(self.flaskapp) manager.create_api(self.Person, app=self.flaskapp) response = self.app.get('/api/person') assert response.status_code == 200
# -*- coding: utf-8 -*- from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask.ext.mail import Mail mail = Mail() from flask.ext.cache import Cache cache = Cache() from flask.ext.login import LoginManager login_manager = LoginManager() from flask.ext.openid import OpenID oid = OpenID() from flask.ext.restless import APIManager rest = APIManager() from flask.ext.wtf.csrf import CsrfProtect csrf = CsrfProtect() import zmq zmq_context = zmq.Context()
from angular_flask import app from flask.ext.restless import APIManager api_manager = APIManager(app)
#This is for RPC api # api = restful.Api(app) # api.decorators=[cors.crossdomain(origin='*',headers=['Origin', 'X-Requested-With', 'Content-Type', 'Accept'])] # api.add_resource(resources.customer.Customer, '/api/customers/<string:uid>') # api.add_resource(resources.customer.Customers, '/api/customers') # api.add_resource(resources.dataset.Dataset, '/api/datasets/<string:uid>') # api.add_resource(resources.dataset.Datasets, '/api/datasets') # api.add_resource(resources.entry.Entry, '/api/entries/<string:uid>') # api.add_resource(resources.entry.Entries, '/api/entries') # api.add_resource(resources.user.User, '/api/users/<string:uid>') # api.add_resource(resources.user.Users, '/api/users') # api.add_resource(resources.schema.DatasetColumns, '/api/datasetColumns') # api.add_resource(resources.schema.DatasetColumn, '/api/datasetColumns/<string:uid>') # api.add_resource(resources.schema.EntryCells, '/api/entryCells') # api.add_resource(resources.schema.DatasetColumnOptions,'/api/datasetColumnOptions') #This is for data api manager = APIManager(app, session=db.Session()) manager.create_api(User) manager.create_api(Simulation) manager.create_api(Argument) manager.create_api(Diagnostic) manager.create_api(Kernel) manager.create_api(Note) if __name__ == '__main__': app.run(debug=True)