def create_app(test_config=None): """Instantiate the voluba-linear-backend Flask application.""" # logging configuration inspired by # http://flask.pocoo.org/docs/1.0/logging/#basic-configuration if test_config is None or not test_config.get('TESTING'): logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, # preserve Gunicorn loggers 'formatters': { 'default': { 'format': '[%(asctime)s] [%(process)d] %(levelname)s ' 'in %(module)s: %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S %z', } }, 'handlers': { 'wsgi': { 'class': 'logging.StreamHandler', 'stream': 'ext://flask.logging.wsgi_errors_stream', 'formatter': 'default' } }, 'root': { 'level': 'DEBUG', 'handlers': ['wsgi'] } }) # If we are running under Gunicorn, set up the root logger to use the same # handler as the Gunicorn error stream. if logging.getLogger('gunicorn.error').handlers: root_logger = logging.getLogger() root_logger.handlers = logging.getLogger('gunicorn.error').handlers root_logger.setLevel(logging.getLogger('gunicorn.error').level) # Hide Kubernetes health probes from the logs access_logger = logging.getLogger('gunicorn.access') exclude_useragent_re = re.compile(r'kube-probe') access_logger.addFilter( lambda record: not (record.args['h'].startswith('10.') and record.args[ 'm'] == 'GET' and record.args['U'] == '/health' and exclude_useragent_re.search(record.args['a']))) app = flask.Flask(__name__, instance_path=os.environ.get("INSTANCE_PATH"), instance_relative_config=True) app.config.from_object(DefaultConfig) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile("config.py", silent=True) app.config.from_envvar("VOLUBA_LINEAR_BACKEND_SETTINGS", silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure that the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass @app.route("/") def root(): return flask.redirect('/redoc') @app.route("/source") def source(): return flask.redirect(SOURCE_URL) # Return success if the app is ready to serve requests. Used in OpenShift # health checks. @app.route("/health") def health(): return '', 200 if app.config.get('ENABLE_ECHO'): @app.route('/echo') def echo(): app.logger.info('ECHO:\n' 'Headers\n' '=======\n' '%s', flask.request.headers) return '' if app.config.get('CORS_ORIGINS'): import flask_cors flask_cors.CORS(app, origins=app.config['CORS_ORIGINS'], max_age=app.config['CORS_MAX_AGE']) if app.config['ENV'] == 'development': local_server = [ { 'url': '/', }, ] else: local_server = [] smorest_api = flask_smorest.Api( app, spec_kwargs={ 'servers': local_server + [ { 'url': 'https://voluba-linear-backend.apps.hbp.eu/', 'description': 'Production instance running the *master* ' 'branch', }, { 'url': 'https://voluba-linear-backend.apps-dev.hbp.eu/', 'description': 'Development instance running the *dev* ' 'branch', }, ], 'info': { 'title': 'voluba-linear-backend', 'description': '''\ An HTTP backend for estimating linear spatial transformations from a list of point landmarks. This backend is used by [Voluba](https://voluba.apps.hbp.eu/), a web-based tool for interactive registration of 3-dimensional images, dedicated to the alignment of sub-volumes into brain templates. For more information, see the **source code repository:** <{SOURCE_URL}>. '''.format(SOURCE_URL=SOURCE_URL), 'license': { 'name': 'Apache 2.0', 'url': 'https://www.apache.org/licenses/LICENSE-2.0.html', }, }, }) from . import api smorest_api.register_blueprint(api.bp) if app.config.get('PROXY_FIX'): from werkzeug.middleware.proxy_fix import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app, **app.config['PROXY_FIX']) return app
#!/usr/bin/env python3 from flask import Flask, render_template, request, redirect, url_for, Response import redis, json import flask_cors # config system app = Flask(__name__) app.config.update(dict(SECRET_KEY='yoursecretkey')) r = redis.StrictRedis(host='localhost', port=6379, db=0, password='******') cors = flask_cors.CORS(app, resource={r"/": {"origin": "*"}}) @app.route('/RealData', methods=['GET']) def real(): # get real time data redis_data = r.execute_command('JSON.GET', 'dht11.real') result = json.loads(redis_data.decode()) response = {'error_code': 0, 'result': result} return response @app.route('/GraphData', methods=['GET']) def graph(): # get full graph data redis_data = r.execute_command('JSON.GET', 'dht11.graph') result = json.loads(redis_data) response = {'error_code': 0, 'result': result} return response if __name__ == '__main__':
import flask import flask_praetorian import flask_cors import mongoengine from mongoengine import Document, fields, DoesNotExist, signals from bson.json_util import loads, dumps db = mongoengine db.connect("praetorian", host="localhost", port=27017) guard = flask_praetorian.Praetorian() cors = flask_cors.CORS() class RoleException(Exception): pass allowed_roles = ["admin", "operator"] class User(Document): """ This is a small sample of a User class that persists to MongoDB. The following docker-compose.yml snippet can be used for testing. Please do not use in production. version: "3.2" services: mongo:
or flask.request.remote_addr == '127.0.0.1'): return flask.make_response('', 405) logger.info('Requesting shutdown...') func = flask.request.environ.get('werkzeug.server.shutdown') if func is None: return flask.make_response('Not running with the Werkzeug Server', 500) func() return flask.make_response('Server shutting down...', 200) if __name__ == '__main__': # Start of the web interface (with clean shutdown on error) # noinspection PyUnresolvedReferences logger.info('Starting on port: ' + str(config.get_http_port())) # Cross Origin Resource Sharing flask_cors.CORS(webapp) # noinspection PyUnresolvedReferences try: webapp_stopped = False webapp.run(host='0.0.0.0', port=int(config.get_http_port()), debug=False, threaded=True) except TypeError as e: print('Error: %s' % e, file=sys.stderr) finally: webapp_stopped = True shutdown() print('Application stopped') sys.exit(0)
import os, sys from flask import Flask, request from flask_restful import Resource, Api import flask_cors as cors from uuid import uuid4 as uuid from time import time from scope import bus, log, executor, query, ProgrammingError, InterfaceError, OperationalError, IntegrityError # Flask + JWT app = Flask(__name__) api = Api(app) cors.CORS(app, origins="*", allow_headers=[ "X-Real-Ip", "Content-Type", "Authorization", "Access-Control-Allow-Credentials", "X-Custom-Header", "Cache-Control", "x-Requested-With" ], supports_credentials=True) class Photo(Resource): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.is_tester = False def get(self): try: res = executor.execute_query(query, "select_faces_with_argument", is_tester=self.is_tester,
# -------------------------------------------------- # upload_path = "I:\\Project\\Project\\ValueX\\public\\upload" # 必须绝对路径? public_folder = "../../../public" template_folder = public_folder static_folder = public_folder + "/static" report_folder = public_folder + "/report" app = flask.Flask(__name__, static_folder=static_folder, template_folder=template_folder) app.config.from_object(config.config["config_d"]) app.config["upload_path"] = upload_path flask_cors.CORS(app, supports_credentials=True) api = flask_restful.Api(app) socketio = flask_socketio.SocketIO(app) # -------------------------------------------------- # @app.route("/") def index(): return flask.render_template("/index.html") @app.route("/upload_file", methods=["GET", "POST"]) def upload_file(): response = {"status": 0, "message": "upload & save failed!"}
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) flask_cors.CORS(self) self.wiring = Wiring(env)
from flask import Blueprint import flask_cors import logging import traceback from flask_graphql import GraphQLView from wandb.board.app.graphql.schema import schema from wandb.board.app.util.errors import format_error logger = logging.getLogger(__name__) graphql = Blueprint('graphql', __name__) flask_cors.CORS(graphql) GraphQLView.format_error = format_error graphql.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True))
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) flask_cors.CORS(self) self.wiring = Wiring(env) self.route('/api/v1/card/<card_id_or_slug>')(self.card)
from __future__ import absolute_import, division, print_function, unicode_literals import logging from functools import partial from flask import Flask, request, url_for, redirect, abort, jsonify import flask_cors from max_api import config, cache, utils # Init Flask application = app = Flask(__name__) flask_cors.CORS(app) # Allow cross-origin requests on all routes log = logging.getLogger(app.logger_name) #cache.enabled = False @app.route('/artists/', methods=['GET']) def find_artists(): """ Find artists by name. :return: search results. """ term = request.args.get('term') if not term: return 'Search term required', 400, {'Content-Type': 'text/plain'} spotify = config.get_spotify_client()
import os import flask_cors import jwt from flask import Blueprint, jsonify, request, make_response from werkzeug.security import generate_password_hash, check_password_hash import uuid from app import db from app.helper import token_required from app.models import User, PetOwner, Clinic from app.routes.pet.helper import find_opening_hours from app.routes.user.helper import find_animal_type user_bp = Blueprint('user_api', __name__, url_prefix='/user') flask_cors.CORS(user_bp) # Create account @user_bp.route('', methods=['POST']) def create_user(): data = request.get_json() hashed_password = generate_password_hash(data['password'], method='sha256') user_uid = str(uuid.uuid4()) # check if user already exists email_exists = User.query.filter_by(email=data['email']).first() username_exists = User.query.filter_by(username=data['username']).first() if email_exists or username_exists: return jsonify({'message': 'Account exists.'})
"View API endpoints." import http.client import flask import flask_cors import jsonschema import dbshare.db from dbshare import constants from dbshare import utils blueprint = flask.Blueprint("api_view", __name__) flask_cors.CORS(blueprint, methods=["GET"]) @blueprint.route("/<name:dbname>/<name:viewname>", methods=["GET", "PUT", "DELETE"]) def view(dbname, viewname): """GET: Return the schema for the view. PUT: Create the view. DELETE: Delete the view. """ if utils.http_GET(): try: db = dbshare.db.get_check_read(dbname, nrows=[viewname]) except ValueError: flask.abort(http.client.UNAUTHORIZED) except KeyError: flask.abort(http.client.NOT_FOUND)
"""Flask application.""" import connexion import flask_cors from library import config app = connexion.FlaskApp( __name__, specification_dir="openapi/", ) app.add_api("package.yaml", validate_responses=True) flask_cors.CORS( app.app, resources="*", origins=config.get().access_control_allow_origin, allow_headers=config.get().access_control_allow_headers, )
def create_app(test_config=None): app = flask.Flask(__name__, instance_relative_config=True) flask_cors.CORS(app) L = app.logger L.info("create_app") if test_config is None: app.config.from_pyfile("config.py", silent=True) else: app.config.from_mapping(test_config) try: os.makedirs(app.instance_path) except OSError: pass #initialize_instance(app.instance_path) #flask_monitoringdashboard.config.init_from( # file=os.path.join(app.instance_path, "dashboard/dashboard.cfg") #) #flask_monitoringdashboard.bind(app) node_root_paths = app.config.get( "NODE_ROOTS", [ "nodes", ], ) """ Setup individual MNs using a blueprint for each. Configuration ends up as: app.config['m_nodes'][node_name]['config'] """ app.config["m_nodes"] = {} app.url_map.strict_slashes = True for node_root in node_root_paths: node_path = pathlib.Path(os.path.join(app.instance_path, node_root)) node_path.mkdir(parents=True, exist_ok=True) for path in node_path.iterdir(): if path.is_dir(): mn_name = path.name L.debug("MN_NAME = %s", mn_name) abs_path = path.absolute() mn_config = { "config": os.path.abspath(os.path.join(abs_path, "node.json")), "node_id": None, "persistence": None, } options = {"mnode_name": mn_name, "config_path": mn_config["config"]} url_prefix = f"/{mn_name}/v2" L.debug("URL PREFIX = %s", url_prefix) app.register_blueprint( mnode.m_node, url_prefix=url_prefix, **options ) node_info = mnode.getNode(mn_config["config"]) if node_info is not None: mn_config["node_id"] = node_info["node"]["node_id"] mn_config["persistence"] = mnode.getPersistence(abs_path, node_info) # The persistence layer is returned open and initialized # Close it since it will be used on a different thread # when services requests mn_config["persistence"].close() # db_engine, db_session = mnode.setupDB(mn_config["config"]) # mn_config["db_engine"] = db_engine # mn_config["db_session"] = db_session app.config["m_nodes"][mn_name] = mn_config @app.teardown_appcontext def shutdownSession(exception=None): # L = app.logger # L.debug("teardown appcontext") #jnius.detach() pass @app.before_request def beforeRequest(): # L = app.logger # L.debug("beforeRequest") pass @app.teardown_request def afterRequest(exception=None): # L = app.logger # L.debug("afterRequest") pass @app.template_filter() def datetimeToJsonStr(dt): return opersist.utils.datetimeToJsonStr(dt) @app.template_filter() def asjson(jobj): if jobj is not None: return json.dumps(jobj, indent=2) return "" @app.route("/") def inventory(): nodes = [] for mn_name, mn_config in app.config["m_nodes"].items(): node_info = mnode.getNode(mn_config["config"]) entry = { "name": mn_name, "node_id": mn_config["node_id"], "config": mn_config["config"], "sitemap": node_info["spider"]["sitemap_urls"][0], "oldest": "", "newest": "", "count": 0 } op = None try: op = mn_config["persistence"] op.open() stats = op.basicStatsThings() #entry["numrecords"] = op.countThings() entry.update(stats) except Exception as e: app.logger.error(e) finally: op.close() nodes.append(entry) return flask.render_template("index.html", nodes=nodes) def has_no_empty_params(rule): defaults = rule.defaults if rule.defaults is not None else () arguments = rule.arguments if rule.arguments is not None else () return len(defaults) >= len(arguments) @app.route("/site-map") def site_map(): links = [] for rule in app.url_map.iter_rules(): # Filter out rules we can't navigate to in a browser # and rules that require parameters if "GET" in rule.methods and has_no_empty_params(rule): url = flask.url_for(rule.endpoint, **(rule.defaults or {})) links.append((url, rule.endpoint)) return "<pre>" + json.dumps(links, indent=2) + "</pre>" @app.route("/sha256/<sha_256>") def getItemBySha256(sha_256): #def getPersistence(abs_path, node_config): sha_256 = sha_256.replace("sha256:", "") for mn_name, mn_config in app.config["m_nodes"].items(): op = None app.logger.info("Item %s from %s", sha_256, mn_name) try: op = mn_config["persistence"] op.open() obj = op.getThingSha256(sha_256) if obj is not None: response = flask.make_response(obj.content) response.mimetype = obj.media_type_name obj_path = op.contentAbsPath(obj.content) fldr = os.path.dirname(obj_path) fname = os.path.basename(obj_path) return flask.send_from_directory( fldr, fname, mimetype=obj.media_type_name, as_attachment=False, attachment_filename=obj.file_name, last_modified=obj.t_content_modified, ) except Exception as e: app.logger.error(e) finally: if op is not None: op.close() flask.abort(404) return app
def __init__(self, config: ConfigClass, db: SQLAlchemy, schema: str = None, import_name=__name__.split('.')[0], static_url_path=None, static_folder='static', static_host=None, host_matching=False, subdomain_matching=False, template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None, use_init_db=True, Auth: Type[Auth] = Auth): """ :param config: :param db: :param schema: A string describing the main PostgreSQL's schema. ``None`` disables this functionality. If you use a factory of apps (for example by using :func:`teal.teal.prefixed_database_factory`) and then set this value differently per each app (as each app has a separate config) you effectively create a `multi-tenant app <https:// news.ycombinator.com/item?id=4268792>`_. Your models by default will be created in this ``SCHEMA``, unless you set something like:: class User(db.Model): __table_args__ = {'schema': 'users'} In which case this will be created in the ``users`` schema. Schemas are interesting over having multiple databases (i.e. using flask-sqlalchemy's data binding) because you can have relationships between them. Note that this only works with PostgreSQL. :param import_name: :param static_url_path: :param static_folder: :param static_host: :param host_matching: :param subdomain_matching: :param template_folder: :param instance_path: :param instance_relative_config: :param root_path: :param Auth: """ self.schema = schema ensure_utf8(self.__class__.__name__) super().__init__(import_name, static_url_path, static_folder, static_host, host_matching, subdomain_matching, template_folder, instance_path, instance_relative_config, root_path) self.config.from_object(config) flask_cors.CORS(self) # Load databases self.auth = Auth() self.url_map.converters[Converters.lower.name] = LowerStrConverter self.load_resources() self.register_error_handler(HTTPException, self._handle_standard_error) self.register_error_handler(ValidationError, self._handle_validation_error) self.db = db db.init_app(self) if use_init_db: self.cli.command('init-db', context_settings=self.cli_context_settings)( self.init_db) self.spec = None # type: APISpec self.apidocs()
def create_app(test_config=None): # create and configure the app app = fsk.Flask(__name__) models.setup_db(app) # Set up CORS. fc.CORS(app) # Use the after_request decorator to set Access-Control-Allow # Allow '*' for origins. # Allow methods GET, POST & DELETE @app.after_request def after_request(response): response.headers.add("Access-Control-Allow-Origin", "*") response.headers.add("Access-Control-Allow-Methods", "GET,POST,DELETE") return response # Create an endpoint to handle GET requests for all available categories. @app.route("/categories", methods=["GET"]) @fc.cross_origin() def get_categories(): cats = models.Category.query return fsk.jsonify({ "success": True, "categories": {c.id: c.type for c in cats}, }) # Create an endpoint to get questions based on category. # The category id should be non-negative. # A zero category id fetches all questions regardless of categories. @app.route("/categories/<int:cid>/questions", methods=["GET"]) @fc.cross_origin() def get_questions_by_category(cid): # Retrieve arguments try: page = max(int(fsk.request.args.get("page", 0)), 0) except BaseException: page = 0 # Get questions by category query = models.Question.query.order_by(models.Question.id) if cid != 0: cat = models.Category.query.get(cid) if cat is None: fsk.abort(404) query = query.filter(models.Question.category == cid) total_questions = query.count() # Paginate if applicable if page > 0: query = query.paginate(page=page, per_page=QUESTIONS_PER_PAGE).items qs = [q.format() for q in query] return fsk.jsonify({ "success": True, "questions": qs, "total_questions": total_questions, }) # Create a POST endpoint to get questions based on a search term. # Questions containing the `search` term (case-insensitive) are returned. # If `search` is not given, all questions are returned. # The `page` parameter can optionally be provided for paginated return. @app.route("/questions", methods=["GET"]) @fc.cross_origin() def search_questions(): # Retrieve arguments search_term = fsk.request.args.get("search") try: page = max(int(fsk.request.args.get("page", 0)), 0) except BaseException: page = 0 # Retrieve questions query = models.Question.query.order_by(models.Question.id) if search_term: query = query.filter( models.Question.question.ilike(f"%{search_term}%")) count = query.count() # Paginate if applicable if page > 0: query = query.paginate(page=page, per_page=QUESTIONS_PER_PAGE).items return fsk.jsonify({ "success": True, "questions": [q.format() for q in query], "total_questions": count, }) # Create an endpoint to POST a new question, which will require the # question and answer text, category ID, and difficulty score (+ve int). @app.route("/questions", methods=["POST"]) @fc.cross_origin() def create_question(): data = fsk.request.get_json() # Type-check types = { "question": str, "answer": str, "category": int, "difficulty": int, } data = valid_and_cast(data, types) # Sanity-check cid = data["category"] if models.Category.query.get(cid) is None or data["difficulty"] < 1: fsk.abort(422) # Create question qtn = models.Question(**data) db = models.db try: qtn.insert() q_data = qtn.format() logging.info(f"Created question: {q_data}") return fsk.jsonify({"success": True, "id": q_data["id"]}) except BaseException: db.session.rollback() logging.exception( f"Failed to add new question with content: {data}") fsk.abort(500) finally: db.session.close() # Create an endpoint to get question by ID. @app.route("/questions/<int:qid>", methods=["GET"]) @fc.cross_origin() def get_question(qid): q = models.Question.query.get(qid) if q is None: fsk.abort(404) return fsk.jsonify({"success": True, "question": q.format()}) # Create an endpoint to delete question by ID. @app.route("/questions/<int:qid>", methods=["DELETE"]) @fc.cross_origin() def delete_question(qid): # Check question existence question = models.Question.query.get(qid) if question is None: fsk.abort(404) # Delete question db = models.db q_data = question.format() try: question.delete() logging.info(f"Deleted question: {q_data}.") except BaseException: db.session.rollback() logging.exception(f"Failed to delete question: {q_data}") fsk.abort(500) finally: db.session.close() return fsk.jsonify({"success": True, "id": q_data["id"]}) # Create a POST endpoint to get questions to play the quiz. # This endpoint takes category and previous question parameters # and return a random questions within the given category, # if provided, and that is not one of the previous questions. @app.route("/quizzes", methods=["POST"]) @fc.cross_origin() def get_quiz_question(): data = fsk.request.get_json() # Type-check data = valid_and_cast(data, { "previous_questions": list, "quiz_category": int }) # Sanity-check pqids = data["previous_questions"] cid = data["quiz_category"] try: pqids = [int(qid) for qid in pqids] except BaseException: fsk.abort(422) # Get questions IDs with previous ones excluded query = (models.Question.query.with_entities( models.Question.id).filter(~models.Question.id.in_(pqids))) if cid != 0: query = query.filter(models.Question.category == cid) qids = [q.id for q in query] q = None if qids: # Choose question randomly qid = qids[random.randint(0, len(qids) - 1)] q = models.Question.query.get(qid).format() # Get chosen question return fsk.jsonify({"success": True, "question": q}) # Create error handler for status 400 @app.errorhandler(400) def bad_request_error(error): return error_json(400, "bad request"), 400 # Create error handler for status 404 @app.errorhandler(404) def not_found_error(error): return error_json(404, "resource not found"), 404 # Create error handler for status 422 @app.errorhandler(422) def unprocessable_error(error): return error_json(422, "unprocessable"), 422 # Create error handler for status 500 @app.errorhandler(500) def server_error(error): return error_json(500, "server error"), 500 return app
def create_app(test_config=None): """Instantiate the cortical-voluba Flask application.""" # logging configuration inspired by # http://flask.pocoo.org/docs/1.0/logging/#basic-configuration if test_config is None or not test_config.get('TESTING'): logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, # preserve Gunicorn loggers 'formatters': { 'default': { 'format': '[%(asctime)s] [%(process)d] %(levelname)s ' 'in %(module)s: %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S %z', } }, 'handlers': { 'wsgi': { 'class': 'logging.StreamHandler', 'stream': 'ext://flask.logging.wsgi_errors_stream', 'formatter': 'default' } }, 'root': { 'level': 'DEBUG', 'handlers': ['wsgi'] } }) # If we are running under Gunicorn, set up the root logger to use the same # handler as the Gunicorn error stream. if logging.getLogger('gunicorn.error').handlers: root_logger = logging.getLogger() root_logger.handlers = logging.getLogger('gunicorn.error').handlers root_logger.setLevel(logging.getLogger('gunicorn.error').level) # Hide Kubernetes health probes from the logs access_logger = logging.getLogger('gunicorn.access') exclude_useragent_re = re.compile(r'kube-probe') access_logger.addFilter( lambda record: not (record.args['h'].startswith('10.') and record.args[ 'm'] == 'GET' and record.args['U'] == '/health' and exclude_useragent_re.search(record.args['a']))) app = flask.Flask(__name__, instance_path=os.environ.get('INSTANCE_PATH'), instance_relative_config=True) app.config.from_object(DefaultConfig) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) app.config.from_envvar('CORTICAL_VOLUBA_SETTINGS', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure that the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass @app.route('/') def root(): return flask.redirect('/redoc') @app.route('/source') def source(): return flask.redirect(SOURCE_URL) # Return success if the app is ready to serve requests. Used in OpenShift # health checks. @app.route("/health") def health(): return '', 200 if app.config.get('ENABLE_ECHO'): @app.route('/echo') def echo(): app.logger.info('ECHO:\n' 'Headers\n' '=======\n' '%s', flask.request.headers) return '' if app.config.get('CORS_ORIGINS'): import flask_cors flask_cors.CORS(app, origins=app.config['CORS_ORIGINS'], max_age=app.config['CORS_MAX_AGE'], allow_headers=['Authorization', 'Content-Type']) # Celery must be initialized before the tasks module is imported, i.e. # before the API modules. with app.app_context(): # We must instantiate a new Celery app each time a Flask app is # instantiated, because the Celery app and tasks are tied to the Flask # app (they read from flask_app.config). from . import celery celery.celery_app = celery.create_celery_app(app) # Every time a new Celery app is instantiated, the tasks need to be # re-created because they must use the correct app at import time. from . import tasks importlib.reload(tasks) if app.config['ENV'] == 'development': local_server = [ { 'url': '/', }, ] else: local_server = [] smorest_api = flask_smorest.Api( app, spec_kwargs={ 'servers': local_server + [ { 'url': 'https://cortical-voluba.apps-dev.hbp.eu/', 'description': 'Development instance running the *dev* ' 'branch', }, ], 'info': { 'title': 'cortical-voluba', 'description': '''\ Voluba backend for non-linear depth-informed alignment of cortical patches. For more information, see the **source code repository:** <{SOURCE_URL}>. '''.format(SOURCE_URL=SOURCE_URL), # 'license': { # 'name': 'Apache 2.0', # 'url': 'https://www.apache.org/licenses/LICENSE-2.0.html', # }, }, 'components': { 'securitySchemes': { 'chumni_auth': { 'type': 'http', 'scheme': 'bearer', 'bearerFormat': 'JWT', 'description': 'A bearer token that is used to access the ' 'image service on behalf of the user. As ' 'of January 2020, OIDC tokens generated by ' 'orcid.org are accepted.', }, }, }, }) from . import api_v0 smorest_api.register_blueprint(api_v0.bp) if app.config.get('PROXY_FIX'): from werkzeug.middleware.proxy_fix import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app, **app.config['PROXY_FIX']) return app
import mwapi app = Flask(__name__) __dir__ = os.path.dirname(__file__) app.config.update( yaml.safe_load(open(os.path.join(__dir__, 'default_config.yaml')))) try: app.config.update( yaml.safe_load(open(os.path.join(__dir__, 'config.yaml')))) except IOError: # It is ok if there is no local config file pass # Enable CORS for API endpoints cors = flask_cors.CORS(app, resources={r'/api/*': {'origins': '*'}}) SESSION = mwapi.Session('https://www.wikidata.org', user_agent=app.config['CUSTOM_UA']) FT_MODEL = fasttext.load_model('models/model.bin') @app.route('/') def index(): return render_template('index.html') def adjust_topics_based_on_claims(topics, claims): joined_claims = [":".join(c) for c in claims] properties = [c[0] for c in claims] # list / disambiguation pages
import flask import flask_cors from src import ( blueprints, ) app: flask.Flask = flask.Flask('__main__') cors: flask_cors.CORS = flask_cors.CORS(app) app.register_blueprint(blueprints.appointments_blueprint) app.register_blueprint(blueprints.professionals_blueprint) app.register_blueprint(blueprints.specialties_blueprint)
def init_app(app): flask_cors.CORS(app, resources={r"/*": {"origins": "*"}})
sa.create_engine(follower.strip()) for follower in utils.split_env_var( env.get_credential('SQLA_FOLLOWERS', '')) if follower.strip() ] app.config['SQLALCHEMY_ROUTE_SCHEDULE_A'] = bool( env.get_credential('SQLA_ROUTE_SCHEDULE_A', '')) app.config['PROPAGATE_EXCEPTIONS'] = True # app.config['SQLALCHEMY_ECHO'] = True # Modify app configuration and logging level for production if not app.debug: app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) db.init_app(app) cors.CORS(app) class FlaskRestParser(FlaskParser): def handle_error(self, error, req, schema, status_code, error_headers): message = error.messages status_code = getattr(error, 'status_code', 422) raise exceptions.ApiError(message, status_code) parser = FlaskRestParser() app.config['APISPEC_WEBARGS_PARSER'] = parser app.config['MAX_CACHE_AGE'] = env.get_credential('FEC_CACHE_AGE') v1 = Blueprint('v1', __name__, url_prefix='/v1') api = restful.Api(v1)
def create_app(): """ init app :return: flask app """ app = flask.Flask(__name__, static_folder=config.STATIC_PATH) log.init_log(app, config.LOG_PATH, config.LOG_LEVEL) flask_cors.CORS(app) flask_compress.Compress(app) class RegexConverter(werkzeug.routing.BaseConverter): """ regular expression converts for route """ def __init__(self, url_map, *items): """ support for regular expression route :param url_map: alias for conflict with builtin 'map' :param items: regular expression """ super(RegexConverter, self).__init__(url_map) self.regex = items[0] app.url_map.converters['regex'] = RegexConverter app.config['SECRET_KEY'] = ''.join( random.sample(string.ascii_letters + string.digits, 8)) app.config['SQLALCHEMY_DATABASE_URI'] = config.DB_URL app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) with app.test_request_context(): db.create_all() app.config['OAUTH'] = {} if os.path.isdir(config.OAUTH_DIR): for root, _, files in os.walk(config.OAUTH_DIR): for auth_file in filter(lambda x: x.endswith('_oauth.json'), files): try: with open(os.path.join(root, auth_file)) as fp: prefix = auth_file[:auth_file.find('_')] oauth_config = json.load(fp) if oauth_config is not None: app.config['OAUTH'][prefix] = oauth_config except Exception as e: app.logger.error(e.message) api.init_oauth(app) app.register_blueprint(api.bp, url_prefix='/v1') @app.route('/<regex("$"):url>') def web_index(url=None): """ redirect to index :return: """ return flask.redirect('/web/index.html') @app.route('/web/swagger-ui<regex("$"):url>') def swagger_index(url=None): """ redirect to index :return: """ return flask.redirect('/web/swagger-ui/index.html') return app
import flask import flask_cors app = flask.Flask(__name__) # pylint: disable=invalid-name # cross-site read, same origin policy cors = flask_cors.CORS(app, resources={r"/views/*": {"origins": "*"}}) # Read settings from config module (insta485/config.py) # Overlay settings read from file specified by environment variable. This is # useful for using different on development and production machines. # Reference: http://flask.pocoo.org/docs/0.12/config/ app.config.from_envvar('INSTA485_SETTINGS', silent=True) # Tell our app about views and model. This is dangerously close to a # circular import, which is naughty, but Flask was designed that way. # (Reference http://flask.pocoo.org/docs/0.12/patterns/packages/) We're # going to tell pylint and pycodestyle to ignore this coding style violation. import insta485.views # noqa: E402 pylint: disable=wrong-import-position if __name__ == '__main__': insta485.app.run(debug=True, host='0.0.0.0', port=8000)
file.save(destination) response = "File Uploaded Successfully" return response # Helper function to check if there are any empty cells in the csv file. def csv_cell_checker(file): with open(str(file), 'r') as csv_file: for row in csv.reader(csv_file): if '' in row: print('empty cell') return False return True # Helper function check the number of columns and rows in the uploaded csv file def csv_col_row_check(file): with open(str(file), 'r') as csv_file: columns = csv_file.readline() rows = sum(1 for line in csv_file) + 1 if columns == 3 and rows == 10: return True else: return False if __name__ == "__main__": app.run(debug=True, host="0.0.0.0", use_reloader=False) flask_cors.CORS(app, expose_headers='Authorization')
# -*- coding: utf-8 -*-# import json from route import __user__ as user from flask import Flask import flask_cors __app__ = Flask(__name__) __app__.register_blueprint(user) flask_cors.CORS(__app__) @__app__.route('/', methods=['GET']) def index(): """ Rota root da API """ data = { "name": "Douglas", "nickname": "DougTQ", "nationality": "Brazilian", "age": 21 } reply = __app__.response_class(response=json.dumps(data), status=202, mimetype='__app__lication/json') # reply = make_response(jsonify(dicc), 202) return reply if __name__ == '__main__': __app__.run(port=5000, debug=False, host='localhost', use_reloader=True)
headers = { "Authorization": f"Bearer {os.environ.get( 'REACT_APP_GITHUB_RESEARCHER_TOKEN' )}" } # https://stackoverflow.com/questions/15117416/capture-arbitrary-path-in-flask-route # https://stackoverflow.com/questions/44209978/serving-a-front-end-created-with-create-react-app-with-flask APP = flask.Flask( "github_repository_researcher", static_folder="reactfrontend/build/static", template_folder="reactfrontend/build", ) # https://stackoverflow.com/questions/25594893/how-to-enable-cors-in-flask-and-heroku # https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present flask_cors.CORS(APP) github_ratelimit_graphql = wrap_text(""" rateLimit { limit cost remaining resetAt } viewer { login } """) def main():
except (OSError, FileNotFoundError): CONFIG = {} if CONFIG.get("open_browser_tab_in_startup"): seconds_to_open_tab = float(CONFIG.get("seconds_to_open_browser_tab", 0.75)) flask_port = os.environ["FLASK_PORT"] threading.Timer( seconds_to_open_tab, lambda: webbrowser.open_new_tab(f"http://*****:*****@app.route("/generate-pdf", methods=["POST"]) def fn_generate_pdf(): if flask.request.method != "POST": return flask.make_response(dict(response="Invalid method.", status=404)) data = flask.request.get_json() diagram_mermaid_code = data["diagram"] output_uri = data.get("output_uri", "output.pdf").strip() if not output_uri.endswith(".pdf"): output_uri += ".pdf" temp_dir = pathlib.Path("./temp")
load_dotenv() # Set up the static folder to serve our angular client resources (*.js, *.css) app = flask.Flask(__name__, static_folder='dist/client', static_url_path='/client/') # If we're running in debug, defer to the typescript development server # This gets us things like live reload and better sourcemaps. if app.config['DEBUG']: app.config['API_URL'] = os.getenv( 'DEBUG_API_URL') or 'http://*****:*****@app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def serve_angular(path): """ A catch-all route to serve the angular app. If no other routes match (such as /example) this will be called, and the angular app will take over routing.
'templates'), instance_relative_config=True) # Implementing rostful default config as early as possible. app.config.from_object(config) # Config Workflow # 1. load hardcoded (in source) defaults, minimum expected to not break / crash. # 2. load config from default location (overriding hardcoded defaults). # if not there, create it (at runtime, with the hardcoded default values) # 3. load user provided config from envvar if any, otherwise silently ignore. # 4. load user provided config from command arg if any, if missing file then except (user provided arg is wrong). # if intent is to use file from default location, then no config arg should be provided, # and optional override is available via envvar. # Adding CORS middleware app.cors = cors.CORS(app, resources=r'/*', allow_headers='*') # Adding Reverse proxy middleware app.reverse_proxied = FlaskReverseProxied(app) # Temporary disabled until we can confirm if it s useful or not # # # REST API extended to render exceptions as json # # https://gist.github.com/grampajoe/6529609 # # http://www.wiredmonk.me/error-handling-and-logging-in-flask-restful.html # class Api(restful.Api): # def handle_error(self, e): # # Attach the exception to itself so Flask-Restful's error handler # # tries to render it. # if not hasattr(e, 'data'): # TODO : fix/improve this # e.data = e
#!/usr/bin/env python # -*- coding: utf-8 -*- import contextlib import flask import flask_cors import json import os import psycopg2.extras import psycopg2.pool import urlparse application = flask.Flask(__name__) application.debug = os.environ.get('FLASK_DEBUG') in ['true', 'True'] app_version = os.environ.get('APP_VERSION') flask_cors.CORS(application) @application.route('/points') def points(): bbox = flask.request.args.get("bbox").split(',') if bbox is None: return ('bbox required', 400) with get_db_cursor() as cursor: cursor.execute( "SELECT id as id, ST_X(geom) as latitude, ST_Y(geom) as longitude" + " FROM adcirc_save_points" + " WHERE geom && ST_MakeEnvelope(%s, %s, %s, %s, 4326)" % tuple(bbox)) data = cursor.fetchall() if len(data) > 0: