def register_extensions(app): """Register Flask extensions.""" db.app = app db.init_app(app) csrf = CSRFProtect() csrf.init_app(app) cache.init_app(app) login_manager.init_app(app) celery_app.init_app(app)
def create_app(config='config.Production', instance=True): app = Flask(__name__, instance_relative_config=instance) app.config.from_object(config) app.config.from_pyfile('config.py', silent=True) app.config.from_envvar('FLASKR_SETTINGS', silent=True) app.debug = app.config['DEBUG'] csrf = CSRFProtect() csrf.init_app(app) register_api(app) db.init_app(app) user_datastore = get_datastore(db) app.security = Security(app, user_datastore) @app.before_first_request def init_database(): """Check if the database doesn't exist and create it""" try: app.logger.info('Getting users...') get_users() app.logger.info('Success.') except: app.logger.error('Fail. We are gonna create the database') first_data(app, user_datastore) if not os.path.isfile(os.getenv("HOME") + '/.ssh/keys/id_rsa'): ssh.generate_key() @app.route('/', methods=['GET']) @login_required @roles_required('user') def index(): return render_template('dashboard.html') @app.before_request def log_request(): app.logger.debug(request) return app
def create_app(): app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False from docassemble.base.config import daconfig import docassemble.webapp.database import docassemble.webapp.db_object connect_string = docassemble.webapp.database.connection_string() alchemy_connect_string = docassemble.webapp.database.alchemy_connection_string() app.config['SQLALCHEMY_DATABASE_URI'] = alchemy_connect_string app.secret_key = daconfig.get('secretkey', '38ihfiFehfoU34mcq_4clirglw3g4o87') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = docassemble.webapp.db_object.init_flask() db.init_app(app) csrf = CSRFProtect() csrf.init_app(app) babel = Babel() babel.init_app(app) if daconfig.get('behind https load balancer', False): if proxyfix_version >= 15: app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1) else: app.wsgi_app = ProxyFix(app.wsgi_app) return app, csrf, babel
import time from flask import Flask, render_template, request from flask_wtf.csrf import CSRFProtect from flask_socketio import SocketIO, emit from genetic_split.genetic_split import GeneticSplitter APP = Flask(__name__) APP.secret_key = 'splitrnotsosecretkey' SOCKETIO = SocketIO(APP) CSRF = CSRFProtect(APP) SPLITTER = None @APP.route("/", methods=["GET"]) def index(): ''' Index page for splitter-ui ''' return render_template("index.html") @APP.route("/split/", methods=["POST"]) def split_sequence(): ''' Split spaceless sequence using genetic-split algorithm. ''' global SPLITTER SPLITTER = GeneticSplitter(sequence) SPLITTER.evolve_population(50) solution = SPLITTER.solution
import en_core_web_sm from flask_mail import Mail, Message from sqlalchemy import and_ from ratings import ratings_dict from forms import NewUserForm, LoginForm, ListForm, ListUpdateForm, AnimeEntryForm, CategoryForm, SuggestionForm, DeleteUserForm, UpdateUserForm, AddAnimeForm from models import db, connect_db, User, List, List_Entry, Comment, Category, Suggestion app = Flask(__name__) app.config.from_pyfile('config.py') app.register_blueprint(app_funcs) mail = Mail(app) toolbar = DebugToolbarExtension(app) csrf = CSRFProtect(app) bcrypt = Bcrypt() connect_db(app) # db.drop_all() db.create_all() login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' pf = ProfanityFilter() nlp = spacy.load('en_core_web_sm') profanity_filter = ProfanityFilter(nlps={'en': nlp}) nlp.add_pipe(profanity_filter.spacy_component, last=True)
import pandas as pd import numpy as np from flask import jsonify, request, Flask, render_template, redirect, url_for, send_file from werkzeug.utils import secure_filename from werkzeug import SharedDataMiddleware from flask_wtf.csrf import CSRFProtect myPredict = pickle.load(open('model_file', 'rb')) ser_countvect = pickle.load(open('countvect', 'rb')) UPLOAD_FOLDER = '/Users/geofe/Documents/workspace/Projects/Spam_filtering/webapp/uploads' ALLOWED_EXTENSIONS = set(['csv', 'pdf', 'json', 'txt']) app = Flask(__name__) app.config['WTF_CSRF_ENABLED'] = False # Sensitive csrf = CSRFProtect() csrf.init_app(app) # Compliant app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.add_url_rule('/uploads/<filename>', 'uploaded_file', build_only=True) app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {'/uploads': app.config['UPLOAD_FOLDER']}) @app.route('/') def index(): return render_template('index.html') @app.route('/api', methods=['POST']) def model(): result = request.form
def validate(self): if not Form.validate(self): print('Default validation failed') self.invalid = False return False else: if not self.pattern.data and not self.avail_letters.data: self.invalid = True return False else: self.invalid = False return True csrf = CSRFProtect() app = Flask(__name__) app.config["SECRET_KEY"] = "row the boat" csrf.init_app(app) @app.route('/') @app.route('/index') def index(): form = WordForm() return render_template("index.html", form=form) @app.route('/words', methods=['POST', 'GET']) def letters_2_words():
ReviewForm) from DBTools import DBTools worker = DBTools() worker.setup_tables() admin_id = "mengxiaoji" admin_pwd = "meng835542226" check_token = base64.b64encode(bytes(admin_id + admin_pwd, encoding="ascii")).decode("ascii") my_app = Flask(__name__) my_app.config.update(SECRET_KEY="meng13645958845@") csrf = CSRFProtect(my_app) @my_app.route("/", methods=["GET"]) def home(): try: user_id_t = str(request.cookies["user_id"]) session_id_t = int(request.cookies["session_id"]) user_info = worker.get_user_info(user_id_t, session_id_t) if user_info is not None: return render_template("home.html", user_name=user_info["user_name"]) except: print(traceback.format_exc()) return redirect(url_for("login_page"))
# -*- coding: utf-8 -*- import redis from flask import Flask from flask_sqlalchemy import SQLAlchemy # cSrf 防护导入 from flask_wtf.csrf import CSRFProtect from flask_session import Session from config import Config # 创建flask应用 app = Flask(__name__) # 加载配置 app.config.from_object(Config) # 创建连接mysql对象 db = SQLAlchemy(app) # 创建redis对象 redis_store = redis.StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT) # 开启cSrf保护 CSRFProtect(app) # 使用session扩展,将session数据存储到redis Session(app)
"https://raw.githubusercontent.com/qeeqbox/analyzer/master/README.md") APP.config['MONGODB_SETTINGS'] = json_settings[ environ["analyzer_env"]]["web_mongo"] APP.config['SESSION_COOKIE_SAMESITE'] = "Lax" QUEUE = QBQueue("analyzer", json_settings[environ["analyzer_env"]]["redis_settings"]) ANALYZER_TIMEOUT = json_settings[environ["analyzer_env"]]["analyzer_timeout"] FUNCTION_TIMEOUT = json_settings[environ["analyzer_env"]]["function_timeout"] MALWARE_FOLDER = json_settings[environ["analyzer_env"]]["malware_folder"] MONGO_DB = MongoEngine() MONGO_DB.init_app(APP) BCRYPT = Bcrypt(APP) LOGIN_MANAGER = LoginManager() LOGIN_MANAGER.setup_app(APP) CSRF = CSRFProtect() CSRF.init_app(APP) Markdown(APP) class Namespace: ''' this namespace for switches ''' def __init__(self, kwargs): self.__dict__.update(kwargs) def convert_size(_size): ''' convert size to unit
from flask_sqlalchemy import SQLAlchemy from datetime import datetime, timedelta from flask_wtf import FlaskForm from wtforms import widgets from wtforms import RadioField, TextAreaField, TextField, FormField, FieldList, HiddenField, SelectField from wtforms.validators import Optional from flask_wtf.csrf import CSRFProtect import os import csv app = Flask(__name__) app.config[ 'SQLALCHEMY_DATABASE_URI'] = "mysql+mysqlconnector://runaway57:[email protected]/runaway57$frames" app.secret_key = "runaway57$frames" db = SQLAlchemy(app) crsf = CSRFProtect(app) class Tweets(db.Model): __tablename__ = 'TWEETS' tweetid = db.Column(db.String(50), primary_key=True) username = db.Column(db.String(16), primary_key=True) completed = db.Column(db.Boolean) def serialize(self): return { "tweetid": self.tweetid, "username": self.username, "completed": self.completed }
def create_app(test_config=None): app = Flask(__name__) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_object('app.settings.DevelopmentConfig') else: # load the test config if passed in app.config.from_mapping(test_config) db.init_app(app) db.app = app db.create_all() mail = Mail() mail.init_app(app) CSRFProtect(app) CORS(app) create_log(Config.log_path, Config.log_level) app.add_template_filter(log_class, "log_class") """ 蓝图注册 """ from app import opc, user, auth, issue, charts, modbus app.register_blueprint(auth.auth) app.register_blueprint(user.admin) app.register_blueprint(opc.cs) app.register_blueprint(modbus.mt) app.register_blueprint(issue.faq) app.register_blueprint(charts.ct) def make_toke(): csrf_token = generate_csrf() return csrf_token def login_required(view): @functools.wraps(view) def wrapped_view(**kwargs): if g.user is None: return redirect(url_for("auth.login")) return view(**kwargs) return wrapped_view @app.route('/', methods=['GET'], endpoint='index') @login_required def index(): flash('爱上一个地方,就应该背上包去旅行,走得更远。大家都在等你,还不快过来玩耍!', 'success') return render_template('index.html', home='bg-primary') @app.route('/impress', methods=['GET'], endpoint='impress') def impress(): return render_template('impress.html') @app.errorhandler(404) def page_not_found(error): return render_template('404/page_not_found.html'), 404 @app.before_first_request def before_first(): app.logger.debug("config_studio 重新启动") # @csrf_exempt @app.route('/signin', methods=['POST', 'GET'], endpoint='signin') def signin(): response = {} try: username = request.args.get("Username") password = request.args.get("Password") # user = authenticate(request, username=username, password=password) if username == 'admin' and password == '111111': app.logger.debug('登录成功') response['login'] = True response['msg'] = 'success' response['code'] = 200 token = (str(encode_auth_token(username), encoding='utf-8')) response['token'] = token return response response['login'] = False response['msg'] = '登录失败' response['code'] = 500 return response except Exception as e: print(e) return str(e) def encode_auth_token(email): # 申请Token,参数为自定义,user_id不必须,此处为以后认证作准备,程序员可以根据情况自定义不同参数 """ 生成认证Token :param user_id: int :param login_time: int(timestamp) :return: string """ try: headers = { # "typ": "JWT", # "alg": "HS256", "email": email } playload = { "headers": headers, "iss": 'hyy', "exp": datetime.datetime.utcnow() + datetime.timedelta(days=0, hours=0, minutes=30, seconds=0), 'iat': datetime.datetime.utcnow() } signature = jwt.encode(playload, app.secret_key, algorithm='HS256') return signature except Exception as e: return e app.add_url_rule("/", endpoint="index") return app
def create_app(config_name): """通过传入不同的配置名字,初始化其对应配置的应用实例""" app = Flask(__name__) log_level = config[config_name].LOG_LEVEL # 配置项目日志 setup_log(log_level) # 配置 app.config.from_object(config[config_name]) # 配置数据库 db.init_app(app) # 配置redis global redis_store redis_store = StrictRedis(host=config[config_name].REDIS_HOST, port=config[config_name].REDIS_PORT, decode_responses=True) # 开启csrf保护 """ CSRFProtect 这个类专门只对指定 app 进行 csrf_token 校验操作,所以开发者需要做以下几件事情: 生成 csrf_token 的值 将 csrf_token 的值传给前端浏览器 在前端请求时带上 csrf_token 值 """ CSRFProtect(app) @app.after_request def after_request(response): # 调用函数生成 csrf_token csrf_token = generate_csrf() # 通过 cookie 将值传给前端 response.set_cookie("csrf_token", csrf_token) return response from apps.utils.common import user_login_data @app.errorhandler(404) @user_login_data def page_not_found(_): user = g.user data = {"user_info": user.to_dict() if user else None} return render_template('news/404.html', data=data) # 设置session保存位置 Session(app) from apps.utils.common import to_index_class app.add_template_filter(to_index_class, "index_class") from .account import account_app app.register_blueprint(account_app, url_prefix="/user") from .news import news_app app.register_blueprint(news_app) from .admin import admin_app app.register_blueprint(admin_app, url_prefix="/admin") return app
} ] return render_template("index.html", title = 'home', user = user, posts = posts, ip = ip) # 这个callback函数用于reload User object,根据session中存储的user id @lm.user_loader def load_user(user_id): return User.query.get(user_id) #return User.get(user_id) # csrf protection csrf = CsrfProtect() csrf.init_app(app) @app.before_request def before_request(): global ip ip = request.remote_addr g.user = current_user if g.user is not None and current_user.is_authenticated \ and not current_user.confirmed: token = current_user.generate_confirmation_token() current_user.confirm(token) return redirect(url_for('login')) @app.route('/login', methods=['GET', 'POST']) def login():
def create_app(config='config'): csrf = CSRFProtect() # Define the WSGI application object app = Flask(__name__) app.jinja_env.filters["task_details_for_markup"] = task_details_for_markup # Configurations app.config.from_object(config) app.config['CORS_HEADERS'] = 'Content-Type' csrf.init_app(app) if 'API_URL' in os.environ: # Use the API_URL environment varible on Heroku. app.config['API_URL'] = os.environ['API_URL'] if 'SECRET_KEY' in os.environ: # Use the SECRET_KEY environment varible on Heroku # It must be a constant value to allow the session # to be persistent. app.config['SECRET_KEY'] = os.environ['SECRET_KEY'] if 'DATABASE_URL' in os.environ: database_path = os.environ['DATABASE_URL'] else: database_path = None setup_db(app, database_path) CORS(app) # Import a module / component using its blueprint handler # variable (mod_auth) from app.mod_auth.controllers import mod_auth as auth_module from app.mod_calendar.controllers import mod_calendar as calendar_module # Register blueprint(s) app.register_blueprint(auth_module) app.register_blueprint(calendar_module) @app.route('/', methods=['GET']) def index(): return redirect("/calendar/", code=302) # To avoid main_calendar_action below shallowing favicon requests # and generating error logs @app.route("/favicon.ico") def favicon(): send_from_directory( os.path.join("static", "ico"), "favicon.ico", mimetype="image/vnd.microsoft.icon", ) # CORS Headers @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true') return response @app.errorhandler(404) def not_found_error(error): return render_template('errors/404.html'), 404 @app.errorhandler(500) def server_error(error): return render_template('errors/500.html'), 500 ''' Error handler for AuthError error handler should conform to general task above ''' @app.errorhandler(AuthError) def handle_auth_error(error): return jsonify({ "success": False, "error": error.status_code, "message": error.error['description'] }), error.status_code # Create the Flask-Migrate object migrate = Migrate(app, db) return app
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) csrf = CSRFProtect() app.config.update(dict(SECRET_KEY=os.urandom(24) or 'riverrun')) csrf.init_app(app) ''' app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) ''' Bootstrap(app) nav = Nav() ''' def get_db(): db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(DATABASE) return db @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if db is not None: db.close() ''' # registers the "top" menubar nav.register_element( 'top', Navbar( 'Parking', View('Home', 'home'), View('Application', 'application'), Subgroup( 'Admin', View('All Applications', 'view_applications'), View('Settings and Configuration', 'settings'), #Separator(), #Label('Discontinued Products'), #View('Wg10X', 'products', product='wg10x'), ), )) ''' if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass ''' @app.route('/') def home(): #cur = get_db().cursor() lot = Lot() return render_template('index.html', object=lot) @app.route('/application', methods=['GET', 'POST']) def application(): complete = {} if request.method == 'POST': result = request.form for key, value in result.items(): if key != 'csrf_token': if key != 'submit': complete[key] = value now = unicode(datetime.datetime.now()) complete['timestamp'] = now #print application app_obj = Application(complete['full_name']) process_form_results(complete, app_obj) app_obj.id = complete['full_name'] app_obj.grade = complete['grade'] app_obj.multiply(app_obj.qualifier) app_obj.expo_bloom(app_obj.qualifier, app_obj.raw_score) #print application application = json.dumps(app_obj.__dict__) with open("data/output.json", "a") as record: record.write('\n\n' + application) return render_template('ack.html', result=complete, object=app_obj) else: form = ApplicationForm() return render_template('application_form.html', title="Application", form=form, wtf=wtf) @app.route('/receipt') def acknowledge(): return render_template('ack.html') nav.init_app(app) @app.route('/admin/applications') def view_applications(): with open('data/output.json') as data: records = data.read() records = records.split('\n\n') for record in records: record = record.strip() record = json.loads(record) return render_template('applications.html', records=records) @app.route('/admin/settings') def settings(): return render_template('settings.html') return app
from tempfile import mkdtemp from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError from werkzeug.security import check_password_hash, generate_password_hash from fractions import Fraction from flask_wtf import FlaskForm from wtforms import StringField, DateField, PasswordField, IntegerField, SubmitField, SelectField, FloatField, TextAreaField from wtforms.validators import InputRequired, Length, NumberRange, DataRequired, Optional from flask_bootstrap import Bootstrap from flask_wtf.csrf import CSRFProtect from wtforms.fields.html5 import DateField from wtforms.widgets import html5 from helpers import apology, login_required # To enable CSRF protection globally for a Flask app, register the CSRFProtect extension. csrf = CSRFProtect() # Configure application app = Flask(__name__) Bootstrap(app) csrf.init_app(app) # apply it lazily # CSRF uses this key to prevent forms being submitted by people not on the route app.config['SECRET_KEY'] = os.getenv('SECRET_KEY') or \ 'abc123ced456' # Ensure templates are auto-reloaded app.config["TEMPLATES_AUTO_RELOAD"] = True # Ensure responses aren't cached
from flask import Flask from flask_wtf.csrf import CSRFProtect import logging import appengine_config import myapp.app_config app = Flask(__name__) app.config.from_object(__name__) if appengine_config.GAE_DEV: logging.warning('using a dummy secret key') app.secret_key = 'my-secrete-key' app.debug = True else: app.secret_key = myapp.app_config.app_secret_key DEBUG = True csrf_protect = CSRFProtect(app)
return render_template('login.html', form=form, mode=mode) @app.route('/logout') def logout(): session.pop('userEmail', None) return redirect('/') @app.route('/') def hello(): userEmail = session.get('userEmail', None) if userEmail: userName = MyUser.login(userEmail)[1] return render_template('index.html', userName=userName) return render_template('index.html') @app.route('/chart') def chart(): return render_template('chart.html') if __name__ == "__main__": app.config['SECRET_KEY'] = 'this is SEcret Key' csrf = CSRFProtect() csrf.init_app(app) csrf.exempt(api_v1) app.run(host='0.0.0.0', port=5000, debug=True)
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)
from flask import Flask from flask_wtf.csrf import CSRFProtect # type: ignore project_dir = pathlib.Path(__file__).resolve().parent.parent web_dir = project_dir / 'lmsweb' template_dir = project_dir / 'templates' static_dir = project_dir / 'static' config_file = web_dir / 'config.py' webapp = Flask( __name__, template_folder=str(template_dir), static_folder=str(static_dir), ) if not config_file.exists(): shutil.copy(str(web_dir / 'config.py.example'), str(config_file)) webapp.config.from_pyfile(str(config_file)) csrf = CSRFProtect(webapp) # Must import files after app's creation from lms.lmsdb import models # NOQA: F401, E402 from lms.lmsweb import views # NOQA: F401, E402 # gunicorn search for application application = webapp
from flask import Flask from flask import render_template from flask import request from flask import session from flask import redirect, url_for from flask_wtf.csrf import CSRFProtect import forms from static.db import sqlrequest app = Flask(__name__) app.secret_key = 'YC6B8E4IXc' csr = CSRFProtect(app) @app.route('/', methods=['GET', 'POST']) def Index(): error = '' #Use to catch errors to show the user user = '' #Forms login_form = forms.LoginForm(request.form) regist_form = forms.RegistForm(request.form) if 'username' in session: return redirect(url_for('Home')) if request.method == 'POST' and regist_form.validate(): #Saber si el formulario enviado es el de registrarse, comprovando si los campos son validos try: sqlrequest.sqlinsert(regist_form.username.data, regist_form.email.data,
def create_app(config: SDConfig) -> Flask: app = Flask(__name__, template_folder=config.SOURCE_TEMPLATES_DIR, static_folder=path.join(config.SECUREDROP_ROOT, 'static')) app.request_class = RequestThatSecuresFileUploads app.config.from_object(config.SOURCE_APP_FLASK_CONFIG_CLS) # The default CSRF token expiration is 1 hour. Since large uploads can # take longer than an hour over Tor, we increase the valid window to 24h. app.config['WTF_CSRF_TIME_LIMIT'] = 60 * 60 * 24 CSRFProtect(app) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_URI db.init_app(app) # TODO: Attaching a Storage dynamically like this disables all type checking (and # breaks code analysis tools) for code that uses current_app.storage; it should be refactored app.storage = Storage(config.STORE_DIR, config.TEMP_DIR, config.JOURNALIST_KEY) # TODO: Attaching a CryptoUtil dynamically like this disables all type checking (and # breaks code analysis tools) for code that uses current_app.storage; it should be refactored app.crypto_util = CryptoUtil( scrypt_params=config.SCRYPT_PARAMS, scrypt_id_pepper=config.SCRYPT_ID_PEPPER, scrypt_gpg_pepper=config.SCRYPT_GPG_PEPPER, securedrop_root=config.SECUREDROP_ROOT, word_list=config.WORD_LIST, nouns_file=config.NOUNS, adjectives_file=config.ADJECTIVES, gpg_key_dir=config.GPG_KEY_DIR, ) @app.errorhandler(CSRFError) def handle_csrf_error(e: CSRFError) -> werkzeug.Response: msg = render_template('session_timeout.html') session.clear() flash(Markup(msg), "important") return redirect(url_for('main.index')) assets = Environment(app) app.config['assets'] = assets i18n.setup_app(config, app) app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True app.jinja_env.globals['version'] = version.__version__ # Exported to source templates for being included in instructions app.jinja_env.globals['submission_key_fpr'] = config.JOURNALIST_KEY app.jinja_env.filters['rel_datetime_format'] = \ template_filters.rel_datetime_format app.jinja_env.filters['nl2br'] = evalcontextfilter(template_filters.nl2br) app.jinja_env.filters['filesizeformat'] = template_filters.filesizeformat for module in [main, info, api]: app.register_blueprint(module.make_blueprint(config)) # type: ignore @app.before_request @ignore_static def setup_i18n() -> None: """Store i18n-related values in Flask's special g object""" g.locale = i18n.get_locale(config) g.text_direction = i18n.get_text_direction(g.locale) g.html_lang = i18n.locale_to_rfc_5646(g.locale) g.locales = i18n.get_locale2name() @app.before_request @ignore_static def check_tor2web() -> None: # ignore_static here so we only flash a single message warning # about Tor2Web, corresponding to the initial page load. if 'X-tor2web' in request.headers: flash( Markup( gettext( '<strong>WARNING: </strong> ' 'You appear to be using Tor2Web. ' 'This <strong> does not </strong> ' 'provide anonymity. ' '<a href="{url}">Why is this dangerous?</a>').format( url=url_for('info.tor2web_warning'))), "banner-warning") @app.before_request @ignore_static def load_instance_config() -> None: app.instance_config = InstanceConfig.get_current() @app.before_request @ignore_static def setup_g() -> Optional[werkzeug.Response]: """Store commonly used values in Flask's special g object""" if 'expires' in session and datetime.utcnow() >= session['expires']: msg = render_template('session_timeout.html') # clear the session after we render the message so it's localized session.clear() # Redirect to index with flashed message flash(Markup(msg), "important") return redirect(url_for('main.index')) session['expires'] = datetime.utcnow() + \ timedelta(minutes=getattr(config, 'SESSION_EXPIRATION_MINUTES', 120)) # ignore_static here because `crypto_util.hash_codename` is scrypt # (very time consuming), and we don't need to waste time running if # we're just serving a static resource that won't need to access # these common values. if logged_in(): g.codename = session['codename'] g.filesystem_id = app.crypto_util.hash_codename(g.codename) try: g.source = Source.query \ .filter(Source.filesystem_id == g.filesystem_id) \ .filter_by(deleted_at=None) \ .one() except NoResultFound as e: app.logger.error("Found no Sources when one was expected: %s" % (e, )) del session['logged_in'] del session['codename'] return redirect(url_for('main.index')) g.loc = app.storage.path(g.filesystem_id) return None @app.errorhandler(404) def page_not_found( error: werkzeug.exceptions.HTTPException) -> Tuple[str, int]: return render_template('notfound.html'), 404 @app.errorhandler(500) def internal_error( error: werkzeug.exceptions.HTTPException) -> Tuple[str, int]: return render_template('error.html'), 500 return app
if conf.get("SILENCE_FAB"): logging.getLogger("flask_appbuilder").setLevel(logging.ERROR) if app.debug: app.logger.setLevel(logging.DEBUG) # pylint: disable=no-member else: # In production mode, add log handler to sys.stderr. app.logger.addHandler(logging.StreamHandler()) # pylint: disable=no-member app.logger.setLevel(logging.INFO) # pylint: disable=no-member logging.getLogger("pyhive.presto").setLevel(logging.INFO) db = SQLA(app) if conf.get("WTF_CSRF_ENABLED"): csrf = CSRFProtect(app) csrf_exempt_list = conf.get("WTF_CSRF_EXEMPT_LIST", []) for ex in csrf_exempt_list: csrf.exempt(ex) pessimistic_connection_handling(db.engine) migrate = Migrate(app, db, directory=APP_DIR + "/migrations") # Logging configuration logging.basicConfig(format=app.config.get("LOG_FORMAT")) logging.getLogger().setLevel(app.config.get("LOG_LEVEL")) if app.config.get("ENABLE_TIME_ROTATE"): logging.getLogger().setLevel(app.config.get("TIME_ROTATE_LOG_LEVEL")) handler = TimedRotatingFileHandler(
from urlparse import urljoin from flask import Flask, request, jsonify, abort, url_for, session from flask_sqlalchemy import SQLAlchemy from flask_security import Security, SQLAlchemyUserDatastore from flask_security.utils import encrypt_password as encrypt from flask_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)
def init_app(self, app): self.app = app self.conf.update(app.config.get("CELERY_CONF", {})) # Flask admin admin = Admin(name="OpenCVE Admin", template_mode="bootstrap3", index_view=HomeView()) # Debug toolbar debug_toolbar = DebugToolbarExtension() # CSRF protection csrf = CSRFProtect() # SQLAlchemy db = SQLAlchemy(session_options={"autoflush": False}) # Flask gravatar gravatar = Gravatar( size=100, rating="g", default="retro", force_default=False, use_ssl=True, base_url=None, ) # Flask migrate
# # Authors: Ling Thio <*****@*****.**> from datetime import datetime from flask import Flask from flask_mail import Mail from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from flask_sqlalchemy import SQLAlchemy from flask_user import UserManager, SQLAlchemyAdapter from flask_wtf.csrf import CSRFProtect, ValidationError app = Flask(__name__) # The WSGI compliant web application object db = SQLAlchemy() # Setup Flask-SQLAlchemy manager = Manager(app) # Setup Flask-Script csrf = CSRFProtect(app) # Setup CSRF Protection csrf.init_app(app) @app.errorhandler(ValidationError) def handle_csrf_error(e): return render_template('csrf_error.html', reason=e.description), 400 # Initialize Flask Application def init_app(app, extra_config_settings={}): # Read common settings from 'app/settings.py' app.config.from_object('app.settings') # Read environment-specific settings from 'app/local_settings.py' try: app.config.from_object('app.local_settings')
# __init__.py is a special Python file that allows a directory to become # a Python package so it can be accessed using the 'import' statement. from datetime import datetime import os from flask import Flask from flask_mail import Mail from flask_migrate import Migrate, MigrateCommand from flask_sqlalchemy import SQLAlchemy from flask_user import UserManager, UserMixin from flask_wtf.csrf import CSRFProtect # Instantiate Flask extensions db = SQLAlchemy() csrf_protect = CSRFProtect() mail = Mail() migrate = Migrate() def create_app(extra_config_settings={}): """Create a Flask applicaction. """ # Instantiate Flask app = Flask(__name__) # Load App Config settings # Load common settings from 'app/settings.py' file app.config.from_object('app.settings') # Load local settings from 'app/local_settings.py' app.config.from_object('app.local_settings')
# For ELB and/or Eureka @app.route('/healthcheck') def healthcheck(): return 'ok' ### Flask Mail ### from flask_mail import Mail mail = Mail(app=app) from security_monkey.common.utils import send_email as common_send_email ### Flask-WTF CSRF Protection ### from flask_wtf.csrf import CSRFProtect, CSRFError csrf = CSRFProtect() csrf.init_app(app) @app.errorhandler(CSRFError) def csrf_error(reason): app.logger.debug("CSRF ERROR: {}".format(reason)) return render_template('csrf_error.json', reason=reason), 400 from security_monkey.datastore import User, Role ### Flask-Security ### from flask_security.core import Security from flask_security.datastore import SQLAlchemyUserDatastore user_datastore = SQLAlchemyUserDatastore(db, User, Role)
app.config['SQLALCHEMY_DATABASE_URI'] = oppleoSystemConfig.DATABASE_URL app.config[ 'EXPLAIN_TEMPLATE_LOADING'] = oppleoSystemConfig.EXPLAIN_TEMPLATE_LOADING app.config['SQLALCHEMY_POOL_RECYCLE'] = 3600 # import os; os.urandom(24) app.config['SECRET_KEY'] = oppleoConfig.secretKey app.config['WTF_CSRF_SECRET_KEY'] = oppleoConfig.csrfSecretKey # File upload, used for user image app.config[ 'AVATAR_FOLDER'] = oppleoConfig.oppleoRootDirectory + 'src/nl/oppleo/webapp/static/images/avatars/' app.config['MAX_CONTENT_PATH'] = 256 * 1024 # 256kB from flask_wtf.csrf import CSRFProtect # https://flask-wtf.readthedocs.io/en/v0.12/csrf.html CSRFProtect(app) from flask_socketio import SocketIO, emit appSocketIO = SocketIO(app) # Make it available through oppleoConfig oppleoConfig.appSocketIO = appSocketIO # Init the database import nl.oppleo.models.Base from flask_login import LoginManager, current_user import threading from queue import Queue from sqlalchemy.exc import OperationalError from sqlalchemy import event
def create_app(test_config=None): # create and configure the app app = Flask( __name__, static_folder='static', instance_relative_config=True, ) app.config.from_mapping(SECRET_KEY='dev', ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # add CSRF token csrf = CSRFProtect(app) # register blueprints (like views in django) app.register_blueprint(resources.bp) app.register_blueprint(objectives.bp) app.register_blueprint(maps.bp) app.register_blueprint(about.bp) @app.route('/') def landing(): kwargs = {} if os.environ.get("POSTGRES_URL", None) is not None: for k, desc in PROGRESS_NUMBER_MAX.items(): kwargs[k] = query_gauge_maximum(desc) kwargs['km_electricity'] = query_electrified_km() kwargs['mapped_villages'] = query_mapped_villages() kwargs['mapped_buildings'] = query_mapped_buildings() if os.path.exists( os.path.join(templates_dir, "maps", "sidebar_checkbox.html")): kwargs['website_app'] = True else: kwargs['website_app'] = False print("\n\n*** warning ***\n") print( "The webmap will not be able to work correctly because it is missing a file, " "please run 'python app/setup_maps.py'") print("\n***************\n\n") return render_template('landing/index.html', **kwargs) @app.route('/termsofservice') def termsofservice(): return render_template('termsofservice.html') @app.route('/privacypolicy') def privacypolicy(): return render_template('privacypolicy.html') @app.route('/about-map') def about_map(): return render_template('credits.html', about_map=True) @app.route('/developed-by') def developed_by(): return render_template('credits.html', about_map=False) @app.teardown_appcontext def shutdown_session(exception=None): if db_session is not None: db_session.remove() # set a global variable to indicate it is the website app.jinja_env.globals.update(nesp2_website=True) app.jinja_env.globals.update(current_year=datetime.datetime.today().year) try: from .maps_utils import define_function_jinja define_function_jinja(app) except ModuleNotFoundError: print("\n\n*** warning ***\n") print( "The webmap will not be able to work correctly, please run 'python " "app/setup_maps.py'") print("\n***************\n\n") except ImportError: print("\n\n*** warning ***\n") print( "The webmap will not be able to work correctly, you are missing the function " "'define_function_jinja' into the app/maps_utils.py file, please run 'python " "app/setup_maps.py'") print("\n***************\n\n") return app
def create_app(config_filename=None, **kwargs): """ Application factory :param config_filename: :return: """ # Initialize flask app app = Flask(__name__.split('.')[0], static_url_path='') # Import default configs app.config.from_object('sqmpy.defaults') # Configurations app.config.from_object('config') # Load the given config file if config_filename: app.config.from_pyfile(config_filename, silent=False) # Import from environment app.config.from_envvar('SQMPY_SETTINGS', silent=True) # Updated with keyword arguments app.config.update(kwargs) # Register app on db from sqmpy.database import db db.init_app(app) csrf = CSRFProtect() # Activate CSRF protection if app.config.get('CSRF_ENABLED'): csrf.init_app(app) # Register blueprints from sqmpy.security import security_blueprint from sqmpy.job import job_blueprint from sqmpy.views import main_blueprint app.register_blueprint(security_blueprint) app.register_blueprint(job_blueprint) app.register_blueprint(main_blueprint) if __debug__: # create_all should be called after models are imported. In current # code they are imported along with blue_print imports above. with app.app_context(): db.create_all() # A global context processor for sub menu items @app.context_processor def make_navmenu_items(): from flask import url_for if job_blueprint.name in app.blueprints: return {'navitems': {job_blueprint.name: url_for('%s.index' % job_blueprint.name)}} else: return {} @app.before_first_request def activate_job_monitor(): thread = JobMonitorThread(kwargs={'app': app}) app.monitor = thread thread.start() return app
from flask import Flask, session from flask_sqlalchemy import SQLAlchemy from white_party.configuration import Config from flask_bcrypt import Bcrypt from flask_wtf.csrf import CSRFProtect from flask_mail import Mail app = Flask(__name__) app.config.from_object(Config) # used to hash passwords crypt = Bcrypt(app) # security csrf_token = CSRFProtect(app) Talisman(app, content_security_policy=Config.TALISMAN_CSP) db = SQLAlchemy(app) db.create_all() mail = Mail(app) from white_party.Users.routes import users from white_party.Laws.routes import laws from white_party.Main.routes import main from white_party.Proposals.routes import proposals from white_party.errors.routes import errors from white_party.tasks.routes import tasks
More Info: Flask: http://flask.pocoo.org/ WTForms: http://flask.pocoo.org/docs/1.0/patterns/wtforms/ """ import os import re import json from flask import Flask, render_template, request, redirect, flash, session, jsonify from flask_wtf.csrf import CSRFProtect app = Flask(__name__) # initialise the flask app app.config['SECRET_KEY'] = os.urandom(24) # create the secret key csrf = CSRFProtect(app) # protect the csrf app csrf.init_app(app) # initialise the csrf with the app profiles_dir = [ ] # specify and empty list to store the directory of the profiles name_list = [] # specify an empty name list to store the name main_class = {} # store the main class to call the main method in main.py # Broker Log File SYSLOG = r"/Users/southzyzy/Work/SAF/DnStack/logs/sysinfo.log" CLIENT_SESS_LOG = r"/Users/southzyzy/Work/SAF/DnStack/logs/client_session.log" DOMAIN_PROFILES_LOG = r"/Users/southzyzy/Work/SAF/DnStack/logs/domain_profiles.log" BLOCKCHAIN_LOG = r"/Users/southzyzy/Work/SAF/DnStack/logs/blockchain.log" # Server Connection Settings HOST, PORT = "localhost", 1335
from flask import Flask from .views import page # Importamos todas las rutas almancenadas en page from flask_bootstrap import Bootstrap # importamos la libreria Bootstrap from flask_wtf.csrf import CSRFProtect from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) db = SQLAlchemy(app) from .models import Users bootstrap = Bootstrap() # creamos una instancia de bootstrap csrf = CSRFProtect() # instanciamos def create_app( config ): # Indicamos que la funcion create_app reciba un parametro: config app.config.from_object( config ) # Indicamos al aervidor que utilice nuestras configuraciones de 'config' csrf.init_app(app) bootstrap.init_app( app ) # Le indicamos al servidor que use bootstrap, esto se harà en los templates (herencia) app.register_blueprint( page) # vamos a indicar al servidor con que rutas se va a trabajar with app.app_context():
print("blueprint registration failed") logging.exception(e) if conf.get('SILENCE_FAB'): logging.getLogger('flask_appbuilder').setLevel(logging.ERROR) if not app.debug: # In production mode, add log handler to sys.stderr. app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) logging.getLogger('pyhive.presto').setLevel(logging.INFO) db = SQLA(app) if conf.get('WTF_CSRF_ENABLED'): csrf = CSRFProtect(app) csrf_exempt_list = conf.get('WTF_CSRF_EXEMPT_LIST', []) for ex in csrf_exempt_list: csrf.exempt(ex) utils.pessimistic_connection_handling(db.engine) cache = utils.setup_cache(app, conf.get('CACHE_CONFIG')) tables_cache = utils.setup_cache(app, conf.get('TABLE_NAMES_CACHE_CONFIG')) migrate = Migrate(app, db, directory=APP_DIR + "/migrations") # Logging configuration logging.basicConfig(format=app.config.get('LOG_FORMAT')) logging.getLogger().setLevel(app.config.get('LOG_LEVEL'))
# 扩展类实例化 from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_bootstrap import Bootstrap from flask_wtf.csrf import CSRFProtect db = SQLAlchemy() # 数据库实例化 login_manager = LoginManager() #扩展登录功能 bootstrap = Bootstrap() #扩展Bootstrap csrf = CSRFProtect() #CSRF保护 # 用户加载函数 @login_manager.user_loader def load_user(user_id): from edatribe.models import Admin user = Admin.query.get(int(user_id)) return user # 页面保护 -> 登录视图 login_manager.login_view = 'auth.login'