Example #1
1
def get_app():
    app = Flask("kardboard")
    app.config.from_object("kardboard.default_settings")
    if os.getenv("KARDBOARD_SETTINGS", None):
        app.config.from_envvar("KARDBOARD_SETTINGS")

    app.secret_key = app.config["SECRET_KEY"]

    app.db = PortAwareMongoEngine(app)

    app.jinja_env.add_extension("kardboard.util.Markdown2Extension")
    app.jinja_env.filters["slugify"] = slugify
    app.jinja_env.filters["timesince"] = timesince

    configure_logging(app)

    try:
        from flaskext.exceptional import Exceptional
    except ImportError:
        pass
    exceptional_key = app.config.get("EXCEPTIONAL_API_KEY", "")
    if exceptional_key:
        exceptional = Exceptional(app)
        app._exceptional = exceptional

    return app
Example #2
1
def create_app(config="CTFd.config"):
    app = Flask("CTFd")
    with app.app_context():
        app.config.from_object(config)

        from CTFd.models import db, Teams, Solves, Challenges, WrongKeys, Keys, Tags, Files, Tracking

        db.init_app(app)
        db.create_all()

        app.db = db

        global mail
        mail = Mail(app)

        Session(app)

        from CTFd.views import views
        from CTFd.challenges import challenges
        from CTFd.scoreboard import scoreboard
        from CTFd.auth import auth
        from CTFd.admin import admin
        from CTFd.utils import init_utils, init_errors, init_logs

        init_utils(app)
        init_errors(app)
        init_logs(app)

        app.register_blueprint(views)
        app.register_blueprint(challenges)
        app.register_blueprint(scoreboard)
        app.register_blueprint(auth)
        app.register_blueprint(admin)

        return app
Example #3
1
def get_app():
    app = Flask("flask_seed")
    app.config.from_object("default_settings")
    if os.getenv("FLASK_SEED_SETTINGS", None):
        app.config.from_envvar("FLASK_SEED_SETTINGS")

    app.secret_key = app.config["SECRET_KEY"]

    # app.g  = globals.load()
    app.db = MongoEngine(app)

    app.jinja_env.add_extension("util.Markdown2Extension")
    app.jinja_env.filters["slugify"] = slugify
    app.jinja_env.filters["timesince"] = timesince
    app.jinja_env.filters["timeuntil"] = timeuntil
    app.jinja_env.filters["jsonencode"] = jsonencode
    app.jinja_env.globals["newrelic_head"] = newrelic_head
    app.jinja_env.globals["newrelic_foot"] = newrelic_foot

    if not app.config.get("TEMPLATE_DEBUG", True):
        compiled_templates = os.path.join(os.path.abspath(os.path.dirname(__file__)), "compiled_templates")
        compiled_files = path.path(compiled_templates).files()
        if len(compiled_files) <= 1:
            app.jinja_env.compile_templates(compiled_templates, zip=None, py_compile=True)
        app.jinja_env.loader = ModuleLoader(compiled_templates)

    return app
 def create_app(self):
     """ Set up an app object with testing config """
     app = Flask(__name__)
     app.config.from_object("config")
     db.init_app(app)
     app.db = db
     return app
Example #5
1
def init_app(db_name=None):
    """Initialize the app.

    Because the database name has to be set before the app inits,
    we allow it to be passed in outside of configs, because we can't
    set it on app.config['DATABASE'] before we actually have an app.

    This is mainly for testing, because it could be set via env vars,
    but we don't want the test to override any env vars that are already set.
    """

    # create a Flask app, force SSL when debug is False
    app = Flask(__name__, static_folder="./ui/static")
    app.config.from_pyfile("config.py")

    # load custom config file
    custom_config = app.config["CUSTOM_CONFIG_PATH"]
    if os.environ.get(custom_config) is not None:
        app.config.from_envvar(custom_config)

    # setup
    app.db = db.connect(db_name)
    setup_auth(app)
    SSLify(app, subdomains=True)

    # register blueprints
    app.register_blueprint(api, url_prefix="/api")
    app.register_blueprint(auth)
    app.register_blueprint(ui)

    return app
