Exemple #1
0
def create_app():
    app.config.from_object(__name__)
    # uri统一资源匹配符
    # SQLALCHEMY_DATABASE_URI配置数据库连接的参数

    Bootstrap(app)
    api = Api()
    api.init_app(app)
    db.init_app(app)
    ST.SERVERSTATICROOT = os.path.join(app.root_path, 'static')

    @app.cli.command("initdb")
    def initdb_command():
        db.drop_all()
        db.create_all()
        res = seeds()
        print(f"db create initialized")

    @app.cli.command("create-user")
    @click.argument("username", default="admin")
    @click.argument("password", default="admin")
    def create_user(username: str, password: str):
        adduser(username, password)

    @app.cli.command("search_user")
    @click.argument("user_id", default=1)
    def search(user_id):
        search_user_info(user_id)

    app.register_blueprint(frontend)
    return app
Exemple #2
0
def create_app(config='config.ProductionConfig'):
    app = Flask(__name__)
    app.config.from_object(config)
    app.config.from_envvar('FLASK_APP_SETTINGS', silent=True)
    app.register_blueprint(api)
    db.init_app(app)
    return app
Exemple #3
0
def create_app():
    app = Flask(__name__, instance_relative_config=True)
    app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['REDIS_URL'] = REDIS_URL
    app.config['SECRET_KEY'] = '123'
    app.app_context().push()

    db.init_app(app)
    db.create_all()

    redis_client.init_app(app)

    login_manager.init_app(app)
    Bootstrap(app)

    from core import auth
    app.register_blueprint(auth.bp)

    from core import message
    app.register_blueprint(message.bp)

    @app.route('/')
    def index():
        return redirect(url_for('auth.register'))

    return app
Exemple #4
0
def create_app(config='config.ProductionConfig'):
    """
    Creates the app object, infers its configuration and connects it to the database.

    :param config: a string or a object representing the default configuration
    :return: the Flask app object
    """
    app = Flask(__name__)
    # Loads the default configuration
    app.config.from_object(config)
    # Overwrites defaults with a file specified in the SAMPLE_FLASK_APP_SETTINGS environment variable
    app.config.from_envvar('SAMPLE_FLASK_APP_SETTINGS', silent=True)
    # Registers the blueprint related to the APIs
    app.register_blueprint(api)
    # Connects to the database
    db.init_app(app)
    return app
Exemple #5
0
def before_first_request():
    from flask import current_app
    from core.server.apis.common.response import BaseResponse

    from core.models import db
    from core.models.mongos import mongo_init_app
    from core.server.apis.common.exceptions import init_error_handler

    print("before_first_request")
    current_app.response_class = BaseResponse

    print("before_first_request >> db_init")
    db.init_app(current_app)
    db.create_all()

    print("before_first_request >> mongo_init")
    mongo_init_app(current_app)

    print("before_first_request >> init_error_handler")
    init_error_handler(current_app)
Exemple #6
0
def create_app(object_name):
    app = Flask(__name__)
    app.config.from_object(object_name)

    CORS(app, resources={r"/api/*": {"origins": "*"}})
    db.init_app(app)
    bcrypt.init_app(app)
    login_manager.init_app(app)

    rest_api.add_resource(ProductApi,
                          '/api/1/product',
                          '/api/1/product/<int:product_id>',
                          endpoint='product')

    rest_api.add_resource(ProductSkuApi,
                          '/api/1/sku',
                          '/api/1/sku/<int:sku_id>',
                          endpoint='sku')

    rest_api.add_resource(CategoryApi,
                          '/api/1/category',
                          '/api/1/category/<int:category_id>',
                          endpoint='category')

    rest_api.add_resource(CreateUserApi,
                          '/api/1/auth/create',
                          endpoint='auth_create')

    rest_api.add_resource(
        AuthApi,
        '/api/1/auth',
        endpoint='auth',
    )

    rest_api.init_app(app)

    return app
