def init_resources(app): api = Api() api.add_resource(HealthCheckHandler, "/risk/health-check") api.add_resource(RiskHandler, "/risk/v1") api.init_app(app)
def init_routes(app): api = Api() api.add_resource(HealthCheckandler, '/health-check') api.add_resource(SnsTopic, '/user/publish') api.init_app(app)
def create_app(config): app = Flask('fedlearner_webconsole') app.config.from_object(config) db.init_app(app) migrate.init_app(app, db) jwt.init_app(app) # Error handlers app.register_error_handler(400, _handle_bad_request) app.register_error_handler(WebConsoleApiException, make_response) app.register_error_handler(Exception, _handle_uncaught_exception) api = Api(prefix='/api/v2') initialize_auth_apis(api) initialize_project_apis(api) initialize_workflow_template_apis(api) initialize_workflow_apis(api) # A hack that use our customized error handlers # Ref: https://github.com/flask-restful/flask-restful/issues/280 handle_exception = app.handle_exception handle_user_exception = app.handle_user_exception api.init_app(app) app.handle_exception = handle_exception app.handle_user_exception = handle_user_exception if app.config.get('START_GRPC_SERVER', True): rpc_server.stop() rpc_server.start(app) if app.config.get('START_SCHEDULER', True): scheduler.stop() scheduler.start(app) return app
def create_app(object_name): app = Flask(__name__) app.config.from_object(config[object_name]) app.response_class = MyResponse db.init_app(app) mail.init_app(app) rest_api = Api() rest_api.add_resource(CommentApi, '/api/comment', '/api/comment/<int:comment_id>') rest_api.add_resource(AllCommentsApi, '/api/all_comments') rest_api.add_resource(RegisterApi, '/api/register') rest_api.add_resource(LoginApi, '/api/login') rest_api.add_resource(LogoutApi, '/api/logout') rest_api.add_resource(UserInfoApi, '/api/user_info', '/api/user_info/<int:user_id>') rest_api.add_resource(AvatarApi, '/api/upload_avatar') rest_api.add_resource(BindEmailApi, '/api/bind_email') rest_api.add_resource(ConfirmEmailApi, '/api/confirm_email') rest_api.add_resource(ChangePasswordApi, '/api/change_password') rest_api.add_resource(SendVerifyEmailApi, '/api/send_verify_email') rest_api.add_resource(ForgetPasswordApi, '/api/forget_password') rest_api.add_resource(ReviseUserInfoApi, '/api/revise_user_info') rest_api.init_app(app) configure_uploads(app, photos) return app
def create_app(): app.config.from_object(__name__) # uri统一资源匹配符 # SQLALCHEMY_DATABASE_URI配置数据库连接的参数 Bootstrap(app) api = Api() api.init_app(app) db.init_app(app) ST.SERVERSTATICROOT = os.path.join(app.root_path, 'static') @app.cli.command("initdb") def initdb_command(): db.drop_all() db.create_all() res = seeds() print(f"db create initialized") @app.cli.command("create-user") @click.argument("username", default="admin") @click.argument("password", default="admin") def create_user(username: str, password: str): adduser(username, password) @app.cli.command("search_user") @click.argument("user_id", default=1) def search(user_id): search_user_info(user_id) app.register_blueprint(frontend) return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) api1 = Api() db.init_app(app) celery.__init__(app.name, broker=app.config['CELERY_BROKER_URL']) # # celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) # print app.name celery.conf.update(app.config) # print celery._preconf['BROKER_URL'] mail.init_app(app) from .api_1_0.goods import GoodsAPI api1.add_resource(GoodsAPI, '/api/v2.0/goods', endpoint='goods') api1.init_app(app) from .api_1_0 import api as api_1_0_blueprint app.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1.0') from .main import main as main_blueprint app.register_blueprint(main_blueprint) return app
def main(debug=False, port=5001, tmpdir='', federator=''): """Run Flask app.""" errors = { 'NODATA': { 'message': "Empty dataset.", 'status': 204, }, } if tmpdir: tempfile.tempdir = tmpdir app = Flask(__name__) api = Api(errors=errors) ## mediator endpoint # DQ query method (direct query) api.add_resource( DQResource, "%s%s" % (settings.EIDA_MEDIATOR_DQ_PATH, settings.MEDIATOR_QUERY_METHOD_TOKEN)) # version method api.add_resource( VersionResource, "%s%s" % (settings.EIDA_MEDIATOR_PATH, settings.MEDIATOR_VERSION_METHOD_TOKEN)) api.init_app(app) app.config.update(PORT=port, TMPDIR=tmpdir, FEDERATOR=federator) app.run(threaded=True, debug=debug, port=port)
def setup_app(self): """ Setup and configure the Flask app with its API. :returns: The configured Flask application instance. :rtype: :py:class:`flask.Flask` """ api = Api() app_config = { 'PROPAGATE_EXCEPTIONS': True, 'SQLALCHEMY_DATABASE_URI': self.args.db_url, 'SQLALCHEMY_TRACK_MODIFICATIONS': False, } # query method api.add_resource( StationLiteResource, "%s%s" % (settings.EIDA_ROUTING_PATH, settings.FDSN_QUERY_METHOD_TOKEN)) # version method api.add_resource( StationLiteVersionResource, "%s%s" % (settings.EIDA_ROUTING_PATH, settings.FDSN_VERSION_METHOD_TOKEN)) # application.wadl method api.add_resource( StationLiteWadlResource, "%s%s" % (settings.EIDA_ROUTING_PATH, settings.FDSN_WADL_METHOD_TOKEN)) app = create_app(config_dict=app_config) api.init_app(app) return app
def create_app(config): # format logging logging.config.dictConfig(LOGGING_CONFIG) before_hook_path = os.getenv('FEDLEARNER_WEBCONSOLE_BEFORE_APP_START') if before_hook_path: module_path, func_name = before_hook_path.split(':') module = importlib.import_module(module_path) # Dynamically run the function getattr(module, func_name)() app = Flask('fedlearner_webconsole') app.config.from_object(config) db.init_app(app) migrate.init_app(app, db) jwt.init_app(app) # Error handlers app.register_error_handler(400, _handle_bad_request) app.register_error_handler(404, _handle_not_found) app.register_error_handler(WebConsoleApiException, make_response) app.register_error_handler(Exception, _handle_uncaught_exception) api = Api(prefix='/api/v2') initialize_auth_apis(api) initialize_project_apis(api) initialize_workflow_template_apis(api) initialize_workflow_apis(api) initialize_job_apis(api) initialize_dataset_apis(api) initialize_setting_apis(api) initialize_mmgr_apis(api) if os.environ.get('FLASK_ENV') != 'production': initialize_debug_apis(api) # A hack that use our customized error handlers # Ref: https://github.com/flask-restful/flask-restful/issues/280 handle_exception = app.handle_exception handle_user_exception = app.handle_user_exception api.init_app(app) app.handle_exception = handle_exception app.handle_user_exception = handle_user_exception # Inits k8s related stuff first since something in composer # may depend on it if Envs.FLASK_ENV == 'production' or Envs.K8S_CONFIG_PATH is not None: k8s_watcher.start() if app.config.get('START_GRPC_SERVER', True): rpc_server.stop() rpc_server.start(app) if app.config.get('START_SCHEDULER', True): scheduler.stop() scheduler.start(app) if app.config.get('START_COMPOSER', True): with app.app_context(): composer.run(db_engine=db.get_engine()) metrics.emit_counter('create_app', 1) return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) db.init_app(app) @app.before_first_request def create_tables(): db.create_all() jwt.init_app(app) @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decrypted_token): jti = decrypted_token['jti'] return models.RevokedTokenModel.is_jti_blacklisted(jti) import models, resources api = Api() api.add_resource(resources.UserRegistration, '/registration') api.add_resource(resources.UserLogin, '/login') api.add_resource(resources.UserLogoutAccessRefresh, '/logout') api.add_resource(resources.TokenRefresh, '/refresh-token') # api.add_resource(resources.AllUsers, '/users') # for test purposes api.add_resource(resources.SecretResource, '/secret') api.add_resource(resources.IsAccessTokenValidResource, '/validate-token') api.init_app(app) return app
def initialize_apps(app): api = Api(app=app, errors=errors) Bcrypt(app=app) JWTManager(app=app) initialize_db(app=app) initialize_routes(api=api) api.init_app(app)
def init_app(): app = Flask(__name__) api = Api(app) api.add_resource(QuoteOfDay, '/', '/quote/') api.add_resource(RandomQuote, '/quote/<author>') api.init_app(app) return app
def initialize_web_server(reactor, simulator, port, database): """Initialize the web server :param reactor: the twisted reactor to use :param simulator: the Simulator ubject that will be used :param port: the port that the server will listen to :param database: the database to use """ logger.debug("The web server will listen at port %d", port) app = Flask(__name__) api = Api() _add_fdm_resources(api, simulator.fdm, simulator.aircraft) _add_instrument_resources(api, simulator.aircraft.instruments) _add_sensor_resources(api, simulator.aircraft.sensors) api.add_resource(AircraftResource, "/aircraft", resource_class_args=(simulator.aircraft,)) api.add_resource( EngineResource, "/aircraft/engine", resource_class_args=(simulator.aircraft.engine,) ) api.add_resource( FlightControlsResource, "/aircraft/controls", resource_class_args=(simulator.aircraft.controls,) ) api.add_resource( SimulatorControlResource, "/simulator", resource_class_args=(simulator,) ) api.add_resource(WaypointResource, "/map/waypoint/<name>", resource_class_args=(database,)) api.add_resource(WaypointsResource, "/map/waypoints", resource_class_args=(database,)) api.init_app(app) @app.route("/") def index(): return render_template("index.html") resource = WSGIResource(reactor, reactor.getThreadPool(), app) site = server.Site(resource) reactor.listenTCP(port, site)
def init_app(app: 'Flask') -> None: """Initialize API v1""" api = Api() api.add_resource(Post, 'post') api.add_resource(User, 'user') bp = Blueprint('api_v1', __name__, url_prefix='/api/v1/<username>/') bp.url_value_preprocessor(pull_user) api.init_app(bp) app.register_blueprint(bp)
def init_resources(app): api = Api() api.add_resource(HealthCheckHandler, "/kikis-delivery-service/health-check") api.add_resource(DeliveryHandler, "/kikis-delivery-service/delivery") api.add_resource(AddressHandler, "/kikis-delivery-service/address") api.add_resource(UserHandler, "/kikis-delivery-service/user") api.add_resource(ReportHandler, "/kikis-delivery-service/report") api.init_app(app)
def creat_app(): app = Flask(__name__) app.config.from_pyfile('db.cfg') db.init_app(app) api = Api() api.add_resource(MemoList, '/memo') api.init_app(app) return app
def init_api(app): api = Api() api.add_resource(HealthCheck, "/health-check") api.add_resource(CriarAluno, "/aluno") api.add_resource(CadastrarProvas, "/gabaritos") api.add_resource(Prova, "/provas/<cpf>/<idProva>") api.add_resource(Aprovado, "/aprovados") api.init_app(app)
def create_app(config): # format logging logging.config.dictConfig(LOGGING_CONFIG) app = Flask('fedlearner_webconsole') app.config.from_object(config) jwt.init_app(app) # Error handlers app.register_error_handler(400, _handle_bad_request) app.register_error_handler(404, _handle_not_found) app.register_error_handler(WebConsoleApiException, make_response) app.register_error_handler(Exception, _handle_uncaught_exception) # TODO(wangsen.0914): This will be removed sooner! db.init_app(app) api = Api(prefix='/api/v2') initialize_auth_apis(api) initialize_project_apis(api) initialize_workflow_template_apis(api) initialize_workflow_apis(api) initialize_job_apis(api) initialize_dataset_apis(api) initialize_setting_apis(api) initialize_mmgr_apis(api) initialize_sparkapps_apis(api) if os.environ.get('FLASK_ENV') != 'production' or Envs.DEBUG: initialize_debug_apis(api) # A hack that use our customized error handlers # Ref: https://github.com/flask-restful/flask-restful/issues/280 handle_exception = app.handle_exception handle_user_exception = app.handle_user_exception api.init_app(app) app.handle_exception = handle_exception app.handle_user_exception = handle_user_exception # Inits k8s related stuff first since something in composer # may depend on it if Envs.FLASK_ENV == 'production' or Envs.K8S_CONFIG_PATH is not None: k8s_watcher.start() if app.config.get('START_GRPC_SERVER', True): rpc_server.stop() rpc_server.start(app) if app.config.get('START_SCHEDULER', True): scheduler.stop() scheduler.start(app) if app.config.get('START_COMPOSER', True): with app.app_context(): composer.run(db_engine=db.get_engine()) metrics.emit_counter('create_app', 1) return app
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_object(Config) else: # load the test config if passed in app.config.from_mapping(test_config) @app.route('/hello') def hello(): return 'Hello, World!' # init db db.init_app(app) # Handle request. @app.before_request def before_request(): print(request.headers) # init RESTful api api = Api(app, prefix=Config.ROOT_URL) api.add_resource(Applications, '/applications') api.add_resource(Application, '/applications/<application_id>') api.add_resource(Applicants, '/applicants') api.add_resource(Applicant, '/applicants/<applicant_id>') api.add_resource(Tokens, '/tokens') api.add_resource(Users, '/users') api.add_resource(ApplicationSearch, '/search/applications') api.add_resource(Tags, '/tags') api.add_resource(Countries, '/countries') api.add_resource(Recommendations, '/recommendations') api.add_resource(Researches, '/researches') api.add_resource(Projects, '/projects') api.init_app(app) # add commands to cli. app.cli.add_command(init_db_command) return app
def create_app(): app = Flask(__name__) CORS(app) api = Api(app, prefix='/api/v1') api.add_resource(Search, '/search/<string:resource>') api.init_app(app) app.config['ERROR_404_HELP'] = False return app
def build_api(app): api = Api() api.add_resource(GETTest, '/api/test') api.add_resource(POSTSignup, '/api/signup') api.add_resource(POSTLogin, '/api/login') api.add_resource(POSTArticle, '/api/article') api.add_resource(GETArticle, '/api/article') api.init_app(app) return api
def api_urls(app): urls = Blueprint('api', __name__) api = Api() api.init_app(urls) # URLs # Tokens # api.add_resource(FooResource, '/foo') return urls
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) cache.init_app(app) db.init_app(app) api = Api() Api_1_0(api) api.init_app(app) CORS(app, supports_credentials=True) # print(app.url_map) return app
def initialize_web_server(reactor, simulator, port, database): """Initialize the web server :param reactor: the twisted reactor to use :param simulator: the Simulator ubject that will be used :param port: the port that the server will listen to :param database: the database to use """ logger.debug("The web server will listen at port %d", port) app = Flask(__name__) api = Api() _add_fdm_resources(api, simulator.fdm, simulator.aircraft) _add_instrument_resources(api, simulator.aircraft.instruments) _add_sensor_resources(api, simulator.aircraft.sensors) api.add_resource(AircraftResource, "/aircraft", resource_class_args=(simulator.aircraft, )) api.add_resource(EngineResource, "/aircraft/engine", resource_class_args=(simulator.aircraft.engine, )) api.add_resource(FlightControlsResource, "/aircraft/controls", resource_class_args=(simulator.aircraft.controls, )) api.add_resource(SimulatorControlResource, "/simulator", resource_class_args=(simulator, )) api.add_resource(WaypointResource, "/map/waypoint/<name>", resource_class_args=(database, )) api.add_resource(WaypointsResource, "/map/waypoints", resource_class_args=(database, )) api.init_app(app) @app.route("/") def index(): return render_template("index.html") resource = WSGIResource(reactor, reactor.getThreadPool(), app) site = server.Site(resource) reactor.listenTCP(port, site)
def create_app(): app = Flask(__name__) CORS(app) api = Api(app, prefix='/api/v1') api.add_resource(Emails, '/notifications/emails') api.add_resource(SMS, '/notifications/sms') api.init_app(app) app.config['ERROR_404_HELP'] = False return app
def create_app(self): app = FlaskAPI(__name__, instance_relative_config=True) app.config.from_object(app_config['staging']) app.config.from_pyfile('config.py') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy() db.init_app(app) api = Api() api.init_app(app) app.register_blueprint(autho) app.register_blueprint(category) app.register_blueprint(recipe) return app
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) ma.init_app(app) api = Api(app, prefix='/api') from links_transform.resources.links import LinksResource from links_transform.resources.links_stat import LinksStat api.add_resource(LinksResource, '/long_to_short', '/<short_postfix>') api.add_resource(LinksStat, '/statistic/<short_postfix>') api.init_app(app) migrate.init_app(app, db) return app
def create_app(): app = Flask(__name__) api = Api() register_routes(api) api.init_app(app) app.config["MAIN_TABLE_NAME"] = "Tickets" dynamodb = boto3.client("dynamodb") with app.app_context(): create_main_table(dynamodb) return app
def create_app(config_class=Config): app = Flask(__name__) api = Api() app.config.from_object(Config) # Initializing API routes from flaskapp.api.routes import initialise_api_routes initialise_api_routes(api) api.init_app(app) from flaskapp.api.routes import api_bp app.register_blueprint(api_bp) return app
def build_urls(app): api = Api() api.add_resource(HealthCheck, f'{BASE_PATH}/health-check') return api.init_app(app)
def create_app(config): before_hook_path = os.getenv( 'FEDLEARNER_WEBCONSOLE_BEFORE_APP_START') if before_hook_path: module_path, func_name = before_hook_path.split(':') module = importlib.import_module(module_path) # Dynamically run the function getattr(module, func_name)() app = Flask('fedlearner_webconsole') app.config.from_object(config) db.init_app(app) migrate.init_app(app, db) jwt.init_app(app) # Error handlers app.register_error_handler(400, _handle_bad_request) app.register_error_handler(404, _handle_not_found) app.register_error_handler(WebConsoleApiException, make_response) app.register_error_handler(Exception, _handle_uncaught_exception) api = Api(prefix='/api/v2') initialize_auth_apis(api) initialize_project_apis(api) initialize_workflow_template_apis(api) initialize_workflow_apis(api) initialize_job_apis(api) initialize_dataset_apis(api) initialize_setting_apis(api) # A hack that use our customized error handlers # Ref: https://github.com/flask-restful/flask-restful/issues/280 handle_exception = app.handle_exception handle_user_exception = app.handle_user_exception api.init_app(app) app.handle_exception = handle_exception app.handle_user_exception = handle_user_exception if app.config.get('START_GRPC_SERVER', True): rpc_server.stop() rpc_server.start(app) if app.config.get('START_SCHEDULER', True): scheduler.stop() scheduler.start(app) return app
def init_api(app): #app = Flask(__name__) api = Api() api.add_resource(TemplateAPI, '/') api.add_resource(AccountListAPI, '/accounts/', endpoint='accounts') api.add_resource(AccountAPI, '/accounts/<int:id>', endpoint='account') api.add_resource(AccountServicesAPI, '/accounts/<int:id>/services', endpoint='accountservices') api.add_resource(MeterListAPI, '/meters/', endpoint='meters') api.add_resource(MeterAPI, '/meters/<int:id>', endpoint='meter') api.add_resource(MeterDataAPI, '/meters/<int:id>/data', endpoint='meterdata') api.add_resource(PlaceListAPI, '/places/', endpoint='places') api.add_resource(PlaceAPI, '/places/<int:id>', endpoint='place') api.add_resource(UserListAPI, '/users/', endpoint='users') api.add_resource(UserAPI, '/users/<int:id>', endpoint='user') api.add_resource(LoginAPI, '/auth/login', endpoint='login') api.add_resource(RegisterAPI, '/auth/register', endpoint='register') api.init_app(app) return app
from flask import Blueprint, request, url_for from flask_restful import Api, Resource, abort from flask_restful import reqparse, fields, marshal_with from flask_jwt import jwt_required from microblog.common.types import email from microblog.common.decorators import create_options from microblog.v1.models.user import User from microblog import db user_bp = Blueprint('user_bp', __name__) user_api = Api() API_VERSION = '1.0' user_api.init_app(user_bp) # By default parse returns the first error caught. # Setting bundle_errors property to true to get all the errors. user_parser = reqparse.RequestParser(bundle_errors=True) user_parser.add_argument('first_name', type=str, required=True, help="User's First Name") user_parser.add_argument('last_name', type=str, required=True, help="User's Last Name") user_parser.add_argument('username', type=str, required=True, help="Choose a username. It needs to be unique.") user_parser.add_argument('password', type=str, required=True, help="Choose a password") user_parser.add_argument('email', type=email, required=True, help="User's email") # This will be used to marshal output for users user_fields = { 'uuid': fields.String, 'first_name': fields.String, 'last_name': fields.String,
from flask import Blueprint from flask_restful import Api from app.static_string import * api = Api() blueprint = Blueprint(USER_API_NAME, __name__) api.init_app(blueprint) from .view import *
time.sleep(0.3) # 随机选取数据 sa = [] for i in range(lenght): sa.append(random.choice(data)) salt = ''.join(sa) return salt # 初始化 app = Flask(__name__) api=Api.init_app(__name__) # api = Api(app) # 初始化源数据# 随机生成 USERS = {"user1": { "username": random_str(10), "password": random_str(16), "token": random_str(32) }, "user2": { "username": random_str(10), "password": random_str(16), "token": random_str(32) }, "user3": { "username": random_str(10),
class Hello(Resource): def get(self): return {'Welcome to the pi-rest project.': 'Enjoy yourself!'} # # Error handlers # @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) @app.errorhandler(400) def bad_request(error): return make_response(jsonify({'error': 'Bad Request'}), 400) # # API endpoints # api.add_resource(Hello, '/') api.add_resource(Pin, '/pins/<int:pin_id>') api.add_resource(Pins, '/pins') api.add_resource(PinsSave, '/pins/save') api.add_resource(PinsLoad, '/pins/load') app.before_first_request(setup_app) api.init_app(app) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
# -*- coding: utf-8 -*- from slugify import slugify from flask import Blueprint, request, url_for from flask_restful import Api, Resource, abort from flask_restful import reqparse, fields, marshal_with from flask_jwt import jwt_required, current_user from microblog.v1.models.post import Post from microblog.v1.models.user import User from microblog.common.decorators import is_owner, create_options from microblog import db post_bp = Blueprint('post_bp', __name__) post_api = Api() API_VERSION = '1.0' post_api.init_app(post_bp) post_parser = reqparse.RequestParser(bundle_errors=True) post_parser.add_argument('title', type=str, required=True, help="Title for the post") post_parser.add_argument('subtitle', type=str, required=False, help="Breif description of post") post_parser.add_argument('body', type=str, required=True, help="Body of the post") post_fields = { "title": fields.String, "body": fields.String, "slug": fields.String, "username": fields.String, "user_link": fields.Url("user_bp.user_detail", absolute=True), "location": fields.Url('post_bp.post_detail', absolute=True),
from flask_cors import CORS from flask_restful import Api from flask import Blueprint, abort, jsonify from version_1.resources.dog import DogList, DogUpdate from version_1.resources.role import RoleList, RoleUpdate from version_1.resources.user import UserList, UserUpdate # Declare the blueprint v1 = Blueprint('v1', __name__) # Set up cross-scripting allowed CORS(v1) # Set up the API and init the blueprint api = Api() api.init_app(v1) # Set the default route @v1.route('/') def show(): return 'Hello World' ############################################# ########## Resources to Add ############################################# # Dogs api.add_resource(DogList, '/dogs') api.add_resource(DogUpdate, '/dogs/<int:id>') # Users