Example #6
1
def create_app(__name__=__name__):
    app = Flask(__name__)
    try:
        app.config.from_pyfile(CONFIG_FILEPATH)
    except IOError:
        pass
    auto_register_modules(app)
    app.db = SQLAlchemy(app)
    return app
Example #7
0
def create_app(set_config=set_config):
    app = Flask(__name__)
    set_config(app)

    db.init_app(app)
    app.db = db

    register_uris(app)

    return app
Example #8
0
def create_app(subdomain="", username="", password=""):
    app = Flask("CTFd", static_folder="../static", template_folder="../templates")
    with app.app_context():
        app.config.from_object("CTFd.config")

        if subdomain:
            app.config.update(
                SQLALCHEMY_DATABASE_URI="mysql://"
                + username
                + ":"
                + password
                + "@localhost:3306/"
                + subdomain
                + "_ctfd",
                HOST=subdomain + app.config["HOST"],
                SESSION_FILE_DIR=app.config["SESSION_FILE_DIR"] + "/" + subdomain,
                DEBUG=True,
            )

        from CTFd.models import db, Teams, Solves, Challenges, WrongKeys, Keys, Tags, Files, Tracking

        db.init_app(app)
        db.create_all()

        app.db = db
        # app.setup = True

        global mail
        mail = Mail(app)

        Session(app)

        from CTFd.views import init_views

        init_views(app)
        from CTFd.errors import init_errors

        init_errors(app)
        from CTFd.challenges import init_challenges

        init_challenges(app)
        from CTFd.scoreboard import init_scoreboard

        init_scoreboard(app)
        from CTFd.auth import init_auth

        init_auth(app)
        from CTFd.admin import init_admin

        init_admin(app)
        from CTFd.utils import init_utils

        init_utils(app)

        return app
Example #9
0
def create_app(set_config=set_config):
    app = Flask(__name__)
    set_config(app)

    db.init_app(app)
    app.db = db

    register_uris(app)

    app.response_class = ApiResponse

    return app
Example #10
0
def create_app(cmdline=False, test_config=None):
    blueprints = get_blueprints()

    app = Flask(__name__)
    if test_config:
        app.config.update(**test_config)
    else:
        app.config.from_envvar("RELENGAPI_SETTINGS")

    # add the necessary components to the app
    app.db = db.make_db(app)
    app.celery = celery.make_celery(app)
    relengapi.principal.init_app(app)
    relengapi.login_manager.init_app(app)
    api.init_app(app)

    for name, bp in blueprints:
        if cmdline:
            logger.info(" * registering blueprint %s", name)
        app.register_blueprint(bp, url_prefix="/%s" % name)

    # set up a random session key if none is specified
    if not app.config.get("SECRET_KEY"):
        logger.warning(" * setting per-process session key - sessions will be reset on " "process restart")
        app.secret_key = os.urandom(24)

    @app.before_request
    def add_db():
        g.db = app.db

    @app.route("/")
    def root():
        # render all of the blueprints' templates first
        bp_widgets = []
        for bp in app.blueprints.itervalues():
            bp_widgets.extend(bp.root_widget_templates or [])
        bp_widgets.sort()
        bp_widgets = [tpl for (_, tpl, condition) in bp_widgets if not condition or condition()]
        return render_template("root.html", bp_widgets=bp_widgets)

    @app.route("/versions")
    @api.apimethod()
    def versions():
        dists = {}
        for dist in pkg_resources.WorkingSet():
            dists[dist.key] = {"project_name": dist.project_name, "version": dist.version}
        blueprints = {}
        for ep in pkg_resources.iter_entry_points("relengapi_blueprints"):
            blueprints[ep.name] = {"distribution": ep.dist.key, "version": ep.dist.version}
        return dict(distributions=dists, blueprints=blueprints)

    return app
