def get_app(config): app = Flask(__name__) app.config.from_object(config) mail.init_app(app) RQ(app) csrf = CsrfProtect(app) csrf.exempt(api_1_0_blueprint) stream_handler = logging.StreamHandler() app.logger.setLevel(logging.DEBUG) app.logger.addHandler(stream_handler) db.init_app(app) Migrate(app, db) bootstrap = Bootstrap(app) security = Security(app, user_datastore) user_registered.connect(user_registered_sighandler) app.register_blueprint(ratings_blueprint) app.register_blueprint(api_1_0_blueprint, url_prefix="/api/v1") app.register_blueprint(verify_blueprint, url_prefix="/v") app.register_blueprint(tournament_blueprint, url_prefix="/tournament") app.register_error_handler(500, email_exception) return app
def register_handlers(app): if app.config['CSRF_ENABLED']: from flask_wtf.csrf import CsrfProtect csrf = CsrfProtect(app) from view.group import groupview from view.user import userview from view.order import orderview from view.alipayapp import alipayview from view.SkuList import buylistview from view.bot import botview from view.workflow import workflowview from view.sku import skuview from view.wechatapp import wechatview from view.other import otherview if app.config['CSRF_ENABLED']: csrf.exempt(alipayview) csrf.exempt(botview) app.register_blueprint(userview) app.register_blueprint(groupview) app.register_blueprint(orderview) app.register_blueprint(alipayview) app.register_blueprint(buylistview, url_prefix='/skulist') app.register_blueprint(botview, url_prefix='/bot') app.register_blueprint(workflowview, url_prefix='/wf') app.register_blueprint(skuview, url_prefix='/sku') app.register_blueprint(wechatview, url_prefix='/wechat') app.register_blueprint(otherview) register_api(app)
def get_app(config): app = Flask(__name__) app.config.from_object(config) mail.init_app(app) RQ(app) csrf = CsrfProtect(app) csrf.exempt(api_1_0_blueprint) stream_handler = logging.StreamHandler() if app.debug: stream_handler.setLevel(logging.INFO) else: stream_handler.setLevel(logging.WARN) app.logger.addHandler(stream_handler) db.init_app(app) bootstrap = Bootstrap(app) security = Security(app, user_datastore) user_registered.connect(user_registered_sighandler) app.register_blueprint(ratings_blueprint) app.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1') app.register_blueprint(verify_blueprint, url_prefix='/v') return app
def create_app(object_name): """ An flask application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/ Arguments: object_name: the python path of the config object, e.g. mothership.settings.ProdConfig env: The name of the current environment, e.g. prod or dev """ app = Flask(__name__) @app.before_first_request def _run_on_start(): init_db() csrf = CsrfProtect(app) @app.template_filter('datetime') def datetimeformat(value, format='%d/%m/%y %H:%M %p'): return datetime.datetime.utcfromtimestamp(value).strftime(format) app.config.from_object(object_name) # initialize the cache cache.init_app(app) # initialize the debug tool bar # debug_toolbar.init_app(app) # initialize SQLAlchemy db.init_app(app) login_manager.init_app(app) # Import and register the different asset bundles assets_env.init_app(app) assets_loader = PythonAssetsLoader(assets) for name, bundle in assets_loader.load_bundles().items(): assets_env.register(name, bundle) # register our blueprints app.register_blueprint(main) app.register_blueprint(campaigns) app.register_blueprint(graphs) app.register_blueprint(fuzzers) csrf.exempt(fuzzers) try: os.mkdir(app.config['DATA_DIRECTORY']) except FileExistsError: pass return app
def initialise(self): """ The application needs initialisation to load the database connection etc. In previous versions this was done with the initialisation of the class in the __init__ method. This is now separated into this function. """ #: Check if the secret key is defined, if not raise an #: exception since it is required assert self.secret_key, 'Secret Key is not defined in config' #: Load the cache self.load_cache() #: Initialise the CSRF handling self.csrf_protection = CsrfProtect() self.csrf_protection.init_app(self) self.view_functions['static'] = self.send_static_file # Backend initialisation self.load_backend() #: Initialise the login handler login_manager = LoginManager() login_manager.user_loader(self._pool.get('nereid.user').load_user) login_manager.header_loader( self._pool.get('nereid.user').load_user_from_header ) login_manager.token_loader( self._pool.get('nereid.user').load_user_from_token ) login_manager.unauthorized_handler( self._pool.get('nereid.user').unauthorized_handler ) login_manager.login_view = "nereid.website.login" login_manager.anonymous_user = self._pool.get('nereid.user.anonymous') login_manager.init_app(self) self.login_manager = login_manager # Monkey patch the url_for method from flask-login to use # the nereid specific url_for flask.ext.login.url_for = url_for self.template_context_processors[None].append( self.get_context_processors() ) # Add the additional template context processors self.template_context_processors[None].append( nereid_default_template_ctx_processor ) # Add template_filters registered using decorator for name, function in self.get_template_filters(): self.jinja_env.filters[name] = function # Finally set the initialised attribute self.initialised = True
def __init__(self, config, test, test_db_uri): if self.__class__._instance is not None: raise EnvironmentUninitializedError() self.__s3_conn = None self.__fixtures = None self.__db = SQLAlchemy() for path in CONFIG_PATH_LOCATIONS: sys.path.append(path) if config is None: # None will be passed by manage.py. # A default param value will get overwritten, so this is implemented here. config = 'splice.default_settings.DefaultConfig' if not test: # load config from environment if it exists config = os.environ.get('SPLICE_SETTINGS', config) config_obj = load_config_obj(config) if test: config_obj.ENVIRONMENT = 'test' config_obj.SQLALCHEMY_DATABASE_URI = test_db_uri config_obj.SQLALCHEMY_BINDS = {'stats': test_db_uri} config_obj.SQLALCHEMY_POOL_SIZE = None config_obj.SQLALCHEMY_POOL_TIMEOUT = None self.log = Mock() self.__s3_conn = Mock() else: self.__loggers = self.__setup_loggers(config_obj) self.config = config_obj app = Flask('splice') app.config.from_object(config) if app.config['ENVIRONMENT'] not in app.config['STATIC_ENABLED_ENVS']: app.config['STATIC_FOLDER'] = None self.__application = app if not test: # pragma: no cover self.csrf = CsrfProtect() self.csrf.init_app(app) # A hack to keep the sqlalchemy binds state. Flask-SQLAlchemy strips it out sqlalchemy_binds = app.config.get('SQLALCHEMY_BINDS') self.db.init_app(self.__application) app.config.SQLALCHEMY_BINDS = sqlalchemy_binds Migrate(self.__application, self.db)
def create_app(settings_file): app = Flask(__name__) app.config.from_pyfile(settings_file) cache.init_app(app) mail = Mail() csrf = CsrfProtect() csrf.init_app(app) db.init_app(app) toolbar = DebugToolbarExtension() toolbar.init_app(app) app.mail = mail mail.init_app(app) app.hashids = Hashids(salt="salty seafaring sailor", min_length=8) register_errorhandlers(app) app.register_blueprint(main) return app
def __init__(self, app_config, import_name, static_path=None, static_url_path=None, static_folder='static', template_folder='templates', instance_path=None, instance_relative_config=False): from flask.ext.cache import Cache from ambry.library import Library from ambry.run import get_runconfig self._initialized = False self.csrf = CsrfProtect() self.login_manager = LoginManager() super(Application, self).__init__(import_name, static_path, static_url_path, static_folder, template_folder, instance_path, instance_relative_config) self.config.update(app_config) l = Library(get_runconfig(), read_only=True, echo=False) self.cache = Cache(config={'CACHE_TYPE': 'filesystem', 'CACHE_DIR': l.filesystem.cache('ui')}) self.cache.init_app(self)
def create_app(config="config.ini"): app = Flask(__name__, static_url_path='/static') app.config.from_object(__name__) if os.path.exists(config): app.config.from_pyfile(config) else: print("The app does not have a config.ini file") # Define the WSGI application object db.init_app(app) # csrf protection login_manager.init_app(app) principals.init_app(app) csrf = CsrfProtect() csrf.init_app(app) # Register blueprint(s) from modules.inventory import inventory as inventory_blueprint app.register_blueprint(inventory_blueprint, url_prefix='/inventory') from modules.user import user as user_blueprint app.register_blueprint(user_blueprint, url_prefix='/user') from login import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') @app.route("/", methods=['GET']) @login_required @user.require(http_exception=403) def index(): return render_template("index.html", menu=principal_menu()) # Sample HTTP error handling @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 # Sample HTTP error handling @app.errorhandler(403) def access_denied(error): return render_template('403.html'), 403 # Sample HTTP error handling @app.errorhandler(500) def server_full(error): return render_template('500.html'), 500 @app.before_request def make_session_permanent(): session.permanent = True app.permanent_session_lifetime = timedelta(minutes=5) session.modified = True @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): needs = [] if identity.id in ('viewer', 'editor', 'admin'): needs.append(to_view) if identity.id in ('editor', 'admin'): needs.append(be_editor) if identity.id == 'admin': needs.append(be_admin) for n in needs: identity.provides.add(n) # If the authenticated identity is : # - 'the_only user' she can sign in # - "the_only_editor" she can sign in and edit # - "the_only_admin" she can sign in , edit and administrate return app
@app.route('/todolist_yes', methods=['GET']) def getAllTodolist2(): todolist = Todolist.query.filter(Todolist.status==True).all() return render_template('todolist_list.html', title='Complete Todolist', todolist=todolist) @app.route('/todolist_no', methods=['GET']) def getAllTodolist3(): todolist = Todolist.query.filter(Todolist.status==False).all() return render_template('todolist_list.html', title='Uncomplete Todolist', todolist=todolist) @app.route('/delete_todolist/<id>', methods=['GET']) def delete_todolist(id): todolist = Todolist.query.get(id) db.session.delete(todolist) db.session.commit() return redirect('/') @app.route('/todolist_complete/<id>', methods=['GET']) def todolist_complete(id): todolist = Todolist.query.get(id) todolist.status=True db.session.commit() return redirect('/') CsrfProtect(app) #csrf保护
from logging.handlers import RotatingFileHandler from logging import Formatter from config import load_config from flask.ext.login import LoginManager from flask_wtf.csrf import CsrfProtect import myapp from admin.MyModelView import MyAdminIndexView app = Flask(__name__) app.config.from_object(load_config()) api_bp = Blueprint('api', __name__) api = Api(api_bp) db = SQLAlchemy(app) csrf = CsrfProtect(app) admin = Admin(app, name='PinPin Admin', index_view=MyAdminIndexView(), template_mode='bootstrap3') app.wsgi_app = ProxyFix(app.wsgi_app) Bootstrap(app) login_manager = LoginManager() login_manager.login_view = "userview.login" login_manager.init_app(app) from module.user.user import User as UserModule @login_manager.user_loader def load_user(user_id): '''
#!/USR/BIN/PYTHON from flask import Flask import sys # APP SETTINGS app = Flask(__name__) app.config["DEBUG"] = True app.config.from_object("config") # CSRF PROTECT AND ASSETS from flask_wtf.csrf import CsrfProtect csrf = CsrfProtect(app) from flask_images import Images app.config["IMAGES_PATH"] = ['static/img/photowall'] # app.config["IMAGES_CACHE"] = '/static/cache' images = Images(app) from app import views
class Nereid(Flask): """ ... Unlike typical web frameworks and their APIs, nereid depends more on configuration and not direct python modules written along the APIs Most of the functional code will remain on the modules installed on Tryton, and the database configurations. ... """ #: The class that is used for request objects. See #: :class:`~nereid.wrappers.Request` #: for more information. request_class = Request #: The class that is used for response objects. See #: :class:`~nereid.wrappers.Response` for more information. response_class = Response #: the session interface to use. By default an instance of #: :class:`~nereid.session.NereidSessionInterface` is used here. session_interface = NereidSessionInterface() #: An internal attribute to hold the Tryton model pool to avoid being #: initialised at every request as it is quite expensive to do so. #: To access the pool from modules, use the :meth:`pool` _pool = None #: The attribute holds a connection to the database backend. _database = None #: Configuration file for Tryton. The path to the configuration file #: can be specified and will be loaded when the application is #: initialised tryton_configfile = ConfigAttribute('TRYTON_CONFIG') #: The location where the translations of the template are stored translations_path = ConfigAttribute('TRANSLATIONS_PATH') #: The name of the database to connect to on initialisation database_name = ConfigAttribute('DATABASE_NAME') #: The default timeout to use if the timeout is not explicitly #: specified in the set or set many argument cache_default_timeout = ConfigAttribute('CACHE_DEFAULT_TIMEOUT') #: the maximum number of items the cache stores before it starts #: deleting some items. #: Applies for: SimpleCache, FileSystemCache cache_threshold = ConfigAttribute('CACHE_THRESHOLD') #: a prefix that is added before all keys. This makes it possible #: to use the same memcached server for different applications. #: Applies for: MecachedCache, GAEMemcachedCache #: If key_prefix is none the value of site is used as key cache_key_prefix = ConfigAttribute('CACHE_KEY_PREFIX') #: a list or tuple of server addresses or alternatively a #: `memcache.Client` or a compatible client. cache_memcached_servers = ConfigAttribute('CACHE_MEMCACHED_SERVERS') #: The directory where cache files are stored if FileSystemCache is used cache_dir = ConfigAttribute('CACHE_DIR') #: The type of cache to use. The type must be a full specification of #: the module so that an import can be made. Examples for werkzeug #: backends are given below #: #: NullCache - werkzeug.contrib.cache.NullCache (default) #: SimpleCache - werkzeug.contrib.cache.SimpleCache #: MemcachedCache - werkzeug.contrib.cache.MemcachedCache #: GAEMemcachedCache - werkzeug.contrib.cache.GAEMemcachedCache #: FileSystemCache - werkzeug.contrib.cache.FileSystemCache cache_type = ConfigAttribute('CACHE_TYPE') #: If a custom cache backend unknown to Nereid is used, then #: the arguments that are needed for the initialisation #: of the cache could be passed here as a `dict` cache_init_kwargs = ConfigAttribute('CACHE_INIT_KWARGS') #: boolean attribute to indicate if the initialisation of backend #: connection and other nereid support features are loaded. The #: application can work only after the initialisation is done. #: It is not advisable to set this manually, instead call the #: :meth:`initialise` initialised = False #: Prefix the name of the website to the template name sutomatically #: This feature would be deprecated in future in lieu of writing #: Jinja2 Loaders which could offer this behavior. This is set to False #: by default. For backward compatibility of loading templates from #: a template folder which has website names as subfolders, set this #: to True #: #: .. versionadded:: 2.8.0.4 template_prefix_website_name = ConfigAttribute( 'TEMPLATE_PREFIX_WEBSITE_NAME') #: Time in seconds for which the token is valid. token_validity_duration = ConfigAttribute('TOKEN_VALIDITY_DURATION') def __init__(self, **config): """ The import_name is forced into `Nereid` """ super(Nereid, self).__init__('nereid', **config) # Update the defaults for config attributes introduced by nereid self.config.update({ 'TRYTON_CONFIG': None, 'TEMPLATE_PREFIX_WEBSITE_NAME': True, 'TOKEN_VALIDITY_DURATION': 60 * 60, 'CACHE_TYPE': 'werkzeug.contrib.cache.NullCache', 'CACHE_DEFAULT_TIMEOUT': 300, 'CACHE_THRESHOLD': 500, 'CACHE_INIT_KWARGS': {}, 'CACHE_KEY_PREFIX': '', }) def initialise(self): """ The application needs initialisation to load the database connection etc. In previous versions this was done with the initialisation of the class in the __init__ method. This is now separated into this function. """ #: Check if the secret key is defined, if not raise an #: exception since it is required assert self.secret_key, 'Secret Key is not defined in config' #: Load the cache self.load_cache() #: Initialise the CSRF handling self.csrf_protection = CsrfProtect() self.csrf_protection.init_app(self) self.view_functions['static'] = self.send_static_file # Backend initialisation self.load_backend() #: Initialise the login handler login_manager = LoginManager() login_manager.user_loader(self._pool.get('nereid.user').load_user) login_manager.header_loader( self._pool.get('nereid.user').load_user_from_header) login_manager.token_loader( self._pool.get('nereid.user').load_user_from_token) login_manager.unauthorized_handler( self._pool.get('nereid.user').unauthorized_handler) login_manager.login_view = "nereid.website.login" login_manager.anonymous_user = self._pool.get('nereid.user.anonymous') login_manager.init_app(self) self.login_manager = login_manager # Monkey patch the url_for method from flask-login to use # the nereid specific url_for flask.ext.login.url_for = url_for self.add_ctx_processors_from_db() # Add the additional template context processors self.template_context_processors[None].append( nereid_default_template_ctx_processor) # Finally set the initialised attribute self.initialised = True def get_urls(self): """ Return the URL rules for routes formed by decorating methods with the :func:`~nereid.helpers.route` decorator. This method goes through all the models and their methods in the pool of the loaded database and looks for the `_url_rules` attribute in them. If there are URLs defined, it is added to the url map. """ rules = [] models = Pool._pool[self.database_name]['model'] for model_name, model in models.iteritems(): for f_name, f in inspect.getmembers(model, predicate=inspect.ismethod): if not hasattr(f, '_url_rules'): continue for rule in f._url_rules: rules.append( self.url_rule_class(rule[0], endpoint='.'.join( [model_name, f_name]), **rule[1])) return rules def load_cache(self): """ Load the cache and assign the Cache interface to """ BackendClass = import_string(self.cache_type) if self.cache_type == 'werkzeug.contrib.cache.NullCache': self.cache = BackendClass(self.cache_default_timeout) elif self.cache_type == 'werkzeug.contrib.cache.SimpleCache': self.cache = BackendClass(self.cache_threshold, self.cache_default_timeout) elif self.cache_type == 'werkzeug.contrib.cache.MemcachedCache': self.cache = BackendClass(self.cache_memcached_servers, self.cache_default_timeout, self.cache_key_prefix) elif self.cache_type == 'werkzeug.contrib.cache.GAEMemcachedCache': self.cache = BackendClass(self.cache_default_timeout, self.cache_key_prefix) elif self.cache_type == 'werkzeug.contrib.cache.FileSystemCache': self.cache = BackendClass(self.cache_dir, self.cache_threshold, self.cache_default_timeout) else: self.cache = BackendClass(**self.cache_init_kwargs) def load_backend(self): """ This method loads the configuration file if specified and also connects to the backend, initialising the pool on the go """ if self.tryton_configfile is not None: warnings.warn( DeprecationWarning( 'TRYTON_CONFIG configuration will be deprecated in future.' )) CONFIG.update_etc(self.tryton_configfile) CONFIG.set_timezone() register_classes() # Load and initialise pool Database = backend.get('Database') self._database = Database(self.database_name).connect() self._pool = Pool(self.database_name) self._pool.init() @property def pool(self): """ A proxy to the _pool """ return self._pool @property def database(self): """ Return connection to Database backend of tryton """ return self._database @root_transaction_if_required def add_ctx_processors_from_db(self): """ Adds template context processors registers with the model nereid.template.context_processor """ ctx_processor_obj = self.pool.get('nereid.template.context_processor') db_ctx_processors = ctx_processor_obj.get_processors() if None in db_ctx_processors: self.template_context_processors[None].extend( db_ctx_processors.pop(None)) self.template_context_processors.update(db_ctx_processors) def request_context(self, environ): return RequestContext(self, environ) @root_transaction_if_required def create_url_adapter(self, request): """Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. """ if request is not None: Website = Pool().get('nereid.website') website = Website.get_from_host(request.host) rv = website.get_url_adapter(self).bind_to_environ( request.environ, server_name=self.config['SERVER_NAME']) return rv def dispatch_request(self): """ Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. """ DatabaseOperationalError = backend.get('DatabaseOperationalError') req = _request_ctx_stack.top.request if req.routing_exception is not None: self.raise_routing_exception(req) rule = req.url_rule # if we provide automatic options for this URL and the # request came with the OPTIONS method, reply automatically if getattr(rule, 'provide_automatic_options', False) \ and req.method == 'OPTIONS': return self.make_default_options_response() Cache.clean(self.database_name) with Transaction().start(self.database_name, 0, readonly=True): Website = Pool().get('nereid.website') website = Website.get_from_host(req.host) user, company = website.application_user.id, website.company.id for count in range(int(CONFIG['retry']), -1, -1): with Transaction().start(self.database_name, user, context={'company': company}) as txn: try: transaction_start.send(self) rv = self._dispatch_request(req) txn.cursor.commit() except DatabaseOperationalError: # Strict transaction handling may cause this. # Rollback and Retry the whole transaction if within # max retries, or raise exception and quit. txn.cursor.rollback() if count: continue raise except Exception: # Rollback and raise any other exception txn.cursor.rollback() raise else: return rv finally: transaction_stop.send(self) def _dispatch_request(self, req): """ Implement the nereid specific _dispatch """ language = 'en_US' if req.nereid_website: # If this is a request specific to a website # then take the locale from the website language = req.nereid_locale.language.code with Transaction().set_context(language=language): # pop locale if specified in the view_args req.view_args.pop('locale', None) # otherwise dispatch to the handler for that endpoint if req.url_rule.endpoint in self.view_functions: meth = self.view_functions[req.url_rule.endpoint] else: model, method = req.url_rule.endpoint.rsplit('.', 1) meth = getattr(Pool().get(model), method) if not hasattr(meth, 'im_self') or meth.im_self: # static or class method result = meth(**req.view_args) else: # instance method, extract active_id from the url # arguments and pass the model instance as first argument model = Pool().get(req.url_rule.endpoint.rsplit('.', 1)[0]) i = model(req.view_args.pop('active_id')) result = meth(i, **req.view_args) if isinstance(result, LazyRenderer): result = (unicode(result), result.status, result.headers) return result def create_jinja_environment(self): """ Extend the default jinja environment that is created. Also the environment returned here should be specific to the current website. """ rv = super(Nereid, self).create_jinja_environment() # Add the custom extensions specific to nereid rv.add_extension('jinja2.ext.i18n') rv.add_extension('nereid.templating.FragmentCacheExtension') rv.filters.update(**NEREID_TEMPLATE_FILTERS) # add the locale sensitive url_for of nereid rv.globals.update(url_for=url_for) if self.cache: # Setup the bytecode cache rv.bytecode_cache = MemcachedBytecodeCache(self.cache) # Setup for fragmented caching rv.fragment_cache = self.cache rv.fragment_cache_prefix = self.cache_key_prefix + "-frag-" # Install the gettext callables from .contrib.locale import TrytonTranslations translations = TrytonTranslations(module=None, ttype='nereid_template') rv.install_gettext_callables(translations.gettext, translations.ngettext) return rv @locked_cached_property def jinja_loader(self): """ Creates the loader for the Jinja2 Environment """ return ModuleTemplateLoader( self.database_name, searchpath=self.template_folder, ) def select_jinja_autoescape(self, filename): """ Returns `True` if autoescaping should be active for the given template name. """ if filename is None: return False if filename.endswith(('.jinja', )): return True return super(Nereid, self).select_jinja_autoescape(filename) @property def guest_user(self): warnings.warn( DeprecationWarning( "guest_user as an attribute will be deprecated.\n" "Use request.nereid_website.guest_user.id instead")) from .globals import request return request.nereid_website.guest_user.id
class registration(FlaskForm): csrf_token=CsrfProtect(app) email=StringField('Email', [validators.DataRequired()]) password=PasswordField('Password', [validators.DataRequired(),validators.Length(min=8, max=13),validators.EqualTo('confirm', message='Passwords must match')]) confirm=PasswordField('Confirm password', [validators.Optional()]) submit=SubmitField("Register")
from urlparse import urljoin from flask import Flask, request, jsonify, abort, url_for, session from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.security import Security, SQLAlchemyUserDatastore from flask.ext.security.utils import encrypt_password as encrypt from flask.ext.mail import Mail from werkzeug.contrib.atom import AtomFeed import xmltodict import uuid import random import string from flask_wtf.csrf import CsrfProtect csrf = CsrfProtect() db = SQLAlchemy() # After defining `db`, import auth models due to # circular dependency. from mhn.auth.models import User, Role, ApiKey user_datastore = SQLAlchemyUserDatastore(db, User, Role) mhn = Flask(__name__) mhn.config.from_object('config') csrf.init_app(mhn) # Email app setup. mail = Mail() mail.init_app(mhn) # Registering app on db instance.
class Application(Flask): def __init__(self, app_config, import_name, static_path=None, static_url_path=None, static_folder='static', template_folder='templates', instance_path=None, instance_relative_config=False): from flask.ext.cache import Cache from ambry.library import Library from ambry.run import get_runconfig self._initialized = False self.csrf = CsrfProtect() self.login_manager = LoginManager() super(Application, self).__init__(import_name, static_path, static_url_path, static_folder, template_folder, instance_path, instance_relative_config) self.config.update(app_config) l = Library(get_runconfig(), read_only=True, echo=False) self.cache = Cache(config={ 'CACHE_TYPE': 'filesystem', 'CACHE_DIR': l.filesystem.cache('ui') }) self.cache.init_app(self) def __call__(self, environ, start_response): if not self._initialized: from ambry.library import Library from ambry.run import get_runconfig rc = get_runconfig() l = Library(rc, read_only=True, echo=False) secret_key = None if os.getenv('AMBRY_UI_SECRET'): app.logger.info("Using secret_key from env") secret_key = os.getenv('AMBRY_UI_SECRET') if not secret_key and l.ui_config.secret: app.logger.info("Using secret_key from library") secret_key = l.ui_config.secret if not secret_key: from uuid import uuid4 app.logger.warn( "SECRET_KEY was not set. Setting to a random value") secret_key = str( uuid4()) # Must be the same for all worker processes. if not self.config['WTF_CSRF_SECRET_KEY']: self.config['WTF_CSRF_SECRET_KEY'] = secret_key self.config['SECRET_KEY'] = secret_key title = os.getenv('AMBRY_UI_TITLE', "Ambry Data Library"), if l.ui_config.website_title: title = l.ui_config.website_title self.config['website_title'] = title self.secret_key = secret_key self.csrf.init_app(self) self.session_interface = ItsdangerousSessionInterface() self.login_manager.init_app(app) Bootstrap(app) self._initialized = True return super(Application, self).__call__(environ, start_response)
def configure_extensions(app): # Flask-WTF csrf = CsrfProtect() csrf.init_app(app)
from flask import Flask from flask_wtf.csrf import CsrfProtect csrf = CsrfProtect() application = Flask(__name__) csrf.init_app(application) application.config.from_object('config') from app.models import Task from app.controllers import * if __name__ == '__main__': application.run(port=8000)
def run_app(): CsrfProtect(app) port = int(os.environ.get('PORT', 8003)) app.run(host='0.0.0.0', port=port)
class Application(Flask): def __init__(self, app_config, import_name, static_path=None, static_url_path=None, static_folder='static', template_folder='templates', instance_path=None, instance_relative_config=False): from flask.ext.cache import Cache from ambry.library import Library from ambry.run import get_runconfig self._initialized = False self.csrf = CsrfProtect() self.login_manager = LoginManager() super(Application, self).__init__(import_name, static_path, static_url_path, static_folder, template_folder, instance_path, instance_relative_config) self.config.update(app_config) l = Library(get_runconfig(), read_only=True, echo=False) self.cache = Cache(config={'CACHE_TYPE': 'filesystem', 'CACHE_DIR': l.filesystem.cache('ui')}) self.cache.init_app(self) def __call__(self, environ, start_response): if not self._initialized: from ambry.library import Library from ambry.run import get_runconfig rc = get_runconfig() l = Library(rc, read_only=True, echo=False) secret_key = None if os.getenv('AMBRY_UI_SECRET'): app.logger.info("Using secret_key from env") secret_key = os.getenv('AMBRY_UI_SECRET') if not secret_key and l.ui_config.secret: app.logger.info("Using secret_key from library") secret_key = l.ui_config.secret if not secret_key: from uuid import uuid4 app.logger.warn("SECRET_KEY was not set. Setting to a random value") secret_key = str(uuid4()) # Must be the same for all worker processes. if not self.config['WTF_CSRF_SECRET_KEY']: self.config['WTF_CSRF_SECRET_KEY'] = secret_key self.config['SECRET_KEY'] = secret_key title = os.getenv('AMBRY_UI_TITLE', "Ambry Data Library"), if l.ui_config.website_title: title = l.ui_config.website_title self.config['website_title'] = title self.secret_key = secret_key self.csrf.init_app(self) self.session_interface = ItsdangerousSessionInterface() self.login_manager.init_app(app) Bootstrap(app) self._initialized = True return super(Application, self).__call__(environ, start_response)
import json, os, shutil from flask import Flask, request from flask import render_template from flask_wtf.csrf import CsrfProtect from connections import get_connection_to import traceback from PIL import Image dashapp = Flask(__name__) dashapp.secret_key = '6wfwef6AqwdwqdSDW676w6QDWD6748wd((FD' dashapp.config['SESSION_TYPE'] = 'filesystem' dashapp.config['WTF_CSRF_SECRET_KEY'] = 'asdaDawqdwd#$@%fewd#22342FWFQE' csrf = CsrfProtect() csrf.init_app(dashapp) @dashapp.route('/') def nsdash(): comment_count_query = "SELECT count(*) FROM comments" query_count_query = "SELECT count(*) FROM query" try: cursor, conn = get_connection_to(db_name='nsi') comment_count_obj = cursor.execute(comment_count_query) if comment_count_obj: ((comment_count, ), ) = cursor.fetchall() query_count_obj = cursor.execute(query_count_query) if query_count_obj: ((query_count, ), ) = cursor.fetchall() except Exception as e: pass
def create_app(): """Create Flask app.""" config = load_config() app = Flask(__name__) app.config.from_object(config) if not hasattr(app, 'production'): app.production = not app.debug and not app.testing # Proxy fix app.wsgi_app = ProxyFix(app.wsgi_app) # CSRF protect CsrfProtect(app) if app.debug or app.testing: DebugToolbarExtension(app) # Serve static files app.wsgi_app = SharedDataMiddleware( app.wsgi_app, { '/pages': os.path.join(app.config.get('PROJECT_PATH'), 'application/pages') }) else: # Log errors to stderr in production mode app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.ERROR) # Enable Sentry if app.config.get('SENTRY_DSN'): from .utils.sentry import sentry sentry.init_app(app, dsn=app.config.get('SENTRY_DSN'), logging=True, level=logging.ERROR) # Serve static files app.wsgi_app = SharedDataMiddleware( app.wsgi_app, { '/static': os.path.join(app.config.get('PROJECT_PATH'), 'output/static'), '/pkg': os.path.join(app.config.get('PROJECT_PATH'), 'output/pkg'), '/pages': os.path.join(app.config.get('PROJECT_PATH'), 'output/pages') }) # Register components register_db(app) register_routes(app) register_admin(app) register_security(app) register_babel(app) register_api(app) register_jinja(app) register_error_handle(app) register_hooks(app) register_socketio(app) register_redis(app) register_context_processor(app) register_before_first_request(app) return app
from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.cache import Cache from flask.ext.script import Manager from flask.ext.migrate import Migrate from flask_wtf.csrf import CsrfProtect from flask.ext.themes import setup_themes from flask.ext.mail import Mail from config import LOG_DIR blog = Flask(__name__) blog.config.from_object('config') csrf = CsrfProtect() csrf.init_app(blog) db = SQLAlchemy(blog) lm = LoginManager() lm.init_app(blog) lm.login_view = 'login' lm.login_message = u"请先登录" cache = Cache(blog) '''控制台''' manager = Manager(blog) '''数据库迁移''' migrate = Migrate(blog, db)
def test_deprecated_csrfprotect(recwarn): CsrfProtect() w = recwarn.pop(FlaskWTFDeprecationWarning) assert 'CSRFProtect' in str(w.message)
def register_form(app): csrf = CsrfProtect() csrf.init_app(app)
from flask import Flask, flash, redirect, url_for from flask_sqlalchemy import SQLAlchemy from flask_wtf.csrf import CsrfProtect from flask.ext.login import LoginManager, current_user from flask.ext.heroku import Heroku from flask.ext.mail import Mail from flask.ext.principal import Identity, Principal, RoleNeed, UserNeed, Permission, identity_changed, identity_loaded # CONFIGURATION app = Flask(__name__) # application object CsrfProtect(app) # enables CSRF protection for all view handlers lm = LoginManager() lm.init_app(app) app.config.from_object("config.DevelopmentConfig") # read and use config file heroku = Heroku(app) db = SQLAlchemy(app) # sqlalchemy database object # flask-principal normal_role = RoleNeed('normal') normal_permission = Permission(normal_role) admin_role = RoleNeed('admin') admin_permission = Permission(admin_role) Principal(app) # mail stuff mail = Mail(app) from project.users.views import users_blueprint from project.analysis.views import analysis_blueprint from project.upload.views import upload_blueprint from project.main.views import main_blueprint
def create_app(config): """ Creates a Flask application based on the provided configuration object. Args: config: The configuration object. """ app = Flask(__name__) app.config.from_object(config) from remedyblueprint import remedy, url_for_other_page, server_error app.register_blueprint(remedy) # Register a custom error handler for production scenarios if app.debug is not True: app.error_handler_spec[None][500] = server_error app.error_handler_spec[None][Exception] = server_error from admin import admin admin.init_app(app) from auth.user_auth import auth, login_manager app.register_blueprint(auth) login_manager.init_app(app) # searching configurations app.jinja_env.trim_blocks = True # Register the paging helper method with Jinja2 app.jinja_env.globals['url_for_other_page'] = url_for_other_page app.jinja_env.globals['logged_in'] = lambda: current_user.is_authenticated db.init_app(app) from flask_wtf.csrf import CsrfProtect CsrfProtect(app) Migrate(app, db, directory=app.config['MIGRATIONS_DIR']) manager = Manager(app) manager.add_command('db', MigrateCommand) # Enable logging for production environments if app.debug is not True: logging.basicConfig(stream=sys.stderr) file_handler = RotatingFileHandler('python.log', maxBytes=1024 * 1024 * 100, backupCount=20) file_handler.setLevel(logging.WARNING) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) app.logger.addHandler(file_handler) # Configure proxies for WSGI if app.wsgi_app is not None: from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) # turning API off for now # from api_manager import init_api_manager # api_manager = init_api_manager(app, db) # map(lambda m: api_manager.create_api(m), models) return app, manager
from flask_bootstrap import Bootstrap import config import models import humanize from datetime import date, timedelta import markdown from ressources import connect_db, auth_required, get_token from users import users_api from task import task_api import forms app = Flask(__name__) app.secret_key = config.SECRET csfr = CsrfProtect(app) Bootstrap(app) @app.before_request def open_db(): g.db = connect_db() g.cursor = g.db.cursor() @app.after_request def call_after_request_callbacks(response): for callback in getattr(g, 'after_request_callbacks', ()): callback(response) return response
import sys, os from flask import send_from_directory from flask import abort import json import re reload(sys) sys.setdefaultencoding('utf8') APP_ROOT = os.path.dirname(os.path.abspath(__file__)) UPLOAD_FOLDER = os.path.join(APP_ROOT, 'static/favicons') app = Flask(__name__) app.secret_key = '\x8d\xf9\x8d>\xf9\xd0S\xf2\x7f\xfflX\r\xaa\xd2\xa7\x8d\xcek\x04\x9e`\xfbmk\x88*\xb5\xfb\xf0\x06\xa5T\x87\xbc\xfd\x90\x96\xe5-\x07\x87Hh\xf5\x1f\xe1\xfe\xae\xf0\x19\xc4\xfa\x7f\xd5\xf9\xf53\x07e\xc0Z\x99_\xe7\xdf\x1d\x88\x16\xdb\x91\xcd+\xf5\x94\x91}\x16\xd4\xfb?Lp\xc5\x99YXUZ\x03o\xd5\xf5\xa8\x82\tPWGF\x86\x91\xcc\xeb\x97T\xfc\x90\xdf,:5n\xb7\x94\xa0$r\x82\x80\xa4\x17n7\xbd3\xc6 L]' # csrf防护 csrf = CsrfProtect() csrf.init_app(app) # mysql数据库配置 app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'mysql://*****:*****@localhost:3306/sscc' # app.config['SQLALCHEMY_DATABASE_URI']='mysql://*****:*****@10.12.0.5:3306/sscc' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER db = SQLAlchemy(app, use_native_unicode='utf-8') #实例化 # set the location for the whoosh index app.config['WHOOSH_BASE'] = '/whoosh-base' # link数据模型
# import json, os, shutil from flask import Flask, request, session, url_for from flask import render_template, redirect from flask_wtf.csrf import CsrfProtect from connections import get_connection_to import json # import traceback # from PIL import Image from decorators import login_required shadowdashapp = Flask(__name__) shadowdashapp.secret_key = '6wfwef6AqwdwqdSDW67waedccscaQDWD6748wdFD' shadowdashapp.config['SESSION_TYPE'] = 'filesystem' shadowdashapp.config[ 'WTF_CSRF_SECRET_KEY'] = 'asdaC34VERV6843CsC#$@d#$@%fewd#22342FWFQE' csrf = CsrfProtect() csrf.init_app(shadowdashapp) @shadowdashapp.route('/') @login_required def shadowdash(): comment_count_query = "SELECT count(*) FROM user" try: cursor, conn = get_connection_to(db_name='sf') comment_count_obj = cursor.execute(comment_count_query) if comment_count_obj: ((signup_user_count, ), ) = cursor.fetchall() except Exception as e: pass
from flask_wtf import Form from flask_wtf.csrf import CsrfProtect from wtforms import (IntegerField, PasswordField, SelectField, SelectMultipleField, TextAreaField, TextField, ValidationError) from wtforms.validators import DataRequired, Email, Length from _15thnight.models import Category, Service, User csrf_protect = CsrfProtect() USER_ROLES = [('provider', 'PROVIDER'), ('advocate', 'ADVOCATE'), ('admin', 'ADMIN')] GENDERS = [('male', 'Male'), ('female', 'Female'), ('unspecified', 'Unspecified')] user_name_field = TextField('Name', validators=[DataRequired(), Length(max=255)]) user_organization_field = TextField( 'Organization', validators=[DataRequired(), Length(max=255)]) user_email_feild = TextField( 'Email Address', validators=[DataRequired(), Email(message=None), Length(min=6, max=255)]) user_phone_number_field = TextField( 'Phone Number', validators=[DataRequired(), Length(min=10)])
from flask import Flask, render_template, session, flash, request, abort, redirect, url_for, Markup, jsonify from werkzeug.exceptions import BadRequest from config import * from forms import LoginForm, RegisterForm, RegisterLockForm from base64 import b64encode from functools import wraps import json app = Flask(__name__) app.secret_key = SECRET_KEY app.debug = True from flask_wtf.csrf import CsrfProtect csrf = CsrfProtect(app) ################################# # ========= Logging =========== # ################################# import logging import sys app.logger.addHandler(logging.StreamHandler(sys.stdout)) app.logger.setLevel(logging.DEBUG) ################################# # ========= Bootstrap ========= # #################################
from flask.ext.uploads import UploadSet, IMAGES from celery import Celery from flask_mail import Mail from flask_s3 import FlaskS3 from flask_wtf.csrf import CsrfProtect from slugify import slugify from babel import Locale, UnknownLocaleError import yaml import locale s3 = FlaskS3() mail = Mail() alchemydumps = AlchemyDumps() security = Security() csrf = CsrfProtect() babel = Babel() bcrypt = Bcrypt() celery = Celery( __name__, broker='redis://redis', #TODO this should be from config include=['app.tasks'] ) assets = Environment() main_css = Bundle('css/vendor/bootstrap.css', output='gen/main_packed.%(version)s.css') assets.register('main_css', main_css)
from flask_wtf.csrf import CsrfProtect from flask import Flask import config from app.models import db from app.views.admin import admin from app.views.user import user app = Flask(__name__) app.config.from_object(config) mycsrf = CsrfProtect() mycsrf.init_app(app) app.register_blueprint(admin, url_prefix='/admin') app.register_blueprint(user, url_prefix='/user') @app.route('/') def homep(): return 'hello' if __name__ == '__main__': app.run()
def register_form(app): from flask_wtf.csrf import CsrfProtect csrf = CsrfProtect() csrf.init_app(app)
def create_app(config=None): """ config should be a python file """ from pathlib import Path from flask import (Flask, current_app, g, session, url_for, render_template) from flask_sqlalchemy import SQLAlchemy from flask_security import (Security, SQLAlchemyUserDatastore) from flask_wtf.csrf import CsrfProtect from flask_assets import (Environment, Bundle) from .app_setup import (init_db, setup_dirs) from .core import (db, load_blueprints, setup_logger) from .lib.template_filters import ( fmt_datetime, none_as_str, next_page_url, prev_page_url, get_page_url, get_images) from .models.user import (User, Role, user_datastore) from .Admin import (index, series, images, texts, contact) from .Public import (index, contact, texts) from .Security import user app = Flask(__name__.split('.')[0], instance_relative_config=True) app.config.from_object('config') app.config.from_pyfile('config.py') if config is not None: app.config.from_pyfile(config) setup_logger(app) app.logger.info('Started with config from: {}'.format(config)) else: setup_logger(app) app.logger.info('Started App') # Flask.sqlalchemy db.init_app(app) load_blueprints(app) # make sure db tables and required directories exist before_first_request_funcs = [setup_dirs(app), init_db(app)] #Security csrf = CsrfProtect() csrf.init_app(app) security = Security() security.init_app(app, user_datastore, register_blueprint=False) # Assets assets = Environment(app=app) assets.from_yaml('assets.yml') # template filters app.add_template_filter(fmt_datetime) app.add_template_filter(none_as_str) app.add_template_filter(next_page_url) app.add_template_filter(prev_page_url) app.add_template_filter(get_page_url) app.add_template_filter(get_images) return app
class Nereid(Flask): """ ... Unlike typical web frameworks and their APIs, nereid depends more on configuration and not direct python modules written along the APIs Most of the functional code will remain on the modules installed on Tryton, and the database configurations. ... """ #: The class that is used for request objects. See #: :class:`~nereid.wrappers.Request` #: for more information. request_class = Request #: The class that is used for response objects. See #: :class:`~nereid.wrappers.Response` for more information. response_class = Response #: the session interface to use. By default an instance of #: :class:`~nereid.session.NereidSessionInterface` is used here. session_interface = NereidSessionInterface() #: An internal attribute to hold the Tryton model pool to avoid being #: initialised at every request as it is quite expensive to do so. #: To access the pool from modules, use the :meth:`pool` _pool = None #: The attribute holds a connection to the database backend. _database = None #: Configuration file for Tryton. The path to the configuration file #: can be specified and will be loaded when the application is #: initialised tryton_configfile = ConfigAttribute('TRYTON_CONFIG') #: The location where the translations of the template are stored translations_path = ConfigAttribute('TRANSLATIONS_PATH') #: The name of the database to connect to on initialisation database_name = ConfigAttribute('DATABASE_NAME') #: The default timeout to use if the timeout is not explicitly #: specified in the set or set many argument cache_default_timeout = ConfigAttribute('CACHE_DEFAULT_TIMEOUT') #: the maximum number of items the cache stores before it starts #: deleting some items. #: Applies for: SimpleCache, FileSystemCache cache_threshold = ConfigAttribute('CACHE_THRESHOLD') #: a prefix that is added before all keys. This makes it possible #: to use the same memcached server for different applications. #: Applies for: MecachedCache, GAEMemcachedCache #: If key_prefix is none the value of site is used as key cache_key_prefix = ConfigAttribute('CACHE_KEY_PREFIX') #: a list or tuple of server addresses or alternatively a #: `memcache.Client` or a compatible client. cache_memcached_servers = ConfigAttribute('CACHE_MEMCACHED_SERVERS') #: The directory where cache files are stored if FileSystemCache is used cache_dir = ConfigAttribute('CACHE_DIR') #: The type of cache to use. The type must be a full specification of #: the module so that an import can be made. Examples for werkzeug #: backends are given below #: #: NullCache - werkzeug.contrib.cache.NullCache (default) #: SimpleCache - werkzeug.contrib.cache.SimpleCache #: MemcachedCache - werkzeug.contrib.cache.MemcachedCache #: GAEMemcachedCache - werkzeug.contrib.cache.GAEMemcachedCache #: FileSystemCache - werkzeug.contrib.cache.FileSystemCache cache_type = ConfigAttribute('CACHE_TYPE') #: If a custom cache backend unknown to Nereid is used, then #: the arguments that are needed for the initialisation #: of the cache could be passed here as a `dict` cache_init_kwargs = ConfigAttribute('CACHE_INIT_KWARGS') #: boolean attribute to indicate if the initialisation of backend #: connection and other nereid support features are loaded. The #: application can work only after the initialisation is done. #: It is not advisable to set this manually, instead call the #: :meth:`initialise` initialised = False #: Prefix the name of the website to the template name sutomatically #: This feature would be deprecated in future in lieu of writing #: Jinja2 Loaders which could offer this behavior. This is set to False #: by default. For backward compatibility of loading templates from #: a template folder which has website names as subfolders, set this #: to True #: #: .. versionadded:: 2.8.0.4 template_prefix_website_name = ConfigAttribute( 'TEMPLATE_PREFIX_WEBSITE_NAME' ) #: Time in seconds for which the token is valid. token_validity_duration = ConfigAttribute( 'TOKEN_VALIDITY_DURATION' ) def __init__(self, **config): """ The import_name is forced into `Nereid` """ super(Nereid, self).__init__('nereid', **config) # Update the defaults for config attributes introduced by nereid self.config.update({ 'TRYTON_CONFIG': None, 'TEMPLATE_PREFIX_WEBSITE_NAME': True, 'TOKEN_VALIDITY_DURATION': 60 * 60, 'CACHE_TYPE': 'werkzeug.contrib.cache.NullCache', 'CACHE_DEFAULT_TIMEOUT': 300, 'CACHE_THRESHOLD': 500, 'CACHE_INIT_KWARGS': {}, 'CACHE_KEY_PREFIX': '', }) def initialise(self): """ The application needs initialisation to load the database connection etc. In previous versions this was done with the initialisation of the class in the __init__ method. This is now separated into this function. """ #: Check if the secret key is defined, if not raise an #: exception since it is required assert self.secret_key, 'Secret Key is not defined in config' #: Load the cache self.load_cache() #: Initialise the CSRF handling self.csrf_protection = CsrfProtect() self.csrf_protection.init_app(self) self.view_functions['static'] = self.send_static_file # Backend initialisation self.load_backend() #: Initialise the login handler login_manager = LoginManager() login_manager.user_loader(self._pool.get('nereid.user').load_user) login_manager.header_loader( self._pool.get('nereid.user').load_user_from_header ) login_manager.token_loader( self._pool.get('nereid.user').load_user_from_token ) login_manager.unauthorized_handler( self._pool.get('nereid.user').unauthorized_handler ) login_manager.login_view = "nereid.website.login" login_manager.anonymous_user = self._pool.get('nereid.user.anonymous') login_manager.init_app(self) self.login_manager = login_manager # Monkey patch the url_for method from flask-login to use # the nereid specific url_for flask.ext.login.url_for = url_for self.template_context_processors[None].append( self.get_context_processors() ) # Add the additional template context processors self.template_context_processors[None].append( nereid_default_template_ctx_processor ) # Finally set the initialised attribute self.initialised = True def get_urls(self): """ Return the URL rules for routes formed by decorating methods with the :func:`~nereid.helpers.route` decorator. This method goes through all the models and their methods in the pool of the loaded database and looks for the `_url_rules` attribute in them. If there are URLs defined, it is added to the url map. """ rules = [] models = Pool._pool[self.database_name]['model'] for model_name, model in models.iteritems(): for f_name, f in inspect.getmembers( model, predicate=inspect.ismethod): if not hasattr(f, '_url_rules'): continue for rule in f._url_rules: rules.append( self.url_rule_class( rule[0], endpoint='.'.join([model_name, f_name]), **rule[1] ) ) return rules @root_transaction_if_required def get_context_processors(self): """ Returns the method object which wraps context processor methods formed by decorating methods with the :func:`~nereid.helpers.context_processor` decorator. This method goes through all the models and their methods in the pool of the loaded database and looks for the `_context_processor` attribute in them and adds to context_processor dict. """ context_processors = {} models = Pool._pool[self.database_name]['model'] for model_name, model in models.iteritems(): for f_name, f in inspect.getmembers( model, predicate=inspect.ismethod): if hasattr(f, '_context_processor'): ctx_proc_as_func = getattr(Pool().get(model_name), f_name) context_processors[ctx_proc_as_func.func_name] = \ ctx_proc_as_func def get_ctx(): """Returns dictionary having method name in keys and method object in values. """ return context_processors return get_ctx def load_cache(self): """ Load the cache and assign the Cache interface to """ BackendClass = import_string(self.cache_type) if self.cache_type == 'werkzeug.contrib.cache.NullCache': self.cache = BackendClass(self.cache_default_timeout) elif self.cache_type == 'werkzeug.contrib.cache.SimpleCache': self.cache = BackendClass( self.cache_threshold, self.cache_default_timeout) elif self.cache_type == 'werkzeug.contrib.cache.MemcachedCache': self.cache = BackendClass( self.cache_memcached_servers, self.cache_default_timeout, self.cache_key_prefix) elif self.cache_type == 'werkzeug.contrib.cache.GAEMemcachedCache': self.cache = BackendClass( self.cache_default_timeout, self.cache_key_prefix) elif self.cache_type == 'werkzeug.contrib.cache.FileSystemCache': self.cache = BackendClass( self.cache_dir, self.cache_threshold, self.cache_default_timeout) else: self.cache = BackendClass(**self.cache_init_kwargs) def load_backend(self): """ This method loads the configuration file if specified and also connects to the backend, initialising the pool on the go """ if self.tryton_configfile is not None: warnings.warn(DeprecationWarning( 'TRYTON_CONFIG configuration will be deprecated in future.' )) CONFIG.update_etc(self.tryton_configfile) register_classes() # Load and initialise pool Database = backend.get('Database') self._database = Database(self.database_name).connect() self._pool = Pool(self.database_name) self._pool.init() @property def pool(self): """ A proxy to the _pool """ return self._pool @property def database(self): """ Return connection to Database backend of tryton """ return self._database def request_context(self, environ): return RequestContext(self, environ) @root_transaction_if_required def create_url_adapter(self, request): """Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. """ if request is not None: Website = Pool().get('nereid.website') website = Website.get_from_host(request.host) rv = website.get_url_adapter(self).bind_to_environ( request.environ, server_name=self.config['SERVER_NAME'] ) return rv def dispatch_request(self): """ Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. """ DatabaseOperationalError = backend.get('DatabaseOperationalError') req = _request_ctx_stack.top.request if req.routing_exception is not None: self.raise_routing_exception(req) rule = req.url_rule # if we provide automatic options for this URL and the # request came with the OPTIONS method, reply automatically if getattr(rule, 'provide_automatic_options', False) \ and req.method == 'OPTIONS': return self.make_default_options_response() Cache.clean(self.database_name) with Transaction().start(self.database_name, 0, readonly=True): Website = Pool().get('nereid.website') website = Website.get_from_host(req.host) user, company = website.application_user.id, website.company.id for count in range(int(CONFIG['retry']), -1, -1): with Transaction().start( self.database_name, user, context={'company': company}) as txn: try: transaction_start.send(self) rv = self._dispatch_request(req) txn.cursor.commit() except DatabaseOperationalError: # Strict transaction handling may cause this. # Rollback and Retry the whole transaction if within # max retries, or raise exception and quit. txn.cursor.rollback() if count: continue raise except Exception: # Rollback and raise any other exception txn.cursor.rollback() raise else: return rv finally: transaction_stop.send(self) def _dispatch_request(self, req): """ Implement the nereid specific _dispatch """ language = 'en_US' if req.nereid_website: # If this is a request specific to a website # then take the locale from the website language = req.nereid_locale.language.code with Transaction().set_context(language=language): # pop locale if specified in the view_args req.view_args.pop('locale', None) # otherwise dispatch to the handler for that endpoint if req.url_rule.endpoint in self.view_functions: meth = self.view_functions[req.url_rule.endpoint] else: model, method = req.url_rule.endpoint.rsplit('.', 1) meth = getattr(Pool().get(model), method) if not hasattr(meth, 'im_self') or meth.im_self: # static or class method result = meth(**req.view_args) else: # instance method, extract active_id from the url # arguments and pass the model instance as first argument model = Pool().get(req.url_rule.endpoint.rsplit('.', 1)[0]) i = model(req.view_args.pop('active_id')) result = meth(i, **req.view_args) if isinstance(result, LazyRenderer): result = ( unicode(result), result.status, result.headers ) return result def create_jinja_environment(self): """ Extend the default jinja environment that is created. Also the environment returned here should be specific to the current website. """ rv = super(Nereid, self).create_jinja_environment() # Add the custom extensions specific to nereid rv.add_extension('jinja2.ext.i18n') rv.add_extension('nereid.templating.FragmentCacheExtension') rv.filters.update(**NEREID_TEMPLATE_FILTERS) # add the locale sensitive url_for of nereid rv.globals.update(url_for=url_for) if self.cache: # Setup the bytecode cache rv.bytecode_cache = MemcachedBytecodeCache(self.cache) # Setup for fragmented caching rv.fragment_cache = self.cache rv.fragment_cache_prefix = self.cache_key_prefix + "-frag-" # Install the gettext callables from .contrib.locale import TrytonTranslations translations = TrytonTranslations(module=None, ttype='nereid_template') rv.install_gettext_callables( translations.gettext, translations.ngettext ) return rv @locked_cached_property def jinja_loader(self): """ Creates the loader for the Jinja2 Environment """ return ModuleTemplateLoader( self.database_name, searchpath=self.template_folder, ) def select_jinja_autoescape(self, filename): """ Returns `True` if autoescaping should be active for the given template name. """ if filename is None: return False if filename.endswith(('.jinja',)): return True return super(Nereid, self).select_jinja_autoescape(filename)
import auth.models from db import user app = Flask(__name__) login_manager = LoginManager() app.config.from_object('config') login_manager.init_app(app) login_manager.login_view = 'login' mail = Mail(app) app.debug = True app.use_reloader = True crsf = CsrfProtect() crsf.init_app(app) # visible web pages @app.route("/forgotpassword", methods=["GET", "POST"]) def forgotpassword(): form = auth.forms.ForgotPasswordForm() if request.method == "GET": return render_template("forgotpassword.html", form=form) if not form.validate(): return render_template("forgotpassword.html", form=form) else: password = form.newpassword msg = Message("New Password", sender=config.MAIL_USERNAME,
import app.errors # import app.logs _basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config.from_object('config.DebugConfiguration') @app.context_processor def provide_constants(): return {"constants": {"TUTORIAL_PART": 2}} db.init_app(app) csrf_protect = CsrfProtect(app) flask_api = Api(app, decorators=[csrf_protect.exempt]) app.register_blueprint(sensors) app.register_blueprint(users) @app.errorhandler(404) def page_not_found(e): return render_template('errors/404.html'), 404 @app.errorhandler(400) def key_error(e): app.logger.warning('Invalid request resulted in KeyError', exc_info=e) return render_template('errors/400.html'), 400
def create_app(**config_overrides): """Short summary. Parameters ---------- **config_overrides : type Description of parameter `**config_overrides`. Returns ------- type Description of returned object. """ app = Flask(__name__) # Load config app.config.from_pyfile('settings.py') # apply overrides for tests app.config.update(config_overrides) # Proxy fix app.wsgi_app = ProxyFix(app.wsgi_app) # CSRF protect CsrfProtect(app) if app.debug or app.testing: DebugToolbarExtension(app) # Serve static files # app.wsgi_app = SharedDataMiddleware(app.wsgi_app, { # '/pages': os.path.join(app.config.get('PROJECT_PATH'), \ # 'application/pages') # }) else: # Log errors to stderr in production mode app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.ERROR) from raven.contrib.flask import Sentry sentry = Sentry() # Enable Sentry if app.config.get('SENTRY_DSN'): sentry.init_app(app, dsn=app.config.get('SENTRY_DSN')) # Serve static files # app.wsgi_app = SharedDataMiddleware(app.wsgi_app, { # '/static': os.path.join(app.config.get('PROJECT_PATH'), \ # 'output/static'), # '/pkg': os.path.join(app.config.get('PROJECT_PATH'), \ # 'output/pkg'), # '/pages': os.path.join(app.config.get('PROJECT_PATH'), \ # 'output/pages') # }) # Register components register_routes(app) register_db(app) register_error_handle(app) register_hooks(app) return app
from flask import Flask from flask_babel import Babel from flask_mail import Mail from flask_security import SQLAlchemyUserDatastore from flask_security import Security from flask_sqlalchemy import SQLAlchemy from flask_wtf.csrf import CsrfProtect app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) csrfprotect = CsrfProtect(app) babel = Babel(app) mail = Mail(app) # Setup Flask-Security from nipy.admin.forms import ExtendedRegisterForm from nipy.admin.models import Role from nipy.admin.models import User user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore, register_form=ExtendedRegisterForm, confirm_register_form=ExtendedRegisterForm) from nipy.admin.views import admin from nipy.blog.views import blog app.register_blueprint(admin) app.register_blueprint(blog)
def setup_csrf(): # Initiate Flask-WTForms CSRF protection csrf = CsrfProtect() csrf.init_app(app) return None
def initialize_app(application, config, profile=False): # 读取配置 application.config.from_object(config) # 注册蓝图 from app_spider.views.input_data.input_api import input_data_api_view from app_spider.views.login.login_view import login_view from app_spider.views.data.data_view import data_view from app_spider.views.input_mongodb.input_api import input_mongodb_api_view application.register_blueprint(input_data_api_view) application.register_blueprint(login_view) application.register_blueprint(data_view) application.register_blueprint(input_mongodb_api_view) # restful api 不跨域保护 csrf = CsrfProtect() csrf.init_app(application) csrf.exempt(input_data_api_view) csrf.exempt(login_view) csrf.exempt(data_view) csrf.exempt(input_mongodb_api_view)
# Define the WSGI application object app = Flask(__name__) # Configurations app.config.from_object('config') # Define the assets environment assets = Environment(app) assets.debug = app.config["DEBUG"] # Setup the secret key app.secret_key = app.config["SECRET_KEY"] # add CSRF protection (http://flask-wtf.readthedocs.org/en/latest/csrf.html) app.WTF_CSRF_TIME_LIMIT = 86400 csrf_protection = CsrfProtect(app) # import handlers import db import application.handlers.admin import application.handlers.public import application.handlers.welcome import application.handlers.dashboard import application.handlers.directory # Define our core bundles js_core = Bundle('js/core/Core.register.js', 'js/core/toolbelt.js', 'js/core/Core.modal.js', 'js/core/Core.select.js', 'js/core/Core.notifications.js', 'js/elements/loading-buttons.js', filters='rjsmin', output='gen/core.js') assets.register('js_core', js_core)
class loginform(FlaskForm): csrf_token=CsrfProtect(app) email=StringField('Email',[validators.DataRequired()]) password=PasswordField('Password', [validators.DataRequired()]) submit=SubmitField('Login')
class Environment(object): _instance = None @classmethod def instance(cls, config=None, test=False, test_db_uri=None): if cls._instance is None: cls._instance = cls(config, test, test_db_uri) return cls._instance def __init__(self, config, test, test_db_uri): if self.__class__._instance is not None: raise EnvironmentUninitializedError() self.__s3_conn = None self.__fixtures = None self.__db = SQLAlchemy() for path in CONFIG_PATH_LOCATIONS: sys.path.append(path) if config is None: # None will be passed by manage.py. # A default param value will get overwritten, so this is implemented here. config = 'splice.default_settings.DefaultConfig' if not test: # load config from environment if it exists config = os.environ.get('SPLICE_SETTINGS', config) config_obj = load_config_obj(config) if test: config_obj.ENVIRONMENT = 'test' config_obj.SQLALCHEMY_DATABASE_URI = test_db_uri config_obj.SQLALCHEMY_BINDS = {'stats': test_db_uri} config_obj.SQLALCHEMY_POOL_SIZE = None config_obj.SQLALCHEMY_POOL_TIMEOUT = None self.log = Mock() self.__s3_conn = Mock() else: self.__loggers = self.__setup_loggers(config_obj) self.config = config_obj app = Flask('splice') app.config.from_object(config) if app.config['ENVIRONMENT'] not in app.config['STATIC_ENABLED_ENVS']: app.config['STATIC_FOLDER'] = None self.__application = app if not test: # pragma: no cover self.csrf = CsrfProtect() self.csrf.init_app(app) # A hack to keep the sqlalchemy binds state. Flask-SQLAlchemy strips it out sqlalchemy_binds = app.config.get('SQLALCHEMY_BINDS') self.db.init_app(self.__application) app.config.SQLALCHEMY_BINDS = sqlalchemy_binds Migrate(self.__application, self.db) @property def is_debug(self): return self.config.DEBUG @property def is_test(self): return self.config.ENVIRONMENT == "test" @property def is_development(self): return self.config.ENVIRONMENT == "dev" @property def is_production(self): return self.config.ENVIRONMENT == "prod" @property def application(self): return self.__application @property def db(self): return self.__db @property def s3(self): if not self.__s3_conn: if self.config.AWS: self.__s3_conn = boto.connect_s3(self.config.AWS["key"], self.config.AWS["secret_key"]) else: self.__s3_conn = boto.connect_s3() return self.__s3_conn @property def fixtures(self): if not self.__fixtures: self._load_fixtures() return self.__fixtures def _load_locales(self): with open(self.config.LOCALE_FIXTURE_PATH, 'r') as infile: data = [line.strip() for line in infile] data.extend(["en-US", "ERROR"]) return data def _load_countries(self): import csv with open(self.config.COUNTRY_FIXTURE_PATH, 'rb') as f: reader = csv.reader(f) data = [line for line in reader] data.append(("ERROR", "ERROR")) data.append(("STAR", "All Countries")) return data def _load_fixtures(self): locales = set(self._load_locales()) countries = {} for iso_code, name in self._load_countries(): countries[iso_code] = name self.__fixtures = { "locales": locales, "countries": countries, } def __setup_loggers(self, config): # pragma: no cover """ Setup and return loggers """ loggers = {} for name, settings in config.LOG_HANDLERS.iteritems(): internal_name = "splice-{0}".format(name) handler = settings['handler'](**settings['params']) if 'format' in settings: handler.setFormatter(logging.Formatter(settings['format'])) logger = logging.getLogger(internal_name) logger.setLevel(settings['level']) logger.addHandler(handler) loggers[internal_name] = logger return loggers def log(self, msg, name='console', **kwargs): # pragma: no cover """ Log messages via defined outputs """ level = kwargs.pop('level', logging.INFO) internal_name = "splice-{0}".format(name) loggers = {self.__loggers.get(internal_name)} if self.is_debug: # include the console logger in development mode loggers.add(self.__loggers['splice-console']) for logger in loggers: if logging.handlers.SysLogHandler in logger.handlers: # in syslog, message starts after first colon logger_msg = ":{0}".format(msg) else: logger_msg = msg logger.log(level, logger_msg, **kwargs)
import locale import os import sys import time from collections import OrderedDict from typing import Dict, Optional import psycopg2.extras from flask import Flask, g, request, session from flask_babel import Babel, lazy_gettext as _ from flask_wtf import Form from flask_wtf.csrf import CsrfProtect from wtforms import StringField, SubmitField app = Flask(__name__, instance_relative_config=True) # type: Flask csrf = CsrfProtect(app) # Make sure all forms are CSRF protected # Use the test database if running tests instance_name = 'production' if 'test_runner.py' not in sys.argv[ 0] else 'testing' app.config.from_object('config.default') # Load config/INSTANCE_NAME.py app.config.from_pyfile(instance_name + '.py') # Load instance/INSTANCE_NAME.py if os.name == "posix": # For other operating systems e.g. Windows, we would need adaptions here locale.setlocale(locale.LC_ALL, 'en_US.utf-8') # pragma: no cover babel = Babel(app) debug_model = OrderedDict() # type: OrderedDict class GlobalSearchForm(Form):
# coding=utf-8 """""" from __future__ import absolute_import, division, print_function, \ unicode_literals from flask import current_app, flash, request from flask.signals import request_started from flask_wtf.csrf import CsrfProtect from markupsafe import Markup from werkzeug.exceptions import BadRequest from abilian.core.util import unwrap from abilian.i18n import _l wtf_csrf = CsrfProtect() class AbilianCsrf(object): """CSRF error handler, that allows supporting views to gracefully report error instead of a plain 400 error. views supporting this must """ #: for views that gracefully support csrf errors, this message can be #: displayed to user. It can be changed if you have a better one for your #: users. csrf_failed_message = _l( "Security informations are missing or expired. " "This may happen if you have opened the form for a long time. " "<br /><br />"
params = [1 - float(random.randint(1, 2)) / 100, 0, 0, 0, 1 - float(random.randint(1, 10)) / 100, float(random.randint(1, 2)) / 500, 0.001, float(random.randint(1, 2)) / 500 ] img = img.transform(size, Image.PERSPECTIVE, params) # 创建扭曲 img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强(阈值更大) return img,strs csrf = CsrfProtect() app = Flask(__name__) csrf.init_app(app) app.secret_key = os.urandom(30) class RegisterForm(Form): """注册表单""" # SECRET_KEY = os.urandom(30) username = StringField(u'昵称', validators=[DataRequired(message=u'用户名必填')]) email = StringField(u'邮箱', validators=[DataRequired(), Email(message=u'邮箱格式不正确')]) password = PasswordField(u'密码', validators=[DataRequired(), Length(6, 12, message=u'密码长度在6到12为')]) password1 = PasswordField(u'确认密码', validators=[DataRequired(), Length(6, 12, message=u'密码长度在6到12为'), EqualTo('password', message=u'密码必须一致')]) verification_code = StringField(u'验证码', validators=[DataRequired(), Length(4, 4, message=u'填写4位验证码')]) submit = SubmitField(u'注册') class User(object):