def create_blueprint(endpoints): """Create Invenio-Deposit-REST blueprint.""" blueprint = Blueprint( 'invenio_deposit_rest', __name__, url_prefix='', ) for endpoint, options in (endpoints or {}).items(): for rule in create_url_rules(endpoint, **options): blueprint.add_url_rule(**rule) deposit_actions = DepositActionResource.as_view( DepositActionResource.view_name.format(endpoint), serializers=options.get('record_serializers'), pid_type=options['pid_type'], ) blueprint.add_url_rule( '{0}/actions/<any(publish,edit,discard):action>'.format( options['item_route'] ), view_func=deposit_actions, methods=['POST'] ) return blueprint
def create_loan_replace_item_blueprint(app): """Create a blueprint for replacing Loan Item.""" blueprint = Blueprint( "invenio_circulation_loan_replace_item", __name__, url_prefix="" ) rec_serializers = { "application/json": ( "invenio_records_rest.serializers" ":json_v1_response" ) } serializers = { mime: obj_or_import_string(func) for mime, func in rec_serializers.items() } replace_item_view = LoanReplaceItemResource.as_view( LoanReplaceItemResource.view_name.format(CIRCULATION_LOAN_PID_TYPE), serializers=serializers, ctx={}, ) url = "circulation/loans/<{0}:pid_value>/replace-item".format( _LOANID_CONVERTER ) blueprint.add_url_rule(url, view_func=replace_item_view, methods=["POST"]) return blueprint
def create_api_blueprint(self, collection_name, api_name=None, api_prefix=API_PREFIX, methods_allowed=['GET', ], pk_type='str', pk='_id'): """ """ collection = self.get_collection(collection_name) view_name, endpoint, blueprint_name = self.format_names(collection, api_name, api_prefix) # format_names returns a tuple with the names used to register the views and blueprints. try: collection_view = APIView.as_view(view_name, collection) # Flask pluggable view except TypeError: # This exception occurs because flask views don't support unicode # And pymongo collections.name returns a unicode value collection_view = APIView.as_view(str(view_name), collection, pk) methods_allowed = self.format_methods(methods_allowed) self.validate_methods(MongoAPI.METHODS_SUPPORTED, methods_allowed) blueprint = Blueprint(str(blueprint_name), __name__, api_prefix) blueprint.add_url_rule(endpoint, view_func=collection_view, methods=self.root_methods(methods_allowed[:])) #/api/collection_name/ endpoint = create_url_placeholder(endpoint, pk_type, pk) blueprint.add_url_rule(endpoint, view_func=collection_view, methods=self.document_methods(methods_allowed[:])) #/api/collection_name/primary_key blueprint.mongo_rest_api = True return blueprint
def create_blueprint(endpoints): """Create Invenio-Deposit-UI blueprint.""" from invenio_records_ui.views import create_url_rule blueprint = Blueprint( 'invenio_deposit_ui', __name__, static_folder='../static', template_folder='../templates', url_prefix='', ) for endpoint, options in (endpoints or {}).items(): blueprint.add_url_rule(**create_url_rule(endpoint, **options)) @blueprint.route('/deposit') @login_required def index(): """List user deposits.""" return render_template( 'invenio_deposit/index.html', ) @blueprint.route('/deposit/new') @login_required def new(): """Create new deposit.""" return render_template( 'invenio_deposit/edit.html', record={'_deposit': {'id': None}}, ) return blueprint
def create_loan_actions_blueprint(app): """Create a blueprint for Loan actions.""" blueprint = Blueprint( "invenio_circulation_loan_actions", __name__, url_prefix="" ) endpoints = app.config.get("CIRCULATION_REST_ENDPOINTS", []) pid_type = CIRCULATION_LOAN_PID_TYPE options = endpoints.get(pid_type, {}) if options: options = deepcopy(options) serializers = {} if "record_serializers" in options: rec_serializers = options.get("record_serializers") serializers = { mime: obj_or_import_string(func) for mime, func in rec_serializers.items() } loan_actions = LoanActionResource.as_view( LoanActionResource.view_name.format(pid_type), serializers=serializers, ctx={}, ) distinct_actions = extract_transitions_from_app(app) url = "{0}/<any({1}):action>".format( options["item_route"], ",".join(distinct_actions) ) blueprint.add_url_rule(url, view_func=loan_actions, methods=["POST"]) return blueprint
def create(): """Create blueprint. """ # Create instance blueprint = Blueprint('authentication', 'authentication') # Controller Proxies check_controller = controllers.Check() callback_controller = controllers.Callback() def check(): token = request.values.get('jwt') next_url = request.args.get('next', None) callback_url = 'http://'+os_conductor+url_for('.callback') return jsonpify(check_controller(token, next_url, callback_url)) def callback(): state = request.args.get('state') return callback_controller(state) # Register routes blueprint.add_url_rule( 'check', 'check', check, methods=['GET']) blueprint.add_url_rule( 'google_callback', 'callback', callback, methods=['GET']) # Return blueprint return blueprint
class Feedloggr(object): def __init__(self, app=None, *args, **kwargs): if app: self.init_app(app, *args, **kwargs) def init_app(self, app, db): self.app = app # register extension with app self.app.extensions = getattr(app, 'extensions', {}) self.app.extensions['feedloggr'] = self self.blueprint = Blueprint( 'feedloggr', __name__, template_folder='templates', static_folder='static', url_prefix = app.config.get('FEEDLOGGR_URL', '/feedloggr'), ) self.blueprint.add_url_rule('/', view_func=index) self.blueprint.add_url_rule( '/<int:year>-<int:month>-<int:day>', view_func=index, ) db_proxy.initialize(db.database) create_tables(fail_silently=True) app.register_blueprint(self.blueprint)
def register_views(self, app): blueprint = Blueprint( self.config.get('endpoint', 'swagger'), __name__, url_prefix=self.config.get('url_prefix', None), subdomain=self.config.get('subdomain', None), template_folder=self.config.get('template_folder', 'templates'), static_folder=self.config.get('static_folder', 'static'), static_url_path=self.config.get('static_url_path', None) ) for spec in self.config['specs']: self.endpoints.append(spec['endpoint']) blueprint.add_url_rule( spec['route'], spec['endpoint'], view_func=OutputView().as_view( spec['endpoint'], view_args=dict( app=app, config=self.config, spec=spec, sanitizer=self.sanitizer ) ) ) blueprint.add_url_rule( self.config.get('specs_route', '/specs'), 'specs', view_func=SpecsView().as_view( 'specs', view_args=dict(config=self.config) ) ) app.register_blueprint(blueprint)
def as_blueprint(self, name=None): blueprint = Blueprint(name if name else str(uuid4()), __name__) blueprint.add_url_rule( '/', view_func=self.jsonrpc, methods=['POST']) blueprint.add_url_rule( '/map', view_func=self.jsonrpc_map, methods=['GET']) return blueprint
def create(): """Create blueprint. """ # Create instance blueprint = Blueprint('search', 'search') # Controller Proxies search_controller = controllers.search def search(kind): token = request.values.get('jwt') userid = None try: if token is not None: token = jwt.decode(token, PRIVATE_KEY) userid = token.get('userid') except jwt.InvalidTokenError: pass ret = search_controller(kind, userid, request.args) if ret is None: abort(400) return jsonpify(ret) # Register routes blueprint.add_url_rule( '<kind>', 'search', search, methods=['GET']) # Return blueprint return blueprint
class Casl(object): def __init__(self, prefix="/casl", name=None, app=None): self.name = name self.prefix = prefix self.app = app if not name: self.name = __name__ self.routes = [("/word/<word>", "r_word", ["GET"])] if self.app is not None: self.init_app(app) def init_app(self, app): """ Register the blueprint to the app :param app: Flask Application :return: Blueprint for Casl registered in app :rtype: Blueprint """ self.blueprint = Blueprint( self.name, self.name, url_prefix=self.prefix, ) for url, name, methods in self.routes: self.blueprint.add_url_rule( url, view_func=getattr(self, name), endpoint=name, methods=methods ) self.app.register_blueprint(self.blueprint) return self.blueprint def register_routes(self): """ Register routes on app using Blueprint :return: FlaskCasl blueprint :rtype: flask.Blueprint """ if self.app is not None: if not self.blueprint: self.blueprint = self.create_blueprint() self.app.register_blueprint(self.blueprint) return self.blueprint return None def r_word(self,word): response = self.parse(word) return response, 200, { "Content-Type": "application/xml"} def parse(self, word): return "<word>" + word + "</word>"
def create_blueprint(endpoints): """Factory for Invenio-Records-UI blueprint creation. The factory installs one URL route per endpoint defined, and adds an error handler for rendering tombstones. :param endpoints: Dictionary of endpoints to be installed. See usage documentation for further details. """ blueprint = Blueprint( 'invenio_records_ui', __name__, url_prefix='', template_folder='templates', static_folder='static', ) @blueprint.errorhandler(PIDDeletedError) def tombstone_errorhandler(error): return render_template( current_app.config['RECORDS_UI_TOMBSTONE_TEMPLATE'], pid=error.pid, record=error.record or {}, ), 410 for endpoint, options in (endpoints or {}).items(): blueprint.add_url_rule(**create_url_rule(endpoint, **options)) return blueprint
def create_blueprint(endpoints): """Create Invenio-Records-REST blueprint.""" blueprint = Blueprint( 'invenio_records_rest', __name__, url_prefix='', ) for endpoint, options in (endpoints or {}).items(): for rule in create_url_rules(endpoint, **options): blueprint.add_url_rule(**rule) # catch record validation errors @blueprint.errorhandler(ValidationError) def validation_error(error): """Catch validation errors.""" return RESTValidationError().get_response() @blueprint.errorhandler(RequestError) def elasticsearch_badrequest_error(error): """Catch errors of ElasticSearch.""" def first(function, iterable, default=None): """Return the first item from iterable which function is true.""" for item in iterable: if function(item): return item return default handlers = map(lambda c: elasticsearch_error_handlers.get(c['type']), error.info['error']['root_cause']) handler = first(lambda h: h, handlers, lambda h: h) return handler(error) return blueprint
def init_app(self, app): app.config.setdefault('BOWER_COMPONENTS_ROOT', 'bower_components') app.config.setdefault('BOWER_KEEP_DEPRECATED', True) app.config.setdefault('BOWER_QUERYSTRING_REVVING', True) app.config.setdefault('BOWER_REPLACE_URL_FOR', False) app.config.setdefault('BOWER_SUBDOMAIN', None) app.config.setdefault('BOWER_TRY_MINIFIED', True) app.config.setdefault('BOWER_URL_PREFIX', '/bower') blueprint = Blueprint( 'bower', __name__, url_prefix=app.config['BOWER_URL_PREFIX'], subdomain=app.config['BOWER_SUBDOMAIN']) blueprint.add_url_rule('/<component>/<path:filename>', 'serve', serve) app.register_blueprint(blueprint) if app.config['BOWER_KEEP_DEPRECATED'] is True: app.jinja_env.globals['bower_url_for'] = bower_url_for if app.config['BOWER_REPLACE_URL_FOR'] is True: app.jinja_env.globals['url_for'] = replaced_url_for app.url_build_error_handlers.append(handle_url_error)
def as_blueprint(cls, name=None): name = name or cls.endpoint bp = Blueprint(name, cls.__module__, url_prefix=cls.url_prefix) for endpoint, options in cls.url_rules.iteritems(): url_rule = options.get('rule', '') defaults = options.get('defaults', {}) bp.add_url_rule(url_rule, defaults=defaults, view_func=cls.as_view(endpoint)) return bp
def create_blueprint(blueprint_name, conf): webcams_blueprint = Blueprint(blueprint_name, __name__, **conf) webcams_blueprint.add_url_rule('/', view_func=Webcams.as_view('webcams')) webcams_blueprint.add_url_rule('/<slug>', view_func=StillImage.as_view('webcam')) return webcams_blueprint
def create_blueprint(blueprint_name, conf): contact_blueprint = Blueprint(blueprint_name, __name__, **conf) contact_blueprint.add_url_rule('/', view_func=get_routes) contact_blueprint.add_url_rule('/search', view_func=Search.as_view('search')) return contact_blueprint
def test_url_with_blueprint_invalid_object(self): app = Flask(__name__) bp = Blueprint("foo", __name__, url_prefix="/foo") bp.add_url_rule("/<hey>", "foobar", view_func=lambda x: x) app.register_blueprint(bp) field = fields.Url() with app.test_request_context("/foo/hey"): self.assertRaises(MarshallingException, lambda: field.output("hey", None))
def test_url_with_blueprint_absolute_scheme(self): app = Flask(__name__) bp = Blueprint("foo", __name__, url_prefix="/foo") bp.add_url_rule("/<hey>", "foobar", view_func=lambda x: x) app.register_blueprint(bp) field = fields.Url(absolute=True, scheme='https') with app.test_request_context("/foo/hey", base_url="http://localhost"): self.assertEquals("https://localhost/foo/3", field.output("hey", Foo()))
def test_url_with_blueprint(self): app = Flask(__name__) bp = Blueprint("foo", __name__, url_prefix="/foo") bp.add_url_rule("/<hey>", "foobar", view_func=lambda x: x) app.register_blueprint(bp) field = fields.Url() with app.test_request_context("/foo/hey"): self.assertEquals("/foo/3", field.output("hey", Foo()))
def test_with_blueprint(self, app, mocker): bp = Blueprint('foo', __name__, url_prefix='/foo') bp.add_url_rule('/<foo>', 'foobar', view_func=lambda x: x) app.register_blueprint(bp) field = fields.Url() obj = mocker.Mock(foo=42) with app.test_request_context('/foo/foo'): assert '/foo/42' == field.output('foo', obj)
def test_with_blueprint_invalid_object(self, app): bp = Blueprint('foo', __name__, url_prefix='/foo') bp.add_url_rule('/<foo>', 'foobar', view_func=lambda x: x) app.register_blueprint(bp) field = fields.Url() with app.test_request_context('/foo/foo'): with pytest.raises(fields.MarshallingError): field.output('foo', None)
def create_blueprint(self, url_prefix=''): blueprint = Blueprint(self.name, __name__) url = url_prefix + '/' + self.name blueprint.add_url_rule(url, view_func=self.dispatch_collection, methods=['GET', 'POST']) blueprint.add_url_rule(url + '/<object_id>', view_func=self.dispatch_object, methods=['GET', 'PUT', 'PATCH', 'DELETE']) return blueprint
def create_blueprint(blueprint_name, conf): transport_blueprint = Blueprint(blueprint_name, __name__, **conf) transport_blueprint.add_url_rule('/', view_func=get_routes) transport_blueprint.add_url_rule('/park-and-rides', view_func=ParkAndRides.as_view('p-r')) return transport_blueprint
def create_blueprint(endpoints): """Create Invenio-Records-REST blueprint.""" blueprint = Blueprint("invenio_records_rest", __name__, url_prefix="") for endpoint, options in (endpoints or {}).items(): for rule in create_url_rules(endpoint, **options): blueprint.add_url_rule(**rule) return blueprint
def test_with_blueprint_absolute(self): bp = Blueprint('foo', __name__, url_prefix='/foo') bp.add_url_rule('/<foo>', 'foobar', view_func=lambda x: x) self.app.register_blueprint(bp) field = fields.Url(absolute=True) obj = Mock(foo=42) with self.app.test_request_context('/foo/foo'): assert_equal('http://localhost/foo/42', field.output('foo', obj))
def test_with_blueprint_absolute_scheme(self, app, mocker): bp = Blueprint('foo', __name__, url_prefix='/foo') bp.add_url_rule('/<foo>', 'foobar', view_func=lambda x: x) app.register_blueprint(bp) field = fields.Url(absolute=True, scheme='https') obj = mocker.Mock(foo=42) with app.test_request_context('/foo/foo', base_url='http://localhost'): assert 'https://localhost/foo/42' == field.output('foo', obj)
def api_factory(name): """Construct a Blueprint and a REMOTE decorator to set up an API. RPC calls are availiable at the url /name/ """ api = Blueprint(name, __name__, url_prefix='/'+name) rpc_api = JSONRPCAPI(SmartDispatcher()) assert type(rpc_api.dispatcher == SmartDispatcher) api.add_url_rule('/', 'rpc', rpc_api.as_view(), methods=['POST']) return api, rpc_api.dispatcher.add_method
def register_base_urls(app): from base.views import VVerify views_pages = Blueprint( 'base', __name__, template_folder='templates', static_folder='static' ) views_pages.add_url_rule('/test/verify', view_func=VVerify.as_view('views'), ) app.register_blueprint(views_pages)
class App(BaseApp): module = 'http://mollyproject.org/apps/places' human_name = _('Places') def __init__(self, instance_name, config, providers, services): self.instance_name = instance_name poi_service = PointsOfInterest(instance_name, services['kv'].db[instance_name], services['search']) for provider in providers: provider.poi_service = poi_service self._register_provider_as_importer(provider, services) self._poi_endpoint = PointOfInterestEndpoint(instance_name, poi_service) self._nearby_search_endpoint = NearbySearchEndpoint(instance_name, poi_service) self._search_endpoint = PointOfInterestSearchEndpoint(instance_name, poi_service) self.blueprint = Blueprint(self.instance_name, __name__) self.blueprint.add_url_rule('/<slug>/', 'poi', self._poi_endpoint.get) self.blueprint.add_url_rule( '/nearby/<float:lat>,<float:lon>/', 'nearby', self._nearby_search_endpoint.get_nearby ) self.blueprint.add_url_rule( '/nearby/<float:lat>,<float:lon>/category/<slug>/', 'nearby_category', self._nearby_search_endpoint.get_category ) self.blueprint.add_url_rule( '/nearby/<float:lat>,<float:lon>/amenity/<slug>/', 'nearby_amenity', self._nearby_search_endpoint.get_amenity ) self.blueprint.add_url_rule( '/search', 'search', self._search_endpoint.get ) @property def links(self): return [ self.nearby_homepage_component, self.search_homepage_component ] @property def nearby_homepage_component(self): return { 'self': 'http://mollyproject.org/apps/places/nearby', 'href': self._get_url_template('nearby') } @property def search_homepage_component(self): return { 'self': 'http://mollyproject.org/apps/places/search', 'href': self._search_endpoint.href() }
from flask.views import MethodView from app.comments.models import Comment from ....utils import jwt_required comments_blueprint = Blueprint('comments', __name__) class CommentsListAPIView(MethodView): """ Update Instance api resource """ @jwt_required def post(self, answer_id=None): data = request.get_json(force=True) data['answer_id'] = answer_id response = Comment(data).save() if response: response_object = {'message': 'Your comment was successful'} return make_response(jsonify(response_object)), 201 response_object = {'message': 'Some error occurred. Please try again.'} return make_response(jsonify(response_object)), 400 # Define the API resources comment_view = CommentsListAPIView.as_view('comment_api') # Add Rules for API Endpoints comments_blueprint.add_url_rule( '/api/v1/questions/answers/comment/<string:answer_id>', view_func=comment_view, methods=['POST'])
import logging from flask import Blueprint from burgeon.api.social.points_api import AddPointsAPI from burgeon.api.social.get_profile_api import GetProfileAPI log = logging.getLogger('burgeon.social') social_blueprint = Blueprint('social', __name__) # API resources add_points_api_view = AddPointsAPI.as_view('add_points_api') get_profile_api_view = GetProfileAPI.as_view('get_profile_api') # API Endpoints social_blueprint.add_url_rule( '/social/add_points', view_func=add_points_api_view, methods=['POST'] ) social_blueprint.add_url_rule( '/profile/<int:user_id>', view_func=get_profile_api_view, methods=['GET'] )
def create_app(*, config_module_class: str) -> Flask: """ Creates app in function so that flask with flask extensions can be initialized with specific config. Here it defines the route of APIs so that it can be seen in one place where implementation is separated. Config is being fetched via module.class name where module.class name can be passed through environment variable. This is to make config fetched through runtime PYTHON_PATH so that Config class can be easily injected. More on: http://flask.pocoo.org/docs/1.0/config/ :param config_module_class: name of the config (TODO: Implement config.py) :return: Flask """ if FLASK_APP_MODULE_NAME and FLASK_APP_CLASS_NAME: print('Using requested Flask module {module_name} and class {class_name}' .format(module_name=FLASK_APP_MODULE_NAME, class_name=FLASK_APP_CLASS_NAME), file=sys.stderr) class_obj = getattr(importlib.import_module(FLASK_APP_MODULE_NAME), FLASK_APP_CLASS_NAME) flask_kwargs_dict = {} # type: Dict[str, Any] if FLASK_APP_KWARGS_DICT_STR: print('Using kwargs {kwargs} to instantiate Flask'.format(kwargs=FLASK_APP_KWARGS_DICT_STR), file=sys.stderr) flask_kwargs_dict = ast.literal_eval(FLASK_APP_KWARGS_DICT_STR) app = class_obj(__name__, **flask_kwargs_dict) else: app = Flask(__name__) if CORS_ENABLED: CORS(app) config_module_class = \ os.getenv('METADATA_SVC_CONFIG_MODULE_CLASS') or config_module_class app.config.from_object(config_module_class) if app.config.get('LOG_CONFIG_FILE'): logging.config.fileConfig(app.config.get('LOG_CONFIG_FILE'), disable_existing_loggers=False) else: logging.basicConfig(format=app.config.get('LOG_FORMAT'), datefmt=app.config.get('LOG_DATE_FORMAT')) logging.getLogger().setLevel(app.config.get('LOG_LEVEL')) logging.info('Created app with config name {}'.format(config_module_class)) logging.info('Using backend {}'.format(app.config.get('PROXY_CLIENT'))) api_bp = Blueprint('api', __name__) api_bp.add_url_rule('/healthcheck', 'healthcheck', healthcheck) api = Api(api_bp) api.add_resource(PopularTablesAPI, '/popular_tables/') api.add_resource(TableDetailAPI, '/table/<path:table_uri>') api.add_resource(TableDescriptionAPI, '/table/<path:id>/description') api.add_resource(TableTagAPI, '/table/<path:id>/tag/<tag>') api.add_resource(TableOwnerAPI, '/table/<path:table_uri>/owner/<owner>') api.add_resource(ColumnDescriptionAPI, '/table/<path:table_uri>/column/<column_name>/description') api.add_resource(Neo4jDetailAPI, '/latest_updated_ts') api.add_resource(TagAPI, '/tags/') api.add_resource(UserDetailAPI, '/user', '/user/<path:id>') api.add_resource(UserFollowsAPI, '/user/<path:user_id>/follow/') api.add_resource(UserFollowAPI, '/user/<path:user_id>/follow/<resource_type>/<path:resource_id>') api.add_resource(UserOwnsAPI, '/user/<path:user_id>/own/') api.add_resource(UserOwnAPI, '/user/<path:user_id>/own/<resource_type>/<path:table_uri>') api.add_resource(UserReadsAPI, '/user/<path:user_id>/read/') api.add_resource(DashboardDetailAPI, '/dashboard/<path:id>') api.add_resource(DashboardDescriptionAPI, '/dashboard/<path:id>/description') api.add_resource(DashboardTagAPI, '/dashboard/<path:id>/tag/<tag>') app.register_blueprint(api_bp) if app.config.get('SWAGGER_ENABLED'): Swagger(app, template_file=os.path.join(ROOT_DIR, app.config.get('SWAGGER_TEMPLATE_PATH')), parse=True) return app
# noinspection PyUnresolvedReferences @news_bp.route('/comments/<int:comment_id>', methods=("DELETE", )) @require_auth @require_sudo def delete_comments(comment_id) -> response_json: comment = Comments.query.filter_by(id=comment_id, status=0).first() if comment is None: return response_json(code=400, msg="该评论不存在") comment.status = 1 db.session.add(comment) db.session.commit() return response_json() news_bp.add_url_rule(rule="", view_func=NewsAPI.as_view("news"), methods=("GET", "POST")) news_bp.add_url_rule(rule="/<int:news_id>", view_func=NewAPI.as_view("new"), methods=("GET", "PUT", "DELETE")) news_bp.add_url_rule(rule="/<int:news_id>/comments", view_func=NewsCommentsAPI.as_view("NewsCommentsAPI"), methods=("GET", "POST")) news_bp.add_url_rule(rule="/tags", view_func=TagsAPI.as_view("tags"), methods=("GET", "POST")) news_bp.add_url_rule(rule="/tags/<int:tag_id>", view_func=TagAPI.as_view("tag"), methods=("DELETE", "PUT"))
id = request_data.get("id", "") if "q" in request_data: id = request_data["q"] if "query" in request_data: id = request_data[u"query"] _post_analytics(g.user, "CKAN API Request", logic_function, "", id) except Exception as e: log.debug(e) pass return api.action(logic_function, ver) ga.add_url_rule( "/api/action/<logic_function>", methods=["GET", "POST"], view_func=action, ) ga.add_url_rule( u"/<int(min=3, max={0}):ver>/action/<logic_function>".format( api.API_MAX_VERSION), methods=["GET", "POST"], view_func=action, ) def download(id, resource_id, filename=None, package_type="dataset"): handler_path = tk.config.get(CONFIG_HANDLER_PATH) if handler_path: handler = import_string(handler_path, silent=True) else:
except AccessDenied as exception: return generate_http_error_flask(401, 'AccessDenied', exception.args[0][0]) except AccountNotFound as exception: return generate_http_error_flask(404, 'AccountNotFound', exception.args[0][0]) except RSENotFound as exception: return generate_http_error_flask(404, 'RSENotFound', exception.args[0][0]) except Exception as exception: print format_exc() return exception, 500 return "OK", 200 bp = Blueprint('account_limit', __name__) account_limit_view = AccountLimit.as_view('account_limit') bp.add_url_rule('/<account>/<rse>', view_func=account_limit_view, methods=['post', 'delete']) application = Flask(__name__) application.register_blueprint(bp) application.before_request(before_request) application.after_request(after_request) def make_doc(): """ Only used for sphinx documentation to add the prefix """ doc_app = Flask(__name__) doc_app.register_blueprint(bp, url_prefix='/accounts') return doc_app if __name__ == "__main__":
class LoginAPI(MethodView): def post(self): post_data = request.get_json() email = post_data.get('email') password = post_data.get('password') try: user = User.query.filter_by(email=email).first() if user is None: responseObject = {'message': 'User does not exist!'} return make_response(jsonify(responseObject)), 400 else: responseObject = { 'message': 'Successfully logged in', 'user': user.to_json(), 'auth_token': user.encode_auth_token(user.id).decode() } return make_response(jsonify(responseObject)), 200 except Exception as e: raise e def get(self): pass registration_view = RegisterAPI.as_view('register_api') login_view = LoginAPI.as_view('login_api') auth_bp.add_url_rule('/signup', view_func=registration_view, methods=['POST']) auth_bp.add_url_rule('/login', view_func=login_view, methods=['POST'])
# encoding: utf-8 from flask import Blueprint from ckanext.validation import common validation = Blueprint(u'validation', __name__) validation.add_url_rule(u'/dataset/<id>/resource/<resource_id>/validation', 'read', methods=('GET', ), view_func=common.validation) def get_blueprints(): return [validation]
from flask import Blueprint from .api.file_api import FileApi from .api.user_api import UserApi back_end = Blueprint('BackEnd', __name__, static_folder='static') back_end.add_url_rule('/file/<path:path>/', endpoint='FileApi', view_func=FileApi.as_view('file_api'), methods=['GET', 'POST', 'PATCH', 'DELETE']) back_end.add_url_rule('/user/', endpoint='UserApi', view_func=UserApi.as_view('user_api'), methods=['POST'])
'''rmon.views.urls 定义了所有API对应的URL''' from flask import Blueprint from rmon.views.index import IndexView api = Blueprint('api', __name__) # 通过api.add_url_rule方法添加了IndexView视图控制器对应的路由URL:/ # 当通过GET HTTP方法访问URL/时,就会执行IndexView中对应的get方法 api.add_url_rule('/', view_func=IndexView.as_view('index'))
if remmber: session.permanent = True return redirect(url_for("cms.index")) #蓝图中反转必须加上蓝图名字 else: return redirect(url_for("cms.index")) else: return self.get(message="邮箱或者密码错误") #如果用户不存在,返回错误 else: message = form.errors.popitem()[1][0] #如果forms验证不通过,说明密码或者邮箱格式不对 #所有错误类型都是存在form.errors字典中 #列:form.errors={"password":["密码错误"]},通过popitem(),取出:("password",["密码错误"]) return self.get(message) #调用get方法实现本页面的跳转 bp.add_url_rule("/login/", view_func=LoginView.as_view("login")) #定义一个个人信息页面 @bp.route("/profile/") @login_required def profile(): return render_template("cms/cms_profile.html") #注意:在html页面中{{}}里面必须写内容,不能空着,否则会报错。 #邮箱的发送 @bp.route("/captcha/") def send_captcha():
post = Post.objects.get_or_404(slug=slug) form = self.form(request.form) context = {"post": post, "form": form} return context def get(self, slug): context = self.get_context(slug) return render_template('posts/detail.html', **context) def post(self, slug): context = self.get_context(slug) form = context.get('form') if form.validate(): comment = Comment() form.populate_obj(comment) post = context.get('post') post.comments.append(comment) post.save() return redirect(url_for('posts.detail', slug=slug)) return render_template('posts/detail.html', **context) # Register the urls posts.add_url_rule('/posts', view_func=ListView.as_view('list')) posts.add_url_rule('/posts/<slug>/', view_func=DetailView.as_view('detail'))
'visualize_colors': visualize_colors, 'bar_chart_icon': config.get('bar_chart_icon'), 'line_chart_icon': config.get('line_chart_icon'), 'point_chart_icon': config.get('point_chart_icon'), }, 'errors': {} } return render('admin/visualize_data.html', extra_vars=vars) def _upload_chart_icon(chart_type, data): if '{0}_chart_upload'.format(chart_type) in data: image_upload = data.get('{0}_chart_upload'.format(chart_type)) if isinstance(image_upload, ALLOWED_UPLOAD_TYPES): upload = uploader.get_uploader( 'chart_icons', data.get('{0}_chart'.format(chart_type))) upload.update_data_dict( data, '{0}_chart'.format(chart_type), '{0}_chart_upload'.format(chart_type), '{0}_chart_clear_upload'.format(chart_type)) upload.upload(uploader.get_max_image_size()) return upload.filename else: return data.get('{0}_chart'.format(chart_type)) admin_visualize.add_url_rule(u'/visualize_data', view_func=visualize_data, methods=[u'GET', u'POST'])
#!/usr/bin/env python # -*- coding=UTF-8 -*- # ************************************************************************** # Copyright © 2016 jianglin # File Name: urls.py # Author: jianglin # Email: [email protected] # Created: 2016-07-15 18:36:33 (CST) # Last Update:星期一 2016-7-25 15:34:19 (CST) # By: # Description: # ************************************************************************** from flask import Blueprint from .views import setting, password, privacy, babel site = Blueprint('setting', __name__) site.add_url_rule('', view_func=setting, methods=['GET', 'POST']) site.add_url_rule('/profile', view_func=setting, methods=['GET', 'POST']) site.add_url_rule('/password', view_func=password, methods=['GET', 'POST']) site.add_url_rule('/privacy', view_func=privacy, methods=['GET', 'POST']) site.add_url_rule('/babel', view_func=babel, methods=['GET', 'POST'])
} return make_response(jsonify(response)), 200 else: return "Error while updating" else: if (gotData): response = { "id": gotData.id, "question_id": gotData.question_id, "section_id": gotData.section_id, "comments": gotData.comments, 'message': "Retrieved successfully" } return make_response(jsonify(response)), 200 else: return "Error while fetching data" # define the API resources ans_post_view = AnswerPOSTAPI.as_view('ans_post_api') ass_get_view = AnswerGETAPI.as_view('ass_get_api') answer_blueprint.add_url_rule('/answer', view_func=ans_post_view, methods=['POST']) answer_blueprint.add_url_rule('/answer', view_func=ass_get_view, methods=['GET'])
region_data = [ dict(zip(('region', 'method', 'conclusion'), r)) for r in regions ] data[d.name] = {r['region']: r for r in region_data} regions = ( EtcDicBiogeoreg.query .with_entities(EtcDicBiogeoreg.reg_code) .filter_by(dataset_id=current_dataset) .order_by(EtcDicBiogeoreg.order) ) return render_template('progress/compare.html', **{'data': data, 'regions': regions}) progress.add_url_rule('/species/progress/', view_func=SpeciesProgress.as_view('species-progress')) progress.add_url_rule('/habitat/progress/', view_func=HabitatProgress.as_view('habitat-progress')) progress.add_url_rule('/species/progress/compare/', view_func=ComparisonView.as_view('species-comparison', mixin=SpeciesMixin)) progress.add_url_rule('/habitat/progress/compare/', view_func=ComparisonView.as_view('habitat-comparison', mixin=HabitatMixin)) progress.add_url_rule('/habitat/progress/table/', view_func=HabitatProgressTable.as_view('habitat-progress-table')) @progress.route('/species/progress/assessors', endpoint='species-assessors') def species_assessors(): data = SpeciesMixin.get_assessors( request.args.get('period'), request.args.get('group'))
request_json = request.json name = request_json.get('name') try: with db.connection as con: con.execute( """ INSERT INTO city (name) VALUES (?) """, (name, )) cur = con.execute( """ SELECT * FROM city WHERE name = ? """, (name, )) response = cur.fetchone() return jsonify(dict(response)), 201 except sqlite3.IntegrityError: with db.connection as con: cur = con.execute( f""" SELECT * FROM city WHERE name =? """, (name, )) response = cur.fetchone() return jsonify(dict(response)), 302 bp.add_url_rule('', view_func=Cities.as_view('cities'))
return redirect(url_for('main.links')) prev_page = url_for('main.links', page=links_list.prev_num) if links_list.has_prev else None next_page = url_for('main.links', page=links_list.next_num) if links_list.has_next else None return render_template('main/links.html', form=form, links_list=links_list.items, prev=prev_page, next=next_page, ) @main.route('/redirect_link/<link_hash>') def redirect_link(link_hash): link = Link.query.filter_by(hash_str=link_hash).first() if link: ip = request.remote_addr agent = request.headers.get('User-Agent') new_action = Action(link_id=link.id, type_id=1, ip_address=ip, user_agent=agent, timestamp=datetime.utcnow()) db.session.add(new_action) db.session.commit() url = '{0}?partner_id={1}&hash={2}&k={3}'.format(link.site, 1, link.hash_str, current_app.config['ADVERT_SECRET_KEY']) return redirect(url) main.add_url_rule('/profile', view_func=ProfileView.as_view('profile'))
try: all_details = Assigned_Classes.query.filter_by( user_id=user_id).first() questions = Questions.query.filter_by( all_details.questions).first() classes = AllClasses.query.filter_by(all_details.classes).first() responseObject = { 'status': 'success', 'data': { 'questions': questions, 'classes': classes } } return make_response(jsonify(responseObject)), 200 except Exception as e: responseObject = { 'status': 'fail', 'message': ' No Questions or Classes found.' } return make_response(jsonify(responseObject)), 400 get_assign_classes = GetAssignedClassesAPI.as_view('get_assign_classes') user_side_info_blueprint.add_url_rule('/class_details', view_func=get_assign_classes, methods=['GET'])
from dataservice.api.study_file import StudyFileListAPI from dataservice.api.genomic_file import GenomicFileAPI from dataservice.api.genomic_file import GenomicFileListAPI from dataservice.api.read_group import ReadGroupAPI from dataservice.api.read_group import ReadGroupListAPI from dataservice.api.read_group_genomic_file import ( ReadGroupGenomicFileAPI, ReadGroupGenomicFileListAPI) from dataservice.api.biospecimen_genomic_file import ( BiospecimenGenomicFileAPI, BiospecimenGenomicFileListAPI) from dataservice.api.biospecimen_diagnosis import (BiospecimenDiagnosisAPI, BiospecimenDiagnosisListAPI) from dataservice.api.study.models import Study api = Blueprint('api', __name__, url_prefix='', template_folder='templates') # Documentation docs_view = Documentation.as_view('docs') logo_view = Logo.as_view('logo') swagger_view = Swagger.as_view('swagger') api.add_url_rule('/', view_func=docs_view, methods=['GET']) api.add_url_rule('/logo', view_func=logo_view, methods=['GET']) api.add_url_rule('/docs', view_func=docs_view, methods=['GET']) api.add_url_rule('/swagger', view_func=swagger_view, methods=['GET']) # Status resource status_view = StatusAPI.as_view('status') api.add_url_rule('/status', view_func=status_view, methods=['GET']) # All CRUD resources views = CRUDView.register_views(api)
cls = self.class_map.get(request.args.get('type', 'post')) post = cls() form_cls = model_form(cls, exclude=('created_at', 'comments')) form = form_cls(request.form) context = {"post": post, "form": form, "create": slug is None} return context def get(self, slug): context = self.get_context(slug) return render_template('blog/admin/detail.html', **context) def post(self, slug): context = self.get_context(slug) form = context.get('form') if form.validate(): post = context.get('post') form.populate_obj(post) post.save() return redirect(url_for('admin.index')) return render_template('blog/admin/detail.html', **context) # Register the urls admin.add_url_rule('/admin/', view_func=List.as_view('index')) admin.add_url_rule('/admin/create/', defaults={'slug': None}, view_func=Detail.as_view('create')) admin.add_url_rule('/admin/<slug>/', view_func=Detail.as_view('edit'))
return dataset.read(package_type, id) def resource_read(package_type, id, resource_id): """ Override the default CKAN behaviour for private Dataset Resource visibility. Instead of displaying "404 Dataset not found" message, give unauthenticated users a chance to log in. :param id: Package id/name :param resource_id: Resource id :return: """ if not g.user and not _is_dataset_public(id): return make_uncached_response(redirect_to( url_for('user.login', came_from=url_for('resource.read', id=id, resource_id=resource_id)) )) return resource.read(package_type, id, resource_id) _dataset.add_url_rule(u'new', view_func=dataset.CreateView.as_view('new')) _dataset.add_url_rule(u'<id>', view_func=dataset_read) _dataset.add_url_rule(u'<id>/resource/new', view_func=resource.CreateView.as_view('new_resource')) _dataset.add_url_rule(u'<id>/resource/<resource_id>', view_func=resource_read) def get_blueprints(): return [_dataset]
def post(self): form = CMSLoginForm(request.form) logging.warning(form) if form.validate(): username = form.username.data password = form.password.data # print(username) # print(password) logging.info('username:%s' % username) logging.info('password:%s' % password) user = CMSUser.query.filter_by(username=username).first() print(user) # print(user.username) # print(user.password) if user and user.check_password(password): session[DevConfig.CMS_USER_ID] = user.id return redirect(url_for('cms.index')) return '用户名或密码不正确' return '验证不通过' bp.add_url_rule('/login/', view_func=CMSLogin.as_view('login')) @bp.route('/logout/') @login_required def logout(): del session[DevConfig.CMS_USER_ID] return redirect(url_for('cms.login'))
self.url = '127.0.0.1' self.password = master_password.MPW(self.username, self.mpw).password( self.url).replace('/', '') def post(self): if not self.login(): return make_response( 'Unauthorized', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}) return self.session_id def delete(self): if not self.check_session_id(): return make_response('Logout failed', 401) return make_response('Logout success', 200) def login(self): auth = request.authorization if auth and self.check_auth(auth.username, auth.password): return True return False def check_auth(self, username, password): if username == self.username and password == self.password: return True return False authBluePrint.add_url_rule('/com/vmware/cis/session', view_func=Authentication.as_view('Authentication'))
# generate the auth token auth_token = user.encode_auth_token(user.id) responseObject = { 'status': 'success', 'message': 'Successfully registered.', 'auth_token': auth_token.decode() } return make_response(jsonify(responseObject)), 201 except Exception as e: responseObject = { 'status': 'fail', 'message': 'Some error occurred. Please try again.' } return make_response(jsonify(responseObject)), 401 else: responseObject = { 'status': 'fail', 'message': 'User already exists. Please Log in.', } return make_response(jsonify(responseObject)), 202 # define the API resources registration_view = RegisterAPI.as_view('register_api') # add Rules for API Endpoints auth_blueprint.add_url_rule( '/auth/register', view_func=registration_view, methods=['POST', 'GET'] )
# By: # Description: # ************************************************************************** from flask import Blueprint from .views import (UserCollectListView, UserFollowingListView, UserFollowerListView, UserListView, UserReplyListView, UserView) site = Blueprint('user', __name__, url_prefix='/u') user_list = UserListView.as_view('list') user = UserView.as_view('user') topics = UserView.as_view('topic') replies = UserReplyListView.as_view('reply') collects = UserCollectListView.as_view('collect') followers = UserFollowerListView.as_view('follower') followings = UserFollowingListView.as_view('following') site.add_url_rule('', view_func=user_list) site.add_url_rule('/<username>', view_func=user) site.add_url_rule('/<username>/topics', view_func=topics) site.add_url_rule('/<username>/replies', view_func=replies) site.add_url_rule('/<username>/collects', view_func=collects) site.add_url_rule('/<username>/followers', view_func=followers) site.add_url_rule('/<username>/followings', view_func=followings) def init_app(app): app.register_blueprint(site)
def get(self, user_id): try: page = int(request.values.get('page')) except: page = 1 limit = 10 offset = (page - 1) * limit feeds = backend.get_latest_feed(user_id, limit, offset) if len(feeds) > 0: feeds = pipe_load(feeds) curr_user = backend.get_user_by_uid(g.ukey) liked_post_ids = [p['id'] for p in feeds] liked_dict = backend.is_like_post(curr_user['id'], liked_post_ids) for up in feeds: up['is_like'] = liked_dict.get(up['id']) or False if page == 1: redis.hset(FEED_UPDATE_TIME_KEY % {'user_id': user_id}, 'last_update_time', int(time.time())) return jsonify(results=feeds, page=page) instance.add_url_rule('/feeds/<int:user_id>', view_func=FeedsView.as_view('feed')) instance.add_url_rule('/feeds/notify/<int:user_id>', view_func=NewFeedView.as_view('feed_notify'))
for key in admin_schema: data[key] = config.get(key) extra_vars = {"data": data, "errors": {}} return toolkit.render("admin/dataportal.html", extra_vars=extra_vars) dataportal_admin.provide_automatic_options = False dataportal_admin.methods = ['GET', 'POST'] def group_dashboard(): group = request.args.get("g", "") extra_vars = {"selected_group": group} return toolkit.render("home/index.html", extra_vars=extra_vars) rules = [ ("/standard-date/esentiale", data_stats_essential), ("/standard-date/structura", data_stats_struct), ("/termsandconditions", terms_and_conditions), ("/contact-form", contact_form), ("/cookiepolicy", cookie_policy), ("/codeofconduct", code_of_conduct), ("/ckan-admin/dataportal", dataportal_admin), ("/group-dashboard", group_dashboard), ] for rule in rules: dpt_blueprint.add_url_rule(rule[0], view_func=rule[1])
class IndexView(LoggedInView): template = "queries/index.html" def render(self, ): query_urls = [{ "url": url_for("queries.run", query_idx=idx), "heading": queries[idx].heading, "text": queries[idx].text, } for idx in range(len(queries)) if queries[idx].is_allowed()] return super().render(queries=query_urls) class ShowQueryView(QueryView): query = None def dispatch_request(self, query_idx): if query_idx < 0 or query_idx >= len(queries): abort(404) self.query = queries[query_idx] return super().dispatch_request() queries_bp = Blueprint("queries", __name__, url_prefix="/queries") queries_bp.add_url_rule("/<int:query_idx>", view_func=ShowQueryView.as_view(name="run")) queries_bp.add_url_rule("/unauth", view_func=UnauthView.as_view(name="unauth")) queries_bp.add_url_rule("/", view_func=IndexView.as_view(name="index"))
#!/usr/bin/env python # -*- coding: utf-8 -*- # ************************************************************************** # Copyright © 2016 jianglin # File Name: urls.py # Author: jianglin # Email: [email protected] # Created: 2016-12-21 21:56:49 (CST) # Last Update:星期五 2017-11-10 10:57:55 (CST) # By: # Description: # ************************************************************************** from flask import Blueprint from .views import AvatarView, AvatarFileView site = Blueprint('upload', __name__) avatar_file_view = AvatarFileView.as_view('avatar_file') avatar_view = AvatarView.as_view('avatar') site.add_url_rule('/avatar', view_func=avatar_view) site.add_url_rule('/avatars/<filename>', view_func=avatar_file_view) def init_app(app): app.register_blueprint(site)