Example #11
0
def get_app():
    app = Flask("breezeminder")

    settings_file = os.environ.get("BREEZEMINDER_SETTINGS", "breezeminder.settings.local")
    app.config.from_object(settings_file)
    app.config["BREEZEMINDER_ENV"] = settings_file.split(".")[-1].upper()
    app.config["SHOW_ADS"] = app.config.get("ADSENSE_CLIENT", None) is not None

    app.secret_key = app.config["SECRET_KEY"]

    app.db = PortAwareMongoEngine(app)

    logger.configure_logging(app)
    return app
Example #12
0
def create_app(app_name, config):

    app = Flask(app_name)
    app.config.from_object(config)

    app.db = SQLAlchemy(app)

    app.migrate = Migrate(app, app.db)

    app.bcrypt = Bcrypt(app)

    app.api = Api(app, prefix="/api/v1")

    app.api_registry = []

    return app
Example #13
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config.get(config_name, "default"))

    # Create database with the config settings
    app.db = create_db(app)

    from .api import api1_0 as api1_0_blueprint

    app.register_blueprint(api1_0_blueprint, url_prefix="/api/v1_0")

    from .api import login_blueprint

    app.register_blueprint(login_blueprint, url_prefix="")

    return app
Example #14
0
def get_app():
    app = Flask("kardboard")
    app.config.from_object("kardboard.default_settings")
    if os.getenv("KARDBOARD_SETTINGS", None):
        app.config.from_envvar("KARDBOARD_SETTINGS")

    app.secret_key = app.config["SECRET_KEY"]

    app.db = MongoEngine(app)

    app.jinja_env.add_extension("kardboard.util.Markdown2Extension")
    app.jinja_env.filters["slugify"] = slugify
    app.jinja_env.filters["timesince"] = timesince
    app.jinja_env.filters["timeuntil"] = timeuntil
    app.jinja_env.filters["jsonencode"] = jsonencode
    app.jinja_env.globals["newrelic_head"] = newrelic_head
    app.jinja_env.globals["newrelic_foot"] = newrelic_foot

    if app.config.get("COMPILE_TEMPLATES", False):
        compiled_templates = os.path.join(os.path.abspath(os.path.dirname(__file__)), "compiled_templates")
        compiled_files = path.path(compiled_templates).files()
        if len(compiled_files) <= 1:
            app.jinja_env.compile_templates(compiled_templates, zip=None, py_compile=True)
        app.jinja_env.loader = ModuleLoader(compiled_templates)

    configure_logging(app)

    app.wsgi_app = FixGunicorn(app.wsgi_app)

    statsd_conf = app.config.get("STATSD_CONF", {})

    statsd_connection = statsd.Connection(
        host=statsd_conf.get("host", "127.0.0.1"),
        port=statsd_conf.get("port", 8125),
        sample_rate=statsd_conf.get("sample_rate", 1),
    )

    machine_name = socket.getfqdn().split(".")[0]
    environment_name = app.config.get("ENV_MAPPING", {}).get(machine_name, "default")
    prefix_name = "%s.%s.kardboard" % (environment_name, machine_name)
    app.statsd = statsd.Client(prefix_name, statsd_connection)

    if SENTRY_SUPPORT and "SENTRY_DSN" in app.config.keys():
        sentry = Sentry(app)
        sentry

    return app
Example #15
0
def create_app(config_file):
    app = Flask(__name__)

    # configuration settings are loaded from the `config.py` module
    # and (optionally) from a file `XSNIPPET_API_SETTINGS` env var points to
    app.config.from_pyfile(config_file)
    app.config.from_envvar("XSNIPPET_API_SETTINGS", silent=True)

    app.register_blueprint(api)

    # create a database connection (it's thread-safe, so we can keep it global)
    app.db = create_db_connection(app)

    # create a cache connection (it's thread-safe too)
    app.cache = create_cache_connection(app, key_prefix="api_")

    return app
