示例#1
0
def create_app():
    """
    创建 app 实例
    """
    app = Flask(__name__)

    # 添加配置
    app.config.from_object('app.setting')
    app.config.from_object('app.secure')

    # 注册蓝图
    register_blueprint(app)

    # 初始化 flask-sqlalchemy
    db.init_app(app)

    # 根据模型创建数据表(model 在 web 中引用)
    # db.create_all(app=app)
    with app.app_context():
        db.create_all()

    # 初始化 flask-login
    login_manager.init_app(app)
    # 指定登录视图函数的 endpoint 和 提示消息
    login_manager.login_view = 'web.login'
    login_manager.login_message = '请先登录或注册'

    # 初始化 flask-mail
    mail.init_app(app)

    return app
示例#2
0
    def CreateDropRequest(self):
        try:
            db.drop_all()
            db.create_all()

            s = db.session()
            admin = Admin(
                admin_id=uuid.uuid4(),
                username=u'Admin',
                password=Config().get_md5('123456'),
                avatarUrl='',
                role_id=1
            )
            s.add(admin)
            s.commit()

            role_id = uuid.uuid4()
            role = Role(role_id=role_id, name=u'超级管理员', checkKey='[]')
            s.add(role)
            s.commit()

            self.__init_routes(init_route, '0', role_id)
            self.__init_menus(init_menu, '0', role_id)
            return True
        except Exception as e:
            print e
            return str(e.message)
示例#3
0
def initdb():
    db.drop_all()
    db.create_all()
    
    test_user = User(login="******", password="******",
                     first_name="xxx", last_name="xxx", email="*****@*****.**")
    db.session.add(test_user)
    db.session.commit()
    return
示例#4
0
 def before_first_request():
     # 运行models,以创建不存在的表
     try:
         db.create_all()
         s = db.session()
         res = s.query(InitSql).first()
         if not res:
             s.add(InitSql(isInit=False))
             s.commit()
     except:
         return ResultDeal(code=-1, msg=u'数据库未连接错误或者出现错误')
示例#5
0
文件: test_user.py 项目: anby1118/si
    def setUp(self):
        """该方法会首先执行,相当于做测试前的准备工作,一般初始化数据使用"""
        self.app = create_app()
        # 使用flask提供的测试客户端进行测试,flask自带测试客户端,直接模拟终端请求
        self.client = self.app.test_client()
        # 开启测试模式
        self.app.debug = True
        # # 对应修改成自己测试数据库
        self.app.config["SQLALCHEMY_DATABASE_URI"] = DB_PATH

        # 先清空并创建表
        self.app_context=self.app.app_context()
        self.app_context.push()
        db.drop_all()
        db.create_all()
示例#6
0
    def CreateDropRequest(self, isInit, params=None):
        s = db.session()
        try:
            db.drop_all()
            db.create_all()
            s.add(InitSql(isInit=False))
            s.commit()

            role_id = uuid.uuid4()
            role = Role(role_id=role_id, name=u'超级管理员', mark=u'SYS_ADMIN')
            s.add(role)
            s.commit()

            password = self.__get_code()
            if not isInit:
                admin = Admin(admin_id=uuid.uuid4(),
                              username=u'Admin',
                              password=Config().get_md5(password),
                              avatarUrl='',
                              role_id=role_id)
            else:
                admin = Admin(admin_id=params['admin_id'],
                              username=u'Admin',
                              password=params['password'],
                              avatarUrl='',
                              role_id=role_id)
            s.add(admin)
            s.commit()

            self.__init_routes(init_route, '0')
            self.__init_menus(init_menu, '0')

            folder = Folder(folder_id=uuid.uuid4(),
                            admin_id=None,
                            name=u'系统文件',
                            is_sys=True)
            s.add(folder)
            s.commit()

            sql = s.query(InitSql).first()
            sql.isInit = True
            s.commit()
            return {'username': '******', 'password': password}
        except Exception as e:
            s.rollback()
            print e
            return str(e.message)