Exemple #7
0
oidc = OpenIDConnect(app)
login_manager = LoginManager(app)
bcrypt = Bcrypt(app)
logger = Logger().get_logger()


def oidc_loggedin():
    return oidc.user_loggedin


def oidc_isAdmin():
    if oidc_loggedin():
        isAdmin = oidc.user_getfield("isAdmin")
        if isAdmin == "yes":
            return True
    return False


app.jinja_env.globals['oidc_loggedin'] = oidc_loggedin
app.jinja_env.globals['oidc_isAdmin'] = oidc_isAdmin
app.jinja_env.globals['TITLE'] = app.config["TITLE"]

from core.models import db, User, Favorites
db.init_app(app)
with app.app_context():
    db.create_all()

from core.forms import RegisterForm, LoginForm
from core import routes
Exemple #8
0
def create_app(config_class=Config):
    """Create Flask app with some extensions"""
    app = Flask(__name__)
    app.config.from_object(config_class)

    # elasticsearch
    app.elasticsearch = (Elasticsearch([app.config["ELASTICSEARCH_URL"]])
                         if app.config["ELASTICSEARCH_URL"] else None)

    # init all extensions with flask app
    # first import from models
    from core.models import (
        db,
        User,
        Product,
        Category,
        Order,
        Role,
        SaleTransaction,
        OrderedProduct,
    )

    # init db
    db.init_app(app)

    # setup security
    # user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    # security = Security(app, user_datastore)

    # init other extensions
    login_manager.init_app(app)
    mail.init_app(app)

    # babel
    babel.init_app(app)
    # @babel.localeselector
    # def get_locale():
    #    return request.accept_languages.best_match(app.config['LANGUAGE'])

    # Admin panel follow db
    admin = Admin(app, name="E-commerce admin")
    # add views for admin
    admin.add_view(AdminView(User, db.session))
    admin.add_view(AdminView(Product, db.session))
    admin.add_view(AdminView(Category, db.session))
    admin.add_view(AdminView(Order, db.session))
    admin.add_view(AdminView(OrderedProduct, db.session))
    admin.add_view(AdminView(SaleTransaction, db.session))

    # initialize migrating database
    migrate = Migrate()
    migrate.init_app(app, db)

    # import all routes of blueprints here
    from core.users.routes import users
    from core.main.routes import main
    from core.errors.routes import errors
    from core.products.routes import products
    from core.cart.routes import cart

    # then register these blueprints here
    app.register_blueprint(users)
    app.register_blueprint(main)
    app.register_blueprint(errors)
    app.register_blueprint(products)
    app.register_blueprint(cart)

    # define some utilities if use flask command
    @app.shell_context_processor
    def shell_context():
        return dict(app=app, db=db, User=User, Category=Category)

    # before first request, create roles
    @app.before_first_request
    def create_role():
        query = db.session.query(Role).all()
        if not query:
            db.session.add(Role(role_name="superuser"))
            db.session.add(Role(role_name="user"))
            db.session.commit()
            print("Roles have been created.")

    @app.cli.command("create")
    @click.argument("superuser")
    def create_superuser(superuser):
        """Create superuser with CLI interface."""
        name = prompt("Enter superuser name.", default="admin")
        email = prompt("Enter superuser email.", default="*****@*****.**")
        phone_number = prompt("Enter superuser phone number.",
                              default="0111111111")
        password = prompt_pass("Enter pasword")
        if not User.query.filter_by(user_name=name).first():
            user = User(
                user_name=name,
                email=email,
                phone=phone_number,
                password=generate_password_hash(password),
                is_superuser=True,
            )
            db.session.add(user)
            db.session.commit()
            superuser_role = (db.session.query(Role).filter_by(
                role_name="superuser").first())
            superuser_role.users.append(user)
            db.session.commit()
            print(f"User {name} has been created.")
        else:
            print(f"User {name} already existed in database.")

    @app.cli.command("dropdb")
    def drop_db():
        """Drop database."""
        if prompt_bool("Are you sure to drop database? [y/N]:"):
            db.drop_all()

    return app