def test_should_add_HealthCheckResource(self, api_mock): api_instance_mock = self.mock.MagicMock() api_mock.return_value = api_instance_mock api.create_api(self.app_mock) self.assertTrue( any(mock_call == base.call(api.resources.HealthCheckResource, '/api/healthcheck') for mock_call in api_instance_mock.add_resource.mock_calls))
def test_should_add_login_resource_with_end_points(self, api_mock): api_instance = self.mock.MagicMock() api_mock.return_value = api_instance api.create_api('APP') api_instance.add_resource.assert_any_call( 'LoginResource', '/api/login' )
def test_should_add_AvatarResource(self, api_mock): api_instance_mock = self.mock.MagicMock() api_mock.return_value = api_instance_mock api.create_api(self.app_mock) self.assertTrue( any(mock_call == base.call(api.resources.AvatarResource, '/api/account/avatar') for mock_call in api_instance_mock.add_resource.mock_calls))
def test_should_add_task_resource_with_end_points(self, api_mock): api_instance = self.mock.MagicMock() api_mock.return_value = api_instance api.create_api('APP') api_instance.add_resource.assert_any_call( 'TaskResource', '/api/projects/<int:project_id>/stories/<int:story_id>/tasks', '/api/projects/<int:project_id>/stories/<int:story_id>/tasks/<int:task_id>' )
def test_should_add_NoteResource(self, api_mock): api_instance_mock = self.mock.MagicMock() api_mock.return_value = api_instance_mock api.create_api(self.app_mock) self.assertTrue( any(mock_call == base.call(api.resources.NoteResource, '/api/notes', '/api/notes/<int:note_id>') for mock_call in api_instance_mock.add_resource.mock_calls))
def start(): """ Starts up a HTTP server attached to the provider port, and optionally in development mode (which is ideal for local development but unideal for production use). """ parser = argparse.ArgumentParser( description='Starts your application\'s HTTP server.') parser.add_argument('--port', '-p', help='The port to listen on', default=8000) parser.add_argument( '--prod', help='If specified the server is started in production mode, where ' + 'the server isn\'t restarted as changes to the source code occur.', action='store_true') args = parser.parse_args() # We set the log level explicitly, as to avoid other libraries manipulating # it for us. root_logger = logging.getLogger() root_logger.setLevel(os.environ.get('LOG_LEVEL', default=logging.INFO)) # In production, write all logs to stdout but format them using JSON # so that they're queriable by fields like their severity, etc. if args.prod: handler = logging.StreamHandler() handler.setFormatter(StackdriverJsonFormatter()) root_logger.addHandler(handler) app = Flask(__name__) # Bind the API functionality to our application. You can add additional # API endpoints by editing api.py. app.register_blueprint(create_api(), url_prefix='/') # In production we use a HTTP server appropriate for production. if args.prod: http_server = WSGIServer(('0.0.0.0', args.port), app, log=root_logger, error_log=root_logger) app.logger.info(f'Server listening at http://0.0.0.0:{args.port}') http_server.serve_forever() else: app.run(host='0.0.0.0', port=args.port)
# raise -> throw error # Unfortunately for us, our API is not performing any type of validation on the # incoming data. In order to validate the POST data, we need to use a hook provided # by Flask-Restless. Flask-Restless calls these hooks request preprocessors and # postprocessors. # Let's take a look at how to use the POST preprocessor to perform some validation on # our comment data def post_preprocessor(data, **kwargs): form = CommentForm(data=data) if form.validate(): return form.data else: raise ProcessingException(description='Invalid form submission.', code=400) api.create_api(Comment, methods=['GET', 'POST'], preprocessors={'POST': [post_preprocessor]}) # Our API will now validate the submitted comment using the validation logic from # our CommentForm . We do this by specifying a preprocessor for the POST method. # The POST preprocessor, which we've implemented as post_preprocessor , accepts # the deserialized POST data as an argument. We can then feed that data into our # CommentForm and call it's validate() method. In the event where validation fails, # we will raise a ProcessingException , signaling to Flask-Restless that this data was # unprocessable and returning a 400 Bad Request response.
from flask_restless import ProcessingException from app import api from entries.forms import CommentForm from models import Comment def post_preprocessor(data, **kwargs): form = CommentForm(data=data) if form.validate(): return form.data else: raise ProcessingException(description='Invalid form submission.', code=400) api.create_api( Comment, include_columns=['id', 'name', 'url', 'body', 'created_timestamp'], include_methods=['gravatar'], methods=['GET', 'POST'], preprocessors={ 'POST': [post_preprocessor], })
from app import api from models import Comment api.create_api(Comment, methods=['GET', 'POST'])
def client(settings_with_rsa): api = create_api(settings_with_rsa) api.dependency_overrides[get_settings] = lambda: settings_with_rsa api.dependency_overrides[send_code_producer] = lambda: mock client = TestClient(api) return client
def start(): """ Starts up a HTTP server attached to the provider port, and optionally in development mode (which is ideal for local development but unideal for production use). """ parser = argparse.ArgumentParser( description='Starts your application\'s HTTP server.') parser.add_argument('--port', '-p', help='The port to listen on', default=8000) parser.add_argument( '--prod', help='If specified the server is started in production mode, where ' + 'the server isn\'t restarted as changes to the source code occur.', action='store_true') args = parser.parse_args() # Locally we don't specify any handlers, which causes `basicConfig` to set # up one for us that writes human readable messages. handlers = None # If we're in production we setup a handler that writes JSON log messages # in a format that Google likes. if args.prod: json_handler = logging.StreamHandler() json_handler.setFormatter(StackdriverJsonFormatter()) handlers = [json_handler] logging.basicConfig(level=os.environ.get('LOG_LEVEL', default=logging.INFO), handlers=handlers) logger = logging.getLogger() logger.debug("AHOY! Let's get this boat out to water...") app = Flask("app") # Bind the API functionality to our application. You can add additional # API endpoints by editing api.py. logger.debug("Starting: init API...") app.register_blueprint(create_api(), url_prefix='/') logger.debug("Complete: init API...") # In production we use a HTTP server appropriate for production. if args.prod: logger.debug("Starting: gevent.WSGIServer...") # There are two proxies -- the one that's run as a sibling of this process, and # the Ingress controller that runs on the cluster. # See: https://skiff.allenai.org/templates.html num_proxies = 2 proxied_app = ProxyFix(app, x_for=num_proxies, x_proto=num_proxies, x_host=num_proxies, x_port=num_proxies) http_server = WSGIServer(('0.0.0.0', args.port), proxied_app, log=logger, error_log=logger) app.logger.info(f'Server listening at http://0.0.0.0:{args.port}') http_server.serve_forever() else: logger.debug("Starting: Flask development server...") num_proxies = 1 proxied_app = ProxyFix(app, x_for=num_proxies, x_proto=num_proxies, x_host=num_proxies, x_port=num_proxies) app.run(host='0.0.0.0', port=args.port)
def create_api(): from app import api api.create_api(web_app)
from app import api, models callbacks_blueprint = api.create_api(models.Callbacks, methods=['DELETE', 'GET', 'POST', 'PUT'], max_results_per_page=-1) callback_data_blueprint = api.create_api( models.CallbackDetails, methods=['DELETE', 'GET', 'PUT', 'POST']) callback_data_blueprint = api.create_api( models.ActiveTickets, methods=['DELETE', 'GET', 'PUT', 'POST']) callback_data_blueprint = api.create_api( models.User, methods=['DELETE', 'GET', 'PUT', 'POST'])
def test_should_instantiate_api(self, api_mock): api.create_api(self.app_mock) self.assertTrue(api_mock.called)
from flask.ext.restless import ProcessingException from app import api from entries.forms import CommentForm from models import Comment def post_preprocessor(data, **kwargs): form = CommentForm(data=data) if form.validate(): return form.data else: raise ProcessingException( description='Invalid form submission.', code=400) api.create_api( Comment, methods=['GET', 'POST'], include_columns=['id', 'name', 'url', 'body', 'created_timestamp'], include_methods=['gravatar'], preprocessors={ 'POST': [post_preprocessor], })
from sanic import Sanic from gino.ext.sanic import Gino from app import config as config_module from app import database, api from app.domain import security_domain config = config_module.get_config() app = Sanic() app.config.from_object(config) database.AppRepository.db = Gino(app=app) api.create_api(app) @app.middleware('request') async def print_on_request(request): print(request) token = request.cookies.get('myToken') decrypted_token = security_domain.Security.decrypt_token(token) if decrypted_token is not None: decrypted_token['datetime'] = str(datetime.datetime.now()) setattr(request, 'authenticated', True) setattr(request, 'user', decrypted_token) def run():
from app import api, models callbacks_blueprint = api.create_api(models.Callbacks, methods=['DELETE', 'GET', 'POST', 'PUT'], max_results_per_page=-1) callback_data_blueprint = api.create_api(models.CallbackDetails, methods=['DELETE', 'GET', 'PUT', 'POST']) callback_data_blueprint = api.create_api(models.ActiveTickets, methods=['DELETE','GET', 'PUT', 'POST']) callback_data_blueprint = api.create_api(models.User, methods=['DELETE','GET', 'PUT', 'POST'])
import os from app.api import create_api conf = os.getenv("API_CONF") api = create_api(conf) if __name__ == '__main__': api.run()
def setUp(self) -> None: self.api = create_api("testing") self.api_context = self.api.app_context() self.api_context.push() self.client = self.api.test_client() db.create_all()
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from flask import Flask, g, request from flask_sqlalchemy import SQLAlchemy from app import config as config_module, api, database, auth, commands config = config_module.get_config() web_app = Flask(__name__) web_app.config.from_object(config) database.AppRepository.db = SQLAlchemy(web_app) commands.register(web_app) api.create_api(web_app) @web_app.before_request def before_request(): token = request.cookies.get('evePlanetaryUserToken', None) username = request.cookies.get('evePlanetaryUserName') api_token = request.headers.get('API-TOKEN', None) authenticated = None user = None user_entity = None new_token = None if token and username: user, new_token, user_entity = auth.check_auth_token(token) elif api_token: authenticated = api.authenticate_api(api_token)
from flask.ext.restless import ProcessingException from app import api # from entries.forms import CommentForm from models import Comment, Entry def post_preprocessor(data, **kwargs): form = CommentForm(data=data) if form.validate(): return form.data else: raise ProcessingException(description='Invalid form submission.', code=400) # api.create_api( # Comment, # include_columns=['id', 'name', 'url', 'body','created_timestamp'], # include_methods=['gravatar'], # methods=['GET', 'POST'],#,'DELETE'], # preprocessors={ # 'POST': [post_preprocessor], # }) api.create_api(Entry)