示例#7
0
def create_app(conf):
    app = Flask(__name__)
    app.config.from_object(conf)
    CORS(app, resources={r"/v1/*": {"origins": "*"}})

    db.init_app(app)
    with app.app_context():
        db.drop_all()
        db.create_all()

    @app.route('/')
    def welcome():
        return 'Welcome to word counting website!'

    api = Api(app, catch_all_404s=True)
    # mapping resource with routes
    api.add_resource(StatisticResource, '/v1/statistics/<int:statistic_id>')
    api.add_resource(StatisticResourceList, '/v1/statistics')

    return app
示例#8
0
def build_sample_db():
    from models.service import Service

    db.drop_all()
    db.create_all()

    # create services
    service_list = []
    for tmp in [
            "Beauticians", "Carpenters", "ComputerTechnicians", "Electricians",
            "Gardeners", "Laborers", "Masseuses", "Painters", "Plumbers",
            "Therapists"
    ]:
        service = Service()
        service.name = tmp
        service_list.append(service)
        db.session.add(service)

    db.session.commit()
    return
示例#9
0
    def CreateDropRequest(self, isInit):
        try:
            s = db.session()

            if isInit:
                try:
                    res = s.query(InitSql).first()
                    if res.isInit:
                        return str('已经初始化~~~')
                except:
                    pass

            db.drop_all()
            db.create_all()

            admin = Admin(admin_id=uuid.uuid4(),
                          username=u'Admin',
                          password=Config().get_md5('123456'),
                          avatarUrl='',
                          role_id=1)
            s.add(admin)
            s.commit()

            role_id = uuid.uuid4()
            role = Role(role_id=role_id, name=u'超级管理员', checkKey='[]')
            s.add(role)
            s.commit()

            self.__init_routes(init_route, '0', role_id)
            self.__init_menus(init_menu, '0', role_id)

            if not isInit:
                sql = InitSql(isInit=True)
                s.add(sql)
                s.commit()

            return True
        except Exception as e:
            print e
            return str(e.message)
示例#10
0
from models.base import db
from models.service import Service

db.drop_all()
db.create_all()

# create services
service_list = []
for tmp in [
        "Beauticians", "Carpenters", "ComputerTechnicians", "Electricians",
        "Gardeners", "Laborers", "Masseuses", "Painters", "Plumbers",
        "Therapists"
]:
    service = Service()
    service.name = tmp
    service_list.append(service)
    db.session.add(service)

db.session.commit()
示例#11
0
from models.base import db
from sqlalchemy import or_, and_
import random

app = Flask(__name__, static_url_path='/dictionary/static')
# 引用config文件,获取数据库相关配置
import config
app.config.from_object(config)
# 解决跨域问题
from flask_cors import CORS
cors = CORS()
cors.init_app(app, resources={"/*": {"origins": "*"}})
# 连接数据库
db.init_app(app)
with app.app_context():  # 手动将app推入栈
    db.create_all()  # 首次模型映射(ORM ==> SQL),若无则建表; 初始化使用

# 這個方法用來轉變model成字典dict,但是不是依據keys,後append的不會被轉入
# def serialize(model):
#     from sqlalchemy.orm import class_mapper
#     columns = [c.key for c in class_mapper(model.__class__).columns]
#     return dict((c, getattr(model, c)) for c in columns)

@app.route("/dictionary/page/<int:page>/")
def page(page):
    page = '000' + str(page)
    page = page[len(page)-4:len(page)]
    src = "https://jay.thathome.cn/dictionary/static/img/dictionary/%s.png" % page
    pp = "https://jay.thathome.cn/dictionary/page/%s/" % str(int(page) - 1)
    pn = "https://jay.thathome.cn/dictionary/page/%s/" % str(int(page) + 1)
    html = "<div style='width:100%%;padding-top:50px;'><h2><span style='float:left;padding:0 10%%;'>當前頁碼:%s</span>" % page
示例#12
0
 def initdb():
     db.create_all()
示例#13
0
def register_plugin(app):
    from models.base import db
    db.init_app(app)
    with app.app_context():
        db.create_all()
示例#14
0
 def setUp(self):
     self.app = create_app('conf.TestingConfig')
     self.client = self.app.test_client()
     # set the databases
     with self.app.app_context():
         db.create_all()
