from flask import Flask, g, render_template, redirect, url_for # flask-1.1.2 import forms import models from flask_wtf.csrf import CsrfProtect csrf = CsrfProtect() Debug = True app = Flask(__name__) csrf.init_app(app) app.secret_key = "shrreasfass781!-adffa1" @app.before_request def before_request(): """Connect to the Database before each request""" db = models.DATABASE db.connect() @app.after_request def after_request(response): """Close the Database after each request""" models.DATABASE.close() return response @app.route('/') def index():
import logging import requests from flask_restful import Api, Resource from flask import Flask, render_template, request, send_from_directory from flask import jsonify from flask_wtf.csrf import CsrfProtect from xml.etree import ElementTree as ET from models import db application = Flask(__name__, template_folder="templates", static_url_path='/static') application._static_folder = os.path.abspath("static/") api = Api(application) csrf = CsrfProtect(application) @application.route('/css/<path:filename>') def serve_static_css(filename): root_dir = os.path.dirname(os.getcwd()) return send_from_directory(os.path.join(root_dir, 'static', 'css'), filename) @application.route('/js/<path:filename>') def serve_static_js(filename): root_dir = os.path.dirname(os.getcwd()) return send_from_directory(os.path.join(root_dir, 'static', 'js'), filename)
# 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.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( u'Security informations are missing or expired. ' u'This may happen if you have opened the form for a long time. <br /><br />' u'Please try to resubmit the form.')
def register_form(app): csrf = CsrfProtect() csrf.init_app(app)
from flask_mongoengine import MongoEngine from flask_pymongo import PyMongo from flask_bcrypt import Bcrypt from flask_logconfig import LogConfig from flask_security import Security from flask_security.core import LoginManager from flask_wtf.csrf import CsrfProtect security = Security() login_manager = LoginManager() bcrypt = Bcrypt() db = MongoEngine() logcfg = LogConfig() # LOG csrf_protect = CsrfProtect() # csrf保护 login_manager.session_protection = None login_manager.login_view = "/login/"
# encoding:utf8 import time from flask import abort, request, Response from . import signals from . import wechat_blueprint as wechat from .messages import WeChatMessageBase, WeChatResponse from flask import current_app from flask_wtf.csrf import CsrfProtect csrf = CsrfProtect(current_app) @csrf.exempt @wechat.route("/<identity>/", methods=["GET", "POST"]) def callback(identity): _send_signal("request_received", identity, request=request) # 验证请求 signature = request.args.get("signature") try: timestamp = int(request.args.get("timestamp")) except: _send_signal("request_badrequest", identity, request=request, message="incorrect timestamp") abort(400) nonce = request.args.get("nonce") if not (signature and timestamp and nonce): _send_signal("request_badrequest", identity, request=request,
def run_app(): CsrfProtect(app) port = int(os.environ.get('PORT', 8003)) app.run(host='0.0.0.0', port=port)
def configure_views(app): user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore, confirm_register_form=ExtendedRegisterForm) csrf = CsrfProtect(app) migrate = Migrate(app, db) admin = Admin(app, name="Lean Workbench Admin") admin.add_view(UserView(User, db.session)) admin.add_view( ExportView(QuickbooksDailyAccountBalance, db.session, name="Quickbooks")) admin.add_view(ExportView(FacebookPageData, db.session, name="Facebook")) admin.add_view(ExportView(DateCount, db.session, name="Twitter Count")) admin.add_view( ExportView(GoogleAnalyticsVisitors, db.session, name="Visitors")) admin.add_view( ExportView(GoogleAnalyticsSignups, db.session, name="Signups")) print current_user @app.route('/') def index(): if current_user.is_authenticated(): logged_in = True return redirect(url_for('dashboard')) else: logged_in = False return render_template('public.html', logged_in=logged_in) @app.route('/signin', methods=["POST", "GET"]) @app.route('/signup', methods=["POST", "GET"]) def sign(): if current_user.is_authenticated(): return redirect(url_for('dashboard')) return render_template('public.html', logged_in=False) @auth_token_required @app.route('/stats', methods=['POST', 'GET']) @app.route('/stats/1', methods=['POST', 'GET']) @app.route('/onboarding/stick', methods=['POST', 'GET']) @app.route('/onboarding/scale', methods=['POST', 'GET']) @app.route('/onboarding/virality', methods=['POST', 'GET']) @app.route('/onboarding/pay', methods=['POST', 'GET']) @app.route('/onboarding/empathy', methods=['POST', 'GET']) @app.route('/export', methods=['POST', 'GET']) @app.route('/scale', methods=['POST', 'GET']) @app.route('/results', methods=['POST', 'GET']) @app.route('/privacy', methods=['POST', 'GET']) @app.route('/eula', methods=['POST', 'GET']) @app.route('/optimization', methods=['POST', 'GET']) @app.route('/baseline', methods=['POST', 'GET']) @app.route('/operations', methods=['POST', 'GET']) @app.route('/onboarding/done', methods=['GET', 'POST']) @app.route('/dashboard', methods=['POST', 'GET']) def dashboard(): """ """ if not current_user.is_authenticated(): return render_template('public.html', logged_in=False) else: return render_template('public.html', logged_in=True) @app.route('/welcome', methods=['POST', 'GET']) def welcome(): current_user.onboarded = True db.session.add(current_user) db.session.commit() return render_template('public.html', logged_in=True) api = restful.Api(app, decorators=[csrf.exempt]) api.add_resource(HypothesisResource, '/api/v1/hypotheses') api.add_resource(FacebookResource, '/api/v1/facebook') api.add_resource(TwitterResource, '/api/v1/twitter') api.add_resource(WufooResource, '/api/v1/wufoo') api.add_resource(GoogleAnalyticsResource, '/api/v1/google-analytics') api.add_resource(Quickbooks_resource, '/api/v1/quickbooks') api.add_resource(UserResource, '/api/v1/users') api.add_resource(Ghosting_resource, '/api/v1/ghosting') api.add_resource(Scale_resource, '/api/v1/scale')
class loginform(FlaskForm): csrf_token=CsrfProtect(app) email=StringField('Email',[validators.DataRequired()]) password=PasswordField('Password', [validators.DataRequired()]) submit=SubmitField('Login')
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 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 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
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
def register_form(app): from flask_wtf.csrf import CsrfProtect csrf = CsrfProtect() csrf.init_app(app)
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
def init_app(instance_path=None): """ Initializes Flask configurations, SQLAlchemy, Quasselflask-specific setup, Flask extension setup/glue. Imports SQLAlchemy models (will create DB connections immediately due to the need to reflect Quassel). Does not create Quasselflask-specific tables - need to call ``init_db()``. :return: """ # flag the dummy as during/after init_app call - just to be nice to devs who misconfigure sensitive modules! # Need to do this before the import calls to allow them to be flagged if issues exist at the module level DummyObject.set_all_init() import quasselflask from quasselflask.base_config import DefaultConfig, InternalConfig from quasselflask.parsing.irclog import DisplayBacklog from quasselflask.parsing.form import PasswordValidator # Flask app = quasselflask.app = Flask(__name__, instance_path=os.environ.get( 'QF_CONFIG_PATH', instance_path), instance_relative_config=True) app.config.from_object(DefaultConfig) app.config.from_object(InternalConfig) app.config.from_pyfile('quasselflask.cfg') app.config.from_envvar('QF_ALLOW_TEST_PAGES', True) if not app.config.get('SECRET_KEY', None): raise EnvironmentError( "QuasselFlask SECRET_KEY parameter not set or empty in configuration" ) app.config['USER_APP_NAME'] = app.config[ 'SITE_NAME'] # used by Flask-User email templates init_logging() app.logger.info('QuasselFlask {}'.format(quasselflask.__version__)) app.logger.info('Initialising...') # Flask-Script cmdman = quasselflask.cmdman = Manager(app) cmdman.help_args = ('-?', '--help') # Database app.logger.info('Configuring database.') db = quasselflask.db = SQLAlchemy(app) app.logger.info( 'Connecting to database and analysing quasselcore tables. This may take a while...' ) import quasselflask.models.models app.logger.info( 'Checking QuasselFlask tables and creating if necessary...') quasselflask.models.models.qf_create_all() # Forms CsrfProtect(app) # Flask-Mail, for Flask-User mail = quasselflask.mail = Mail(app) # Flask-Mail, for Flask-User # Flask-User db_adapter = SQLAlchemyAdapter(db, quasselflask.models.models.QfUser) loginman = LoginManager() loginman.anonymous_user = quasselflask.models.models.QfAnonymousUserMixin userman = quasselflask.userman = UserManager( db_adapter, app, password_validator=PasswordValidator( len_min=app.config['QF_PASSWORD_MIN'], len_max=app.config['QF_PASSWORD_MAX'], required_regex=app.config['QF_PASSWORD_REGEX'], message=app.config['QF_PASSWORD_MSG']), login_manager=loginman) # Configure other internal classes DisplayBacklog.set_time_format(app.config['TIME_FORMAT']) app.logger.debug('Configuring web endpoints...') import quasselflask.views app.logger.debug('Configuring command-line commands...') import quasselflask.commands return 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
"""Code Analyzer RUN.""" from flask import Flask from flask.ext.restful import Api from flask_wtf.csrf import CsrfProtect from views import main from api import configure_api app = Flask(__name__) app.config.from_object('config.default') csrf_protect = CsrfProtect(app) app.register_blueprint(main) api_manager = Api(app) configure_api(api_manager) if __name__ == '__main__': app.run()
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
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 # Initialize Babel Babel(self) # Finally set the initialised attribute self.initialised = True
# 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)
# -*- coding: utf-8 -*- """Extensions module. Each extension is initialized in the app factory located in app.py.""" from flask_bcrypt import Bcrypt from flask_cache import Cache from flask_debugtoolbar import DebugToolbarExtension from flask_login import LoginManager from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from flask_wtf.csrf import CsrfProtect from flask_googlemaps import GoogleMaps from flask_googlemaps import Map bcrypt = Bcrypt() csrf_protect = CsrfProtect() login_manager = LoginManager() db = SQLAlchemy() migrate = Migrate() cache = Cache() debug_toolbar = DebugToolbarExtension() googlemaps = GoogleMaps()
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):
if os.environ.get('STORE_CONFIG') is not None: APP.config.from_envvar('STORE_CONFIG') # Logging handler = RotatingFileHandler(APP.config['LOG_FILE'], maxBytes=10000, backupCount=1) if APP.config['DEBUG'] is not True: handler.setLevel(logging.INFO) else: handler.setLevel(logging.DEBUG) APP.logger.addHandler(handler) # wtforms csrf CsrfProtect(app=APP) # import the modules to be used import model from model import engine, Base import forms SESSION = model.create_session(APP.config['DB_URL'], engine, Base) @APP.route("/", methods=['GET', 'POST']) def index(): ''' Give out the form for preordering ''' form = forms.DiscountForm() out = {'status': False, 'msg': ''} if form.validate_on_submit():
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 import Flask import jinja2 import os app = Flask(__name__, static_folder='static') env = 'production' app.config['ENV'] = env app.config.from_pyfile('config.py') # app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = ('name', 'email') # CSRF protection from flask_wtf.csrf import CsrfProtect CsrfProtect(app) # Database from flask_sqlalchemy import SQLAlchemy # app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL'] app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@localhost/scoda' db = SQLAlchemy(app) # Mail from flask_mail import Mail mail = Mail(app) from flask_mobility import Mobility
def test_deprecated_csrfprotect(recwarn): CsrfProtect() w = recwarn.pop(FlaskWTFDeprecationWarning) assert 'CSRFProtect' in str(w.message)
import sys if "debug" in sys.argv: print("Flask running in debug mode!") app.debug = True app.config.from_object('config.BaseConfig') app.jinja_env.add_extension('jinja2.ext.do') db = SQLAlchemy(app) lm = LoginManager() lm.anonymous_user = AnonUser lm.init_app(app) lm.login_view = 'login' lm.login_message = 'Please log in to access this page.' mail = Mail(app) babel = Babel(app) csrf = CsrfProtect(app) if "debug" in sys.argv: print("Installing debug toolbar!") toolbar = DebugToolbarExtension(app) if not app.debug: import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler('tmp/wlnupdates.log', 'a', 1 * 1024 * 1024, 10) file_handler.setLevel(logging.INFO) file_handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('wlnupdates startup')
from flask_wtf.csrf import CsrfProtect from flask_bcrypt import Bcrypt import pymysql.cursors from pandas import read_csv from werkzeug.utils import secure_filename flask_obj = Flask(__name__) flask_obj.secret_key = "9f9dace5bff3b61cd9603b631d00bad8" db_connect = pymysql.connect(host="localhost", user='******', password="******", db="inventory_management", charset="utf8mb4", cursorclass=pymysql.cursors.DictCursor) cursor = db_connect.cursor() CsrfProtect(flask_obj) bcrypt = Bcrypt() final_login = True ALLOWED_EXTENSIONS = {'csv', 'xlsx'} app = Flask(__name__) def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def email_client(email, s): import smtplib, ssl