Example #16
0
def create_app(**kwargs):
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"
    app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", "devkey")

    from .models import db

    for k, v in kwargs.items():
        app.config[k] = v

    db.init_app(app)

    app.db = db

    from .views import users, shop

    app.register_blueprint(users.bp, url_prefix="/user")
    app.register_blueprint(shop.bp, url_prefix="/shop")

    return app
Example #17
0
def create_app(subdomain="", config=None):
    app = Flask(__name__)
    load_config(app, subdomain=subdomain, config=config)
    # if app.config.get('HEROKU'):
    # heroku.init_app(app)
    if app.config["ENABLE_NEO4J"]:
        init_graph(app)
    else:
        app.graph = None
    if app.config["ENABLE_SQL"]:
        db.init_app(app)
    else:
        app.db = None
    if app.config.get("LOGGING"):
        attach_loggers(app)
    app.session_interface = JSONSecureCookieSessionInterface()
    register_blueprints(app)
    attach_before_request_handlers(app)
    inject_context_processors(app)
    return app
Example #18
0
def create_app():
    global app
    app = Flask(__name__)
    app.config.from_object("config")

    import views

    global db
    db.init_app(app)
    app.db = db

    global login_manager
    login_manager.login_view = "login"
    login_manager.init_app(app)

    import models

    if int(os.environ.get("DEBUG_TOOLBAR", 1)) == 1:
        DebugToolbarExtension(app)

    return app
Example #19
0
def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)

    CsrfProtect(app)

    # Register extensions
    for ext in all_extensions:
        # print(ext)
        ext.init_app(app)
    # Add DB resource to app object for use later.
    app.db = db

    # Creates DB if it doesn't exist. Comment out to avoid checking every time.
    if not os.path.exists(app.config["DBFILE_PATH"]):
        print("Need to create {} at {}".format(app.config["DB_NAME"], app.config["APP_DIR"]))

        @app.before_first_request
        def initialize_database():
            print("Creating {} at {}".format(app.config["DB_NAME"], app.config["APP_DIR"]))
            db.create_all()
            from baseapp.controllers.user.models import User

            user = User(username="admin", email="gaulinmp@gmail.com", password="admin", active=True, admin=True)
            user.save()
            from baseapp.controllers.logger.models import LogProject

            p = LogProject(id=0, name="Default")
            p.save()

    # Register blueprints
    app.register_blueprint(logger.views.blueprint)
    logger.views.blueprint.extra_init(app)
    app.register_blueprint(user.views.blueprint)

    app.logger.setLevel(logging.WARNING)

    register_errorhandlers(app)

    return app
Example #20
0
def create_app(config="CTFd.config"):
    app = Flask("CTFd")
    with app.app_context():
        app.config.from_object(config)

        from CTFd.models import db, Teams, Solves, Challenges, WrongKeys, Keys, Tags, Files, Tracking

        ## sqlite database creation is relative to the script which causes issues with serve.py
        if not database_exists(app.config["SQLALCHEMY_DATABASE_URI"]) and not app.config[
            "SQLALCHEMY_DATABASE_URI"
        ].startswith("sqlite"):
            create_database(app.config["SQLALCHEMY_DATABASE_URI"])

        db.init_app(app)
        db.create_all()

        app.db = db

        # Session(app)

        from CTFd.views import views
        from CTFd.challenges import challenges
        from CTFd.scoreboard import scoreboard
        from CTFd.auth import auth
        from CTFd.admin import admin
        from CTFd.utils import init_utils, init_errors, init_logs

        init_utils(app)
        init_errors(app)
        init_logs(app)

        app.register_blueprint(views)
        app.register_blueprint(challenges)
        app.register_blueprint(scoreboard)
        app.register_blueprint(auth)
        app.register_blueprint(admin)

        return app