示例#15
0
from flask import Flask, jsonify
from models.base import db
from models.student import Student
from config import sqlalchemy

app = Flask(__name__, instance_relative_config=True)
app.config.from_object(sqlalchemy)
db.init_app(app)
db.create_all(app=app)


@app.route('/')
def root():
    return 'Endpoint not used!'


@app.route('/healthcheck')
def healthcheck():
    return 'ok'


Student.add_routes(app)
示例#16
0
def initialize_database(user, local):
    new_db_name = email_to_name(user.email)
    new_password = random_password()

    # Create a user that will have access to the new datase
    new_database = UserDatabase(drivername='mysql+pymysql',
                                username=new_db_name,
                                password=new_password,
                                host=app.config["APP_DB_HOST"],
                                port=app.config["APP_DB_PORT"],
                                database=new_db_name,
                                query=app.config["CLOUD_SQL_CONNECTION_NAME"],
                                user_id=user.id)

    url = get_db_url({
        'drivername': 'mysql+pymysql',
        'username': app.config["APP_DB_USER"],
        'password': app.config["APP_DB_PASS"],
        'host': app.config["APP_DB_HOST"],
        'port': app.config["APP_DB_PORT"],
        'database': new_db_name,
        'query': app.config["CLOUD_SQL_CONNECTION_NAME"]
    })

    # Step 1: create the new database
    if database_exists(url):
        raise APIError(
            http_code=409,
            error_type_key=APIErrorTypes.database_already_exists,
            message=
            f'Trying to create database {new_db_name} for user {user.email}, but the database already exists'
        )
    else:
        create_database(url)

    # Step 2: create all the tables in the new database
    # Setting the config to the new database url is a hack
    # to make sure SQLALCHAMY does all the heavy lifting
    app.config['SQLALCHEMY_BINDS']['user_db'] = url
    db.create_all(['user_db'])

    # Step 3: Create the new user so that someone can connect
    create_user_query = f'CREATE USER \'{new_db_name}\'@\'%%\' ' \
                        f'IDENTIFIED WITH mysql_native_password ' \
                        f'BY \'{new_password}\';'
    db.engine.execute(create_user_query)

    # Step 4: Give the user the right privileges
    priveleges = [
        'CREATE', 'INSERT', 'SELECT', 'UPDATE', 'ALTER', 'DROP', 'REFERENCES'
    ]
    priveleges_string = ', '.join(priveleges)

    priveleges_string = 'ALL PRIVILEGES'

    grant_perms_query = f'GRANT {priveleges_string} ON {new_db_name}.* ' \
                        f'TO \'{new_db_name}\'@\'%%\';'

    db.engine.execute(grant_perms_query)

    # Step 5: Create the alembic table for migration purposes
    alembic_create_query = f'CREATE TABLE `{new_db_name}`.`alembic_version` ' \
                           f'(' \
                           f'  `version_num` varchar(32) NOT NULL,' \
                           f'  PRIMARY KEY (`version_num`)' \
                           f')'
    db.engine.execute(alembic_create_query)

    # Step 6: Get the data that should be in the new alembic table
    alembic_select_query = f'SELECT `version_num` FROM ' \
                           f'`{app.config["EXAMPLE_DB_NAME"]}`.alembic_version'
    versions = db.engine.execute(alembic_select_query).fetchall()

    # Step 7: Insert the data into the new alembic table
    if len(versions) > 0:
        alembic_insert_query = f'INSERT INTO `{new_db_name}`.' \
                               f'`alembic_version` ' \
                               f'(`version_num`)\n' \
                               f'VALUES\n'
        for row in versions:
            alembic_insert_query += f'(\'{row[0]}\')'
        db.engine.execute(alembic_insert_query)

    # Step 8: Add the user to the session. As the relationship
    # to a UserDatabase object is created in the new_database creation,
    # adding the User object user to the session and committing it will
    # create a new User and UserDatabase row
    db.session.add(new_database)
    db.session.commit()

    createMetabase(user, local)

    return new_database