def create_app(object_name): app = Flask(__name__) app.config.from_object(object_name) CORS(app) assets_env.init_app(app) assets_env.register('main_css', main_css) cache.init_app(app) csrf = CSRFProtect(app) csrf.exempt(api_blueprint) csrf.init_app(app) db.init_app(app) login_manager.init_app(app) app.register_blueprint(blog_blueprint) app.register_blueprint(control_blueprint) app.register_blueprint(api_blueprint) app.register_blueprint(upload_blueprint) app.add_template_filter(format_time, 'format_time') app.add_template_filter(html_to_text, 'html_to_text') app.add_template_filter(time_human, 'time_human') return app
def create_app(config=DevelopmentConfig): app = Flask(__name__) migrate = Migrate(app, db) csrf = CSRFProtect(app) app.config.from_object(config) login_manager = LoginManager() login_manager.login_view = 'auth.login' login_manager.init_app(app) db.init_app(app) ma.init_app(app) csrf.init_app(app) with app.app_context(): db.create_all() # register each active blueprint for url, blueprint in ACTIVE_ENDPOINTS: app.register_blueprint(blueprint, url_prefix=url) @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) @app.route('/spec') def spec(): swag = swagger(app) swag['info']['version'] = "1.0.0" swag['info']['title'] = "pygroup-Web" swag['info']['description'] = "My shop example using Flask" return jsonify(swag) app.register_blueprint(swagger_blueprint, url_prefix=SAWGGER_URL) return app
def create_app(test_config=None) -> Flask: app = Flask(__name__, instance_relative_config=True) if test_config is None: user_config = pathlib.Path('config.py') if user_config.exists(): app.config.from_pyfile(user_config, silent=True) else: app.config.from_object(Config) else: app.config.from_object(test_config) Debug(app) Bootstrap(app) app.register_blueprint(frontend) app.config['BOOTSTRAP_SERVE_LOCAL'] = True nav.init_app(app) crsf = CSRFProtect() crsf.init_app(app) return app
def create_app(): app = Flask(__name__) app.config.update(SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE='Strict') app.config.from_mapping(SECRET_KEY=os.environ['FLASK_KEY']) csrf = CSRFProtect() csrf.init_app(app) return app, csrf
def create_app(config_name): global user_datastore app = Flask(__name__) app.config.from_object(app_config[config_name]) csrf = CSRFProtect() csrf.init_app(app) assets = Environment(app) create_assets(assets) via = Via() via.init_app(app) # Code for desmostration the flask upload in several models - - - - from user import user_photo from restaurant import restaurant_photo from food import food_photo configure_uploads(app, (restaurant_photo, food_photo, user_photo)) engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI']) if not database_exists(engine.url): create_database(engine.url) security = Security(app, user_datastore, register_form=SecurityRegisterForm) create_security_admin(app=app, path=os.path.join(os.path.dirname(__file__))) with app.app_context(): db.init_app(app) db.create_all() user_datastore.find_or_create_role(name='admin', description='Administrator') db.session.commit() user_datastore.find_or_create_role(name='end-user', description='End user') db.session.commit() @app.route('/', methods=['GET']) @app.route('/home', methods=['GET']) def index(): return render_template('index.html') @app.errorhandler(403) def forbidden(error): return render_template('error/403.html', title='Forbidden'), 403 @app.errorhandler(404) def page_not_found(error): return render_template('error/404.html', title='Page Not Found'), 404 @app.errorhandler(500) def internal_server_error(error): db.session.rollback() return render_template('error/500.html', title='Server Error'), 500 return app
def create_app(): app = Flask(__name__) app.config.update(SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE='Strict') app.config.from_mapping( SECRET_KEY="dev") # hardcoded for autograder purposes csrf = CSRFProtect() csrf.init_app(app) return app, csrf
def create_app(config=DevelopmentConfig): app = Flask(__name__) migrate = Migrate(app, db) csrf = CSRFProtect(app) app.config.from_object(config) db.init_app(app) ma.init_app(app) csrf.init_app(app) with app.app_context(): #el contexto es la DB, el serializable db.create_all() for url, blueprint in ACTIVE_ENDPOINTS: app.register_blueprint(blueprint, url_prefix=url) return app
def get_app(config_name): """ app工厂函数 :param config_name: 传入现在开发的环境名字 :return: 返回app """ # 调用封装的日志 setupLogging(configs[config_name].LOGGIONG_LEVEL) # 创建app app = Flask(__name__) # 加载配置文件 app.config.from_object(configs[config_name]) # 创建数据库连接对象,赋值给全局db global db # db=SQLAlchemy(app) 这个不能用,因为会出现两个db的bug,两session,后续处理起来麻烦 db.init_app(app) # 创建Redis数据库连接对象 global redis_conn redis_conn = redis.StrictRedis(host=configs[config_name].REDIS_HOST, port=configs[config_name].REDIS_PORT, password=configs[config_name].REDIS_PWD) # session绑定app Session(app) # 自定义转换器加入到默认转换器列表中 app.url_map.converters['re'] = RegexConverter # 哪里需要哪里导入蓝图 from ihome.api_1_0 import api from ihome.web_html import static_html # 注册蓝图 app.register_blueprint(api) app.register_blueprint(static_html) # from ihome.api_1_0.test import test from ihome.api_1_0.pay import order_complete_post # 开启CSRF保护 csrf = CSRFProtect() # 支付宝异步回调没有csrf值 csrf.exempt(order_complete_post) # csrf.exempt(test) csrf.init_app(app) return app
def create_app(config=DevelopmentConfig): app = Flask(__name__) migrate = Migrate(app, db) csrf = CSRFProtect(app) app.config.from_object(config) login_manager = LoginManager() login_manager.login_view = 'auth.login' login_manager.login_message = "Ingrese para acceder a esta pagina." login_manager.init_app(app) db.init_app(app) ma.init_app(app) csrf.init_app(app) migrate.init_app(app, db) with app.app_context(): db.create_all() # register each active blueprint for url, blueprint in ACTIVE_ENDPOINTS: app.register_blueprint(blueprint, url_prefix=url) @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) # ruta principal de la pagina @app.route('/', methods=['GET']) def index(): last_products = get_last_products() random_cat = get_random_categories() categories = get_all_categories() my_info = { "products": last_products, "random_cat": random_cat, "categories": categories } return render_template("index.html", my_info=my_info) # Varables globales para ser usadas en cualquier plantilla @app.context_processor def global_variables(): categories = get_all_categories() basics = {"categories": categories} return dict(basics=basics) return app
def create_app(config=DevelopmentConfig): app = Flask(__name__) csrf = CSRFProtect(app) app.config.from_object(config) db.init_app(app) ma.init_app(app) csrf.init_app(app) with app.app_context(): db.create_all() # register each active blueprint for url, blueprint in ACTIVE_ENDPOINTS: app.register_blueprint(blueprint, url_prefix=url) csrf.exempt(products) return app
def create_app(config=DevelpmentConfig): app = Flask(__name__) migrate = Migrate(app, db) csrf = CSRFProtect(app) app.config.from_object(config) login_manager = LoginManager() login_manager.login_view = "auth.login" login_manager.init_app(app) db.init_app(app) ma.init_app(app) csrf.init_app(app) migrate.init_app(app, db) @app.template_filter('datetimeformat') def datetimeformat(value, format="%Y"): return value.strftime(format) with app.app_context(): db.create_all() # register each active blueprint for url, blueprint in ACTIVE_ENDPOINTS: app.register_blueprint(blueprint, url_prefix=url) #This line disable csrf, I have a problem with addStock because it csrf.exempt(auth) @login_manager.user_loader def load_user(user_id): # since the user_id is just the primary key of our user table, # use it in # the query for the user return User.query.get(int(user_id)) @login_manager.unauthorized_handler def unauthorized(): # do stuff return redirect(url_for("products.catalog")) return app
def create_app(): """ Creates a basic Flask application. Uses CSRF and registers the routing blueprints. :rtype flask.app.Flask """ # create a Flask application application = Flask(__name__) application.config.from_object(Config) # CSRF is required for submitting forms (e.g. to run a simulation) csrf = CSRFProtect() csrf.init_app(application) # register the routing blueprint application.register_blueprint(routes) return application
def create_app(config_file_path: str): app = Flask(__name__) # Load the application configuration app.config.from_pyfile(config_file_path) # Set up cross site forgery protection that WTForms uses csrf = CSRFProtect(app) csrf.init_app(app) # Set up the DbSetup object to connect to the database db_setup = DbSetup(app.config['DATABASE_URI']) db_setup.initialize_database() # Build services that the application will use catalog_service = CatalogService(db_setup) user_service = UserService(db_setup) # Set up the Flask Login Manager login_manager = LoginManager() login_manager.user_loader(user_service.get_user) login_manager.init_app(app) # Set up the google authentication configuration google_config = GoogleAuthConfig(app.config['GOOGLE_SECRETS_FILE'], user_service=user_service) # Control wheter or not OAuth will allow non https transport env_insecure_transport = 'OAUTHLIB_INSECURE_TRANSPORT' os.environ[env_insecure_transport] = app.config[env_insecure_transport] # Controls how strict the matching of scopes returned by the OAuth server # against the requested scopes is env_relax_scope = 'OAUTHLIB_RELAX_TOKEN_SCOPE' os.environ[env_relax_scope] = app.config[env_relax_scope] # Inject the required services into the views used by the application views_init_app(app, catalog_service, google_config) # Return the configured application return app
def create_app(config_name='development'): app_name = app_config[config_name].APP_NAME or __name__ app = Flask(app_name) app.config.from_object(app_config[config_name]) csrf = CSRFProtect() csrf.init_app(app) assets = Environment(app) app.static_folder = 'public' with app.app_context(): from .route import Route import app as user_app blueprint = Blueprint('public', 'public', static_url_path='/public', static_folder='public') app.register_blueprint(blueprint) blueprint = Blueprint('app', 'app', template_folder='templates') app.register_blueprint(blueprint) rt = Route(routes) rt.init_app(app) user_app.init_app(app, csrf, assets) @app.errorhandler(403) def forbidden(error): return render_template('error/403.html', title='Forbidden'), 403 @app.errorhandler(404) def page_not_found(error): return render_template('error/404.html', title='Page Not Found'), 404 @app.errorhandler(500) def internal_server_error(error): return render_template('error/500.html', title='Server Error'), 500 return app
# Sample HTTP error handling @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 # Register blueprint(s) app.register_blueprint(admin_ctr) app.register_blueprint(user_ctr) app.register_blueprint(home_ctr) app.register_blueprint(group_ctr) """ Prevención de XSS & XSRF """ csrf = CSRFProtect() """ Inicializa la aplicación y arranca los servicios necesarios """ csrf.init_app(app) # Inicia la aplicación con la cofiguración establecida db.init_app(app) # Carga la configuración de la bd mail.init_app(app) # Arranca el servidor de correo with app.app_context(): #db.drop_all() # Borra la BD db.create_all() # Crea las tablas que no existan __create_foreign_keys() print("Inicializada la aplicación.")
if os.environ["PPT_ENVIRONMENT"] == "prod": app.config.from_pyfile('../config/settings_prod.py') elif os.environ["PPT_ENVIRONMENT"] == "test": app.config.from_pyfile('../config/settings_test.py') else: app.config.from_pyfile('../config/settings_dev.py') app.secret_key = app.config["SECRET_KEY"] # Load/initialize extensions # CSRFProtect is for csrf protecting POST requests that do not contain a form. # By initializing it, all POST requests must send an X-CSRFToken header # to be allowed to connect. csrf = CSRFProtect() csrf.init_app(app) cors = CORS(app) db = SQLAlchemy(app) lm = LoginManager() lm.init_app(app) principals = Principal(app) wtforms_json.init() # authentication/login form methods. We use flask_jwt for authentication, and # send out a JSON web token that is stored in the client and sent back with # every request. The authentication back end is LDAP. We send out LDAP groups # the user is in for use in role-based authorization on the front end (what to # show the user). We do check the directory again when handling each request. from flask_ppt2.auth.models import User
from flask import Flask from flask_wtf import CSRFProtect from configs import UPLOAD_FOLDER, MAX_CONTENT_LENGTH, SECRET_KEY from web.api import api from web.routes import web # General configs app = Flask(__name__, static_folder='static') csrf = CSRFProtect() app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH app.secret_key = SECRET_KEY csrf.init_app(app) # Compliant # Blueprints app.register_blueprint(api) app.register_blueprint(web)
userstest.username, #the model, not the table Comment.text, Comment.created_date).paginate(page,per_page,True) #(page, rows per page, if True=404, if False: empty) return render_template('reviews.html', comments = comment_list, date_format = date_format) #we send the function as a parameter @app.after_request def after_request(response): return response #always return response db.init_app(app) #this was supposed to be inside if __name__ but it didn't work: https://stackoverflow.com/questions/30764073/sqlalchemy-extension-isnt-registered-when-running-app-with-gunicorn mail.init_app(app) #same as db.init_app if __name__ == '__main__': #before config: #app.run(debug=True) csrf.init_app(app) #this one after config #db.init_app(app) #mail.init_app(app) with app.app_context(): db.create_all() #this will create every table that IS NOT created already app.run()
class BaseWebServer(object): def __init__(self, p_name, p_config, p_package_name, p_user_handler=None, p_login_view=None, p_logged_out_endpoint=None): self._login_manager = None self._flask_stopper = None self._auth_view_handler = None self._server_started = False self._user_handler = p_user_handler self._csrf = None self._name = p_name self._config = p_config self._login_view = p_login_view if p_package_name is None: raise configuration.ConfigurationException( "HttpServer: p_package_name must not be None") self._logger = log_handling.get_logger(self.__class__.__name__) self._app = flask.Flask(p_package_name) # see https://improveandrepeat.com/2020/10/python-friday-43-add-security-headers-to-your-flask-application/ # see https://secure.readthedocs.io/en/latest/frameworks.html#flask self._app.after_request(set_secure_headers) # see https://stackoverflow.com/questions/62992831/python-session-samesite-none-not-being-set # see https://flask.palletsprojects.com/en/2.0.x/security/#security-cookie self._app.config['SESSION_COOKIE_SAMESITE'] = "Strict" self._flask_stopper = some_flask_helpers.FlaskStopper( p_app=self._app, p_logger=self._logger) self._app.config["APPLICATION_ROOT"] = self._config.base_url if self._user_handler is not None: tools.check_config_value(p_config=self._config, p_config_attribute_name="app_secret") self._auth_view_handler = auth_view_handler.AuthViewHandler( p_user_handler=self._user_handler, p_app=self._app, p_logged_out_endpoint=p_logged_out_endpoint, p_url_prefix=self._config.base_url, p_login_view=p_login_view) # Activate CSRF protection self._app.config.update(SECRET_KEY=self._config.app_secret) self._csrf = CSRFProtect() self._csrf.init_app(self._app) self._server_exception = None # Install the actuator handler for the health check self._actuator_view_handler = actuator.ActuatorViewHandler( p_app=self._app, p_url_prefix=self._config.internal_base_url) logger = log_handling.get_logger("werkzeug") logger.setLevel(logging.WARNING) logger = log_handling.get_logger("sqlalchemy.engine") logger.setLevel(logging.WARNING) def destroy(self): self._actuator_view_handler.destroy() self._flask_stopper.destroy() if self._auth_view_handler is not None: self._auth_view_handler.destroy() def add_url_rule(self, p_rel_url, p_endpoint, p_view_method, p_blueprint, p_methods=None, p_login_required=False): if p_login_required: p_view_method = flask_login.login_required(p_view_method) p_blueprint.add_url_rule(join(self._config.base_url, p_rel_url), p_endpoint, p_view_method, methods=p_methods) def get_url(self, p_rel_url='', p_internal=False, p_simple=False): return urllib.parse.urlunsplit( (self._config.scheme, "%s:%d" % (self._config.host, self._config.port), join(self._config.base_url, p_rel_url), None, None)) def start_server(self): tools.check_config_value(p_config=self._config, p_config_attribute_name="port") self._process = threading.Thread(target=self.run) self._process.start() time.sleep(1) if self._server_exception is not None: raise self._server_exception self._server_started = True def stop_server(self): if self._server_started and self._flask_stopper is not None: fmt = "Stopping web server %s..." % self._name self._logger.info(fmt) self._flask_stopper.stop(host=self._config.host, port=self._config.port) fmt = "Waiting for the server thread to terminate" self._logger.info(fmt) self._process.join(timeout=3) fmt = "HTTP server '%s' shut down successfully" % self._name self._logger.info(fmt) def run(self): tools.check_config_value(p_config=self._config, p_config_attribute_name="host") fmt = "Starting web server '{name}' on {address}:{port}{base_url}" self._logger.info( fmt.format(name=self._name, address=self._config.host, port=self._config.port, base_url=self._config.base_url)) # See https://stackoverflow.com/questions/14814201/can-i-serve-multiple-clients-using-just-flask-app-run-as-standalone try: self._app.run(port=self._config.port, host=self._config.host, threaded=True) except Exception as e: fmt = "Exception '%s' while starting web server %s" % (str(e), self._name) self._logger.error(fmt) self._server_exception = e raise e @classmethod def get_authentication_info(cls): return { "is_authenticated": flask_login.current_user is not None and flask_login.current_user.is_authenticated, "username": getattr(flask_login.current_user, "username", "NO USER") if flask_login.current_user is not None else "NO USER" }
def create_app(config_name): global user_datastore app = Flask(__name__) app.config.from_object(app_config[config_name]) csrf = CSRFProtect() csrf.init_app(app) assets = Environment(app) create_assets(assets) via = Via() via.init_app(app) # Ipload in several models - - - - from app.user import user_photo from app.restaurant import restaurant_photo from app.food import food_photo configure_uploads(app, (restaurant_photo, food_photo, user_photo)) engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI']) if not database_exists(engine.url): create_database(engine.url) security = Security(app, user_datastore, register_form=SecurityRegisterForm) create_security_admin(app=app, path=os.path.join(os.path.dirname(__file__))) with app.app_context(): db.init_app(app) #Conditionally create admin/end_user db.create_all() user_datastore.find_or_create_role(name='admin', description='Administrator') db.session.commit() user_datastore.find_or_create_role(name='end-user', description='End user') db.session.commit() # Create two Users for testing purposes -- unless they already exists. # In each case, use Flask-Security utility function to encrypt the password. encrypted_password = utils.encrypt_password('password') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password) if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=encrypted_password) # Commit any database changes; the User and Roles must exist before we can add a Role to the User db.session.commit() # Give one User has the "end-user" role, while the other has the "admin" role. (This will have no effect if the # Users already have these Roles.) Again, commit any database changes. user_datastore.add_role_to_user('*****@*****.**', 'end-user') user_datastore.add_role_to_user('*****@*****.**', 'admin') db.session.commit() @app.route('/', methods=['GET']) @app.route('/home', methods=['GET']) def index(): return render_template('index.html') @app.errorhandler(403) def forbidden(error): return render_template('error/403.html', title='Forbidden'), 403 @app.errorhandler(404) def page_not_found(error): return render_template('error/404.html', title='Page Not Found'), 404 @app.errorhandler(500) def internal_server_error(error): db.session.rollback() return render_template('error/500.html', title='Server Error'), 500 return app
def create_app(test_config=None): # create the application instance app = Flask(__name__, static_folder=os.path.join(os.path.dirname(__file__), 'statics')) app.jinja_loader = FileSystemLoader( os.path.join(os.path.dirname(__file__), 'views')) app.config.from_object(__name__) app.config.from_mapping(SECRET_KEY='key secreted', DATABASE=os.path.join(app.instance_path, 'workscheduler.db')) if test_config is None: app.config.from_pyfile('config.py', silent=True) else: app.config.update(test_config) try: os.makedirs(app.instance_path) except OSError: pass app.config.from_envvar('WORK_SCHEDULER_SETTING', silent=True) sys.path.append(os.path.dirname(__file__)) # database action @click.command('init-db') @with_appcontext def init_db_command(): Database(current_app.config['DATABASE']).init() click.echo('Initialized the database.') app.teardown_appcontext(close_db_session) app.cli.add_command(init_db_command) from .controllers import (auths, menus, schedules, operators, users, belongs, skills) app.register_blueprint(auths.bp) app.register_blueprint(menus.bp) app.register_blueprint(schedules.bp) app.register_blueprint(operators.bp) app.register_blueprint(users.bp) app.register_blueprint(belongs.bp) app.register_blueprint(skills.bp) @app.errorhandler(404) def not_found(error): from flask import render_template return render_template('not_found.html'), 404 from flask_login import LoginManager login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'auths.index' @login_manager.user_loader def load_user(user_id): return auths.load_user(user_id) from flask_wtf import CSRFProtect csrf = CSRFProtect() csrf.init_app(app) return app
from flask_login import current_user, login_user, logout_user, UserMixin, LoginManager from flask_wtf import CSRFProtect from application_utils import * from application_database import * from application_secrets import secrets if secrets: # Running on a server ADMIN_USERNAME = secrets.RDS_USERNAME ADMIN_PASSWORD = secrets.RDS_PASSWORD else: ADMIN_USERNAME = '******' ADMIN_PASSWORD = '******' csrf = CSRFProtect() csrf.init_app(application) application.login_manager = LoginManager() @application.login_manager.user_loader def load_user(user_id): user = UserMixin() user.id = user_id return user host_redirect('/pages/login.html', '/login.html') def login():
from flask_migrate import Migrate from flask_wtf import CSRFProtect from flask_babel import Babel app = Flask(__name__) #Nome da aplicação que o arquivo init.py se encontrar #database config #USERNAME = '******' #PASSWORD = '' #SERVER = 'localhost' #DB_NAME = 'flask_db' #app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql://{USERNAME}:{PASSWORD}@{SERVER}/{DB_NAME}' #app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config.from_object('config') #config.py db = SQLAlchemy(app) migrate = Migrate(app, db) #Criando uma instância csrf = CSRFProtect(app) csrf.init_app(app) #Iniciar a garantia de segurança do csrf babel = Babel(app) #Utilizando babel na aplicação #from .views import cliente_view #não refatorado from .views import cliente_view_refact #refatorado from .models import cliente_model #Commands for flask migrate #flask db init #flask db migrate #flask db upgrade
def main(args): server = Flask(__name__) server.config.from_object(DevelopmentConfig) csrf = CSRFProtect() @server.route("/404") @server.errorhandler(404) def error404(error=""): if ("username" in session): return render_template("404.html", username=session["username"]), 404 else: return render_template("404.html"), 404 @server.before_request def beforeRequest(): if ("id" in session and request.endpoint in ["login", "signup"]): return redirect(url_for("index")) @server.route('/') def index(): if ("username" in session): return render_template("stopwatch.html", userrname=session["username"]) else: return render_template("stopwatch.html") @server.route('/login', methods=["GET", "POST"]) def login(): login_form = forms.LoginForm(request.form) if request.method == "POST" and login_form.validate(): username = login_form.username.data password = login_form.password.data user = User.query.filter_by(username=username).first() if user is not None and user.verifyPassword(password): session["id"] = user.id session["username"] = user.username return redirect(url_for("index")) else: flash(u"Usuario o contraseña invalida") return render_template('login.html', form=login_form) @server.route('/signup', methods=["GET", "POST"]) def signup(): signup_form = forms.SignupForm(request.form) if (request.method == "POST" and signup_form.validate()): wcaId = None if (signup_form.wcaId.data != ""): wcaId = signup_form.wcaId.data[1:] user = User( signup_form.username.data, wcaId, signup_form.email.data, signup_form.password.data, ) db.session.add(user) db.session.commit() flash("Usuario registrado exitosamente") return redirect(url_for("login")) return render_template('signup.html', form=signup_form) @server.route('/logout') def logout(): if ("id" in session): session.pop("id") session.pop("username") return redirect(url_for("index")) @server.route('/users/<user>') def users(user): username = None if ("username" in session): username = session["username"] user = User.query.filter_by(username=user).first() if (user == None): return redirect(url_for("error404")) time2 = Time.query.filter_by(user=user.id, cube="2x2x2").all() time3 = Time.query.filter_by(user=user.id, cube="3x3x3").all() time4 = Time.query.filter_by(user=user.id, cube="4x4x4").all() time5 = Time.query.filter_by(user=user.id, cube="5x5x5").all() time6 = Time.query.filter_by(user=user.id, cube="6x6x6").all() time7 = Time.query.filter_by(user=user.id, cube="7x7x7").all() timesqr = Time.query.filter_by(user=user.id, cube="squareone").all() timeskw = Time.query.filter_by(user=user.id, cube="skewb").all() timemega = Time.query.filter_by(user=user.id, cube="megaminx").all() time3pira = Time.query.filter_by(user=user.id, cube="piraminx").all() return render_template("users.html", user=user.username, username=username, t2=time2, t3=time3, t4=time4, t5=time5, t6=time6, t7=time7, tsqr=timesqr, tskw=timeskw, tmega=timemega, tpira=time3pira) @server.route("/records") def records(): if ("username" in session): return render_template("records.html", username=session["username"]) else: return render_template("records.html") @server.route("/galeria") def galeria(): if ("username" in session): return render_template("galeria.html", username=session["username"]) else: return render_template("galeria.html") @server.route("/setTime") def setTime(): if ("username" in session): cube = request.args.get("cube") time = request.args.get("time") displayTime = request.args.get("displayTime") scramble = request.args.get("scramble") newTime = Time(session["id"], cube, time, displayTime, scramble) db.session.add(newTime) db.session.commit() return "Tiempo grabado con exito" else: return "Primero inicia sesion y luego vemos" @server.route('/generateScramble/<cube>', methods=["GET", "POST"]) def generateScramble(cube): if (cube == "2x2x2"): return scrambler222.get_WCA_scramble() elif (cube == "3x3x3"): return scrambler333.get_WCA_scramble() elif (cube == "4x4x4"): return scrambler444.get_WCA_scramble() elif (cube == "5x5x5"): return scrambler555.get_WCA_scramble() elif (cube == "6x6x6"): return scrambler555.get_WCA_scramble() elif (cube == "7x7x7"): return scrambler555.get_WCA_scramble() elif (cube == "piraminx"): return pyraminxScrambler.get_WCA_scramble() elif (cube == "clock"): return clockScrambler.get_WCA_scramble() elif (cube == "megaminx"): return megaminxScrambler.get_WCA_scramble() elif (cube == "squareone"): return squareOneScrambler.get_WCA_scramble() elif (cube == "skewb"): return skewbScrambler.get_WCA_scramble() csrf.init_app(server) db.init_app(server) with server.app_context(): db.create_all() server.run()
def create_app(config_name): global user_datastore, current_rest_api app = Flask(__name__) app.config.from_object(app_config[config_name]) app.logger.setLevel(app.config['LOG_LEVEL']) csrf = CSRFProtect() csrf.init_app(app) CORS(app, resources={r"/api/*": {"origins": "*"}}) assets = Environment(app) create_assets(assets) api_version = "" if 'API_VERSION' in app.config and app.config['API_VERSION'] and \ not str(app.config['API_VERSION']).startswith('/'): api_version = "/" + str(app.config['API_VERSION']) via = Via() via.init_app(app, api_url_prefix='/api' + api_version) # Code for desmostration the flask upload in several models - - - - # from .restaurant import restaurant_photo # from .food import food_photo # configure_uploads(app, (restaurant_photo, food_photo, user_photo)) # engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI']) # if not database_exists(engine.url): # create_database(engine.url) from app.user.forms import SecurityRegisterForm security = Security(app, user_datastore, register_form=SecurityRegisterForm) create_security_admin(app=app, path=os.path.join(os.path.dirname(__file__))) with app.app_context(): db.init_app(app) if DevelopmentConfig.DATABASE_TYPE == EngineType.SQLEngine: db.create_all() user_datastore.find_or_create_role(name='admin', description='Administrator') if DevelopmentConfig.DATABASE_TYPE == EngineType.SQLEngine: db.session.commit() user_datastore.find_or_create_role(name='end-user', description='End user') if DevelopmentConfig.DATABASE_TYPE == EngineType.SQLEngine: db.session.commit() # @app.route('/', methods=['GET']) # @app.route('/home', methods=['GET']) # def index(): # return render_template('index.html') # # @app.errorhandler(403) # def forbidden(error): # return render_template('error/403.html', title='Forbidden'), 403 # # @app.errorhandler(404) # def page_not_found(error): # return render_template('error/404.html', title='Page Not Found'), 404 # # @app.errorhandler(500) # def internal_server_error(error): # db.session.rollback() # return render_template('error/500.html', title='Server Error'), 500 with app.app_context(): if app.config['SCHEDULER_REDIS_HOST']: current_app.scheduler = BackgroundScheduler({ 'apscheduler.jobstores.default': { 'type': 'redis', 'db': 0, 'jobs_key': app.config['SCHEDULER_JOBS_KEY'], 'run_times_key': "{}-runtime".format(app.config['SCHEDULER_JOBS_KEY']), 'host': app.config['SCHEDULER_REDIS_HOST'], 'port': app.config['SCHEDULER_REDIS_PORT'], 'password': app.config['SCHEDULER_REDIS_PASSWD'], }, 'apscheduler.executors.default': { 'class': 'apscheduler.executors.pool:ThreadPoolExecutor', 'max_workers': '20' }, 'apscheduler.executors.processpool': { 'type': 'processpool', 'max_workers': '5' }, 'apscheduler.job_defaults.coalesce': 'true', 'apscheduler.job_defaults.max_instances': '3', 'apscheduler.timezone': 'Asia/Shanghai', }) current_app.scheduler.start() return app
def create_app(config=DevelopmentConfig): app = Flask(__name__) app.jinja_env.filters['zip'] = zip app.jinja_env.filters['len'] = len app.config.from_object(config) login_manager = LoginManager() csrf = CSRFProtect(app) migrate = Migrate(app) login_manager.init_app(app) db.init_app(app) ma.init_app(app) csrf.init_app(app) migrate.init_app(app, db=db) with app.app_context(): db.create_all() app.register_blueprint(swaggerui_blueprint) # register each active blueprint for url, blueprint in ACTIVE_ENDPOINTS: app.register_blueprint(blueprint, url_prefix=url) login_manager.login_view = "userBp.login" def login_required(f): @wraps(f) def wrap(*args, **kwargs): if 'logged_in' in session: return f(*args, **kwargs) else: flash("Primero debes inicicar sesion") return redirect(url_for('userBp.login')) return wrap @app.route("/") def redirect_home(): if current_user.is_anonymous: return redirect(url_for('store.home_page')) else: if str(current_user.id).isalpha(): return redirect(url_for('adminBp.admin_panel')) else: return redirect(url_for('store.home_page')) @login_manager.user_loader def load_user(user_id): if user_id.isdigit(): return User.query.get(int(user_id)) elif user_id.isalpha(): return AdminUser.query.filter_by(id=user_id).first() @app.route("/spec") def spec(): swag = swagger(app) swag['info']['version'] = "1.0" swag['info']['title'] = "CompuTech Store" swag['info']['Description'] = "A cool technology store" swag['tags'] = [{ "name": "store", "description": "only the home page" }, { "name": "products", "description": "Everything related to the handling and presentation of the products " }] return jsonify(swag) return app
from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from os import makedirs flask_app = Flask(__name__) flask_app.config.from_pyfile("config.py", silent=True) try: makedirs(flask_app.instance_path) except OSError: pass db = SQLAlchemy(flask_app) migrate = Migrate(flask_app, db) csrf = CSRFProtect(flask_app) login_manager = LoginManager() csrf.init_app(flask_app) login_manager.init_app(flask_app) from app import models from app.views import auth, dashboard flask_app.register_blueprint(auth.bp) flask_app.register_blueprint(dashboard.bp) @flask_app.route("/") def index(): return redirect(url_for("auth.login"))
def main(argv): try: from decoder_scg import DecodeStruct decoderSCG = DecodeStruct.getInstance( ) # Classe di decodifica Enumerati e Failure Bits Enum opts, args = getopt.getopt( argv, "i:rs:s:n:t", ["ifile=", "routeonserial=", "serial", "num_serial=", "tcp"]) usage = 'decoderNMEA.py [-i <inputfile>|-r <inputfile> | -s|-n=1|-t]' file = None serial = False routeonserial = None n_serial = 1 tcp_mode = None for opt, arg in opts: if opt in ('-i',"--ifile") and "-s" not in opts and "--serial" not in opts \ and "-rs" not in opts and "--routeonserial" not in opts: file = arg elif opt in ("-s", "--serial") and "-i" not in opts and "--ifile" not in opts \ and "-rs" not in opts and "--routeonserial" not in opts: serial = True elif opt in ("-t", "--tcp_mode"): tcp_mode = arg elif opt in ("-n", "--num_serial"): n_serial = arg elif opt in ("-rs","--routeonserial") and ("-i" in opts or "--ifile" in opts) \ and "-s" not in opts and "--serial" not in opts: routeonserial = arg else: print(usage) sys.exit(2) manager = manageUDP.read_udp(configFile, ["UDP"]) manageFlask.api.add_resource(manageFlask.Server, "/") Bootstrap(manageFlask.app) SECRET_KEY = os.urandom(32) manageFlask.app.config['SECRET_KEY'] = SECRET_KEY csrf = CSRFProtect() csrf.init_app(manageFlask.app) server = WSGIServer((http_server, http_port), manageFlask.app) if serial and not file and not routeonserial: for i in range(n_serial): thread = threading.Thread( target=serial_read, args=(ReadSerial, configFile, ["SERIAL PORT CONFIGURATION" + str(i + 1)], i + 1), ) thread.start() if not serial and file and not routeonserial: #ReadFile("config.ini",["FILE SIMULATOR CONFIGURATION"]) ReadFile(file, "SERIAL PORT CONFIGURATION1").start() if not serial and not file and routeonserial: #ReadFile("config.ini",["FILE SIMULATOR CONFIGURATION"]) ReadFile(routeonserial, "SERIAL PORT CONFIGURATION1", True).start() if tcp_mode is not None: tcpManager = TCPManager(configFile, ["TCP"]) print("Start gevent WSGI server") manageFlask.sock.run(manageFlask.app) server.serve_forever() except getopt.GetoptError: print(usage) sys.exit(2)
import logging app = flask.Flask(__name__) app.config['SECRET_KEY'] = 'hard to guess string' app.jinja_env.globals['ADMIN_USERS'] = ('*****@*****.**') try: logging.basicConfig( filename='log_web_app.log', format='[|%(asctime)s| - %(name)s - %(levelname)s] - %(message)s', level=logging.INFO) logging.info('\n') logging.info('|--------------------|') logging.info('|INICIO DE LA WEB APP|') logging.info('| - Jorge Gomez - |') logging.info('|--------------------|') logging.info('Inicio de la aplicacion') except Exception as ex: logging.warning('Fallo en la conexion: ' + ex) app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True csrf = CSRFProtect(app) csrf.init_app(app) Bootstrap(app) db = SQLAlchemy(app) db.init_app(app) with app.app_context(): db.create_all()
def create_app(): app = Flask( __name__ ) # this is the name of the module/package that is calling this app app.debug = True app.secret_key = 'pineapples' #set the app configuration data #the folder to store images UPLOAD_FOLDER = '/static/img' app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER #Disable security due to CSRF token bug app.config['WTF_CSRF_ENABLED'] = False app.config['WTF_CSRF_SECRET_KEY'] = 'pineapples' csrf = CSRFProtect() csrf.init_app(app) #app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///marketplace.sqlite' app.config.from_mapping( # #Flask SQLAlchemy settings SQLALCHEMY_DATABASE_URI=os.environ['DATABASE_URL'], ) #initialize db with flask app db.init_app(app) ctx = app.app_context() ctx.push() db.create_all() bootstrap = Bootstrap(app) #initialize the login manager login_manager = LoginManager() #set the name of the login function that lets user login # in our case it is auth.login (blueprintname.viewfunction name) login_manager.login_view = 'auth.authenticate' login_manager.init_app(app) #create a user loader function takes userid and returns User #from .models import User # importing here to avoid circular references @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) @login_manager.unauthorized_handler def unauthorized(): return redirect(url_for('auth.authenticate')) login_manager.session_protection = 'basic' #importing views module here to avoid circular references # a commonly used practice. from . import views app.register_blueprint(views.bp) from . import products app.register_blueprint(products.bp) from . import auth app.register_blueprint(auth.bp) #Define global variables for access inside jinja templates app.jinja_env.globals.update(ProductType=ProductType) app.jinja_env.globals.update(SubTypes=SubTypes) #Error handling returns set pages @app.errorhandler(404) def not_found_error(error): return render_template('404.html'), 404 @app.errorhandler(400) def bad_request_error(error): return render_template('400.html'), 400 @app.errorhandler(500) def internal_error(error): return render_template('500.html'), 500 return app