Example #21
0
def create_app(app_dir):
    app = Flask(__name__)
    load_config(app, __name__, app_dir)

    app.register_blueprint(version, url_prefix="/version")
    app.register_blueprint(platform, url_prefix="/platform")
    app.register_blueprint(parameter, url_prefix="/parameter")
    app.register_blueprint(sensor, url_prefix="/sensor")
    app.register_blueprint(phenomena, url_prefix="/phenomena")
    app.register_blueprint(flag, url_prefix="/flag")
    app.register_blueprint(ui, url_prefix="")

    # database
    app.system = mysql.Mysql()
    app.db = SQLAlchemy(app)
    app.system.session = app.db.session

    # general stuff - error pages etc
    app.errorhandler(404)(not_found_error)
    app.errorhandler(408)(conflict_error)
    app.errorhandler(500)(internal_error)

    return app
Example #22
0
def setup():
    """Setup function for tests."""
    # global variable shouldn't be used but is quite useful here
    # pylint: disable=W0603
    global TEMP_DIR
    TEMP_DIR = mkdtemp()
    if not os.path.exists(FAKE_DIR):
        os.mkdir(FAKE_DIR)
        Git(os.path.join(FAKE_DIR, "documents.git")).init()
    app = Flask(__name__, static_folder=os.path.join(PATH, "static"), template_folder=os.path.join(PATH, "templates"))
    app.config.from_object(config)
    app.db = SQLAlchemy(app)
    nuts = application.Koztumize(app)
    application.app = app
    application.nuts = nuts
    app.config["MODELS"] = os.path.join(TEMP_DIR, "models")
    git = Git(app.config["MODELS"])
    git.init()
    git.remote("add", "-t", "models", "origin", app.config["GIT_REMOTE"])
    git.pull()
    git.checkout("models")
    execute_sql(app, "db.sql")
    import koztumize.routes
    import koztumize.tests.document
Example #23
0
def create_app(configuration_file=None):
    app = Flask(__name__)
    app.plugins = []

    # cannot use namespace here, weak signals will disappear
    app.plugin_signals = {
        "plugin-loaded": Signal(),
        "page-loaded": Signal(),
        "special-loaded": Signal(),
        "page-preprocess": Signal(),
        "page-postmarkdown": Signal(),
        "page-treeprocess": Signal(),
        "page-postprocess": Signal(),
    }

    # load a default config, and from configuration file
    app.config.from_object(defaults)
    if configuration_file:
        app.config.from_pyfile(configuration_file)

    app.db = WikiDb(app.config["REPOSITORY_PATH"])
    app.cache = Cache(app)

    app.register_module(frontend)

    # load plugins
    for plugin_name in app.config["PLUGINS"]:
        import_name = "qwappplugin.%s" % plugin_name

        qwappplugin = __import__("qwappplugin.%s" % plugin_name)
        plugin_module = getattr(qwappplugin, plugin_name)
        app.logger.debug("loading plugin %s" % plugin_module.plugin.version_string)

        plugin_module.plugin.register_app(app)

    return app
from flask import Flask, request, make_response, jsonify
from flask_restful import Resource, Api
from pymongo import MongoClient
from bson.objectid import ObjectId
from utils.mongo_json_encoder import JSONEncoder
import bcrypt
from functools import wraps
import datetime

# Basic Setup
app = Flask(__name__)
# MONGO_URL = os.environ.get('MONGOHQ_URL')
mongo = MongoClient("localhost", 27017)
app.db = mongo.develop_database
# app.db = mongo.app42721996
api = Api(app)
BCRYPT_ROUNDS = 12


def check_auth(username, password):
    if username is None or password is None:
        return False
    else:
        #  Get user from database
        myuser_collection = app.db.users
        my_user = myuser_collection.find_one({"username": username})
        if my_user is None:
            return False
        db_password = my_user["password"]
        password = str.encode(password)
        db_password = str.encode(db_password)
Example #25
0
def create_app(test_config=None):  # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app = Flask(__name__)
    app.config.from_object(__name__ + ".ConfigClass")

    # Load local_settings.py if file exists         # For automated tests
    try:
        app.config.from_object("local_settings")
    except:
        pass

    # Load optional test_config                     # For automated tests
    if test_config:
        app.config.update(test_config)

    # Initialize Flask extensions
    db = SQLAlchemy(app)  # Initialize Flask-SQLAlchemy
    babel = Babel(app)  # Initialize Flask-Babel
    mail = Mail(app)  # Initialize Flask-Mail

    # Define the User data model. Make sure to add flask.ext.user UserMixin!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)

        # User authentication information
        username = db.Column(db.String(50), nullable=True, unique=True)
        password = db.Column(db.String(255), nullable=False, server_default="")
        reset_password_token = db.Column(db.String(100), nullable=False, server_default="")

        # User email information
        email = db.Column(db.String(255), nullable=True, unique=True)
        confirmed_at = db.Column(db.DateTime())

        # User information
        active = db.Column("is_active", db.Boolean(), nullable=False, server_default="0")
        first_name = db.Column(db.String(100), nullable=False, server_default="")
        last_name = db.Column(db.String(100), nullable=False, server_default="")

        # Relationships
        roles = db.relationship("Role", secondary="user_roles", backref=db.backref("users", lazy="dynamic"))

    # Define UserEmail DataModel.
    class UserEmail(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        user_id = db.Column(db.Integer, db.ForeignKey("user.id"))

        # User email information
        email = db.Column(db.String(255), nullable=True, unique=True)
        confirmed_at = db.Column(db.DateTime())
        is_primary = db.Column(db.Boolean(), nullable=False, default=False)

        # Relationship
        user = db.relationship("User", uselist=False)

    # Define the Role data model
    class Role(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        name = db.Column(db.String(50), unique=True)

    # Define the UserRoles data model
    class UserRoles(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        user_id = db.Column(db.Integer(), db.ForeignKey("user.id", ondelete="CASCADE"))
        role_id = db.Column(db.Integer(), db.ForeignKey("role.id", ondelete="CASCADE"))

    # Reset all the database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db, User)
    user_manager = UserManager(db_adapter, app)

    # Create regular 'member' user
    if not User.query.filter(User.username == "member").first():
        user = User(
            username="member", email="member@example.com", active=True, password=user_manager.hash_password("Password1")
        )
        db.session.add(user)
        db.session.commit()

    # Create 'user007' user with 'secret' and 'agent' roles
    if not User.query.filter(User.username == "user007").first():
        user1 = User(
            username="user007",
            email="user007@example.com",
            active=True,
            password=user_manager.hash_password("Password1"),
        )
        user1.roles.append(Role(name="secret"))
        user1.roles.append(Role(name="agent"))
        db.session.add(user1)
        db.session.commit()

    # The '/' page is accessible to anyone
    @app.route("/")
    def home_page():
        # if current_user.is_authenticated():
        #     return user_profile_page()
        return render_template_string(
            """
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Home Page{%endtrans%}</h2>
            <p><a href="{{ url_for('user.login') }}">{%trans%}Sign in{%endtrans%}</a></p>
            {% endblock %}
            """
        )

    # The '/profile' page requires a logged-in user
    @app.route("/user/profile")
    @login_required  # Use of @login_required decorator
    @confirm_email_required
    def user_profile_page():
        return render_template_string(
            """
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Profile Page{%endtrans%}</h2>
            <p> {%trans%}Hello{%endtrans%}
                {{ current_user.username or current_user.email }},</p>
            <p> <a href="{{ url_for('user.change_username') }}">
                {%trans%}Change username{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.change_password') }}">
                {%trans%}Change password{%endtrans%}</a></p>
            <p> <a href="{{ url_for('user.logout') }}?next={{ url_for('user.login') }}">
                {%trans%}Sign out{%endtrans%}</a></p>
            {% endblock %}
            """
        )

    # The '/special' page requires a user that has the 'special' AND ('sauce' OR 'agent') role.
    @app.route("/special")
    @roles_required("secret", ["sauce", "agent"])  # Use of @roles_required decorator
    def special_page():
        return render_template_string(
            """
            {% extends "base.html" %}
            {% block content %}
            <h2>{%trans%}Special Page{%endtrans%}</h2>
            {% endblock %}
            """
        )

    # For testing only
    app.db = db
    app.UserEmailClass = UserEmail

    return app
Example #26
0
    """ Forms HTTP path for view functions
    """
    return root_view + "/" + name_html


URL_update_test = url_view("update_test")
URL = url_view("calc1")
URL_update = url_view("update")


# Flask initialisation
app = Flask(__name__)
app.config.from_pyfile("app.cfg")

# SqlAlchemy  initialisation
app.db = db
db.init_app(app)


def fix_currency(currency, errors, db_rates):
    """
    """
    if not currency:
        return "RUR"  # default currency
    if currency not in db_rates:
        errors.append("Currency {} doesn't exist".format(currency))
        return "RUR"  # default currency
    return currency


# View forms
 def create_app(self):
     app = Flask(__name__)
     app.config.from_object("config")
     db.init_app(app)
     app.db = db
     return app
Example #28
0
import logging
from pymongo import MongoClient

logging.basicConfig(
    level=logging.DEBUG,
    format="[%(asctime)s] %(process)d.%(name)s.%(levelname)s: %(message)s",
    filename="run_engine.log",
    filemode="a",
)
log = logging.getLogger()
log.setLevel(logging.DEBUG)


search = Flask(__name__, static_folder="search_engine/static", template_folder="search_engine/templates")
search.dbconnection = MongoClient("localhost", 27017)
search.db = search.dbconnection["placebo"]
search.db["queries"].remove()
search.last_queries = search.db["queries"]
search.text_sn = search.db["text_for_snippets"]
search.rindex = get_index("rindex.pkl", search.text_sn)
search.synonyms = load_synonyms()


@search.route("/")
def index():
    rindex = search.rindex
    synoms = search.synonyms
    query = request.args.get("q", "").strip().lower().strip()
    page = int(request.args.get("p", "1"))
    if page < 1:
        page = 1
Example #29
0
from flask import Flask
from wtforms import TextField, IntegerField
from wtforms.validators import Required
from flask_sqlalchemy import SQLAlchemy

from pynuts import Pynuts
from pynuts.view import BaseForm


# The application
CONFIG = {"WTF_CSRF_ENABLED": False, "SQLALCHEMY_DATABASE_URI": "sqlite:////tmp/test.db"}

app = Flask(__name__)
app.config.update(CONFIG)
app.db = SQLAlchemy(app)
nuts = Pynuts(app)


# The database
class Employee(app.db.Model):
    __tablename__ = "Employee"
    id = app.db.Column(app.db.Integer(), primary_key=True)
    name = app.db.Column(app.db.String())


# The view
class EmployeeView(nuts.ModelView):
    model = Employee
    list_column = "name"

    class Form(BaseForm):
Example #30
0
        users = app.db["users"].find()
        return render_template("users.html", users=users)
    elif request.method == "POST":
        name = request.form.get("name", "")
        full_name = request.form.get("full_name", "")
        skills = request.form.get("skills", "")
        position = request.form.get("position", "")
        photo = request.form.get("photo", "")
        password = request.form.get("password", "")
        new_user = {
            "name": name,
            "full_name": full_name,
            "skills": skills,
            "position": position,
            "photo": photo,
            "password": password,
        }
        # app.db['users'][name] = new_user
        app.db["users"].insert(new_user)
        return redirect("/users/%s" % name)
    else:
        raise RuntimeError("Only POST and GET methods are supported")


if __name__ == "__main__":

    app.db = MongoClient("wardoctor.nosoc.io", port=443)[DATABASE_NAME]
    login_system.init_login_system(app)
    app.run(debug=True)

    # style="background-image:url(https://pp.vk.me/c618426/v618426104/12476/CtRpXTwpsKk.jpg)"