python类db()的实例源码

__init__.py 文件源码 项目:dodscp 作者: seancallaway 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def user_exists(login):
    g.db = connect_db()
    cur = g.db.execute('SELECT id FROM users WHERE login= "' + login + '"')
    if len(cur.fetchall()) > 0:
        return True
    return False

##
# Logs an action
__init__.py 文件源码 项目:dodscp 作者: seancallaway 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def log_action(uid, action):

    # ACTIONS
    #1|Successful login
    #2|Failed login
    #3|Logout
    #4|Server started
    #5|Server restarted
    #6|Server stopped
    #7|Server updated
    #8|Reset Own Password
    #9|Reset Anothers Password
    #10|Created User
    #11|Deleted User
    #12|Modified Admin Status

    g.db = connect_db()
    cur = g.db.execute('INSERT INTO loggedactions(user, action, time) VALUES (?,?,datetime("now"))', (uid, action))
    g.db.commit()
    g.db.close()


####################################### PAGE FUNCTIONS ######################################

#
# INDEX PAGE
#
__init__.py 文件源码 项目:dodscp 作者: seancallaway 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def home():
    results = '';
    if request.method == 'POST':
        if request.form['action'] == 'start':
            # run the start command
            results = "Starting the server...<br /><br />"
            results += check_output([app.script, "start"])
            log_action(session['uid'], 4)
            results = Markup(results.replace('\n', '<br />'))
        elif request.form['action'] == 'stop':
            # run the stop action
            results = "Stoping the server...<br /><br />"
            results += check_output([app.script, "stop"])
            log_action(session['uid'], 6)
            results = Markup(results.replace('\n', '<br />'))
        elif request.form['action'] == 'restart':
            # run the restart action
            results = "Restarting the server...<br /><br />"
            results += check_output([app.script, "restart"])
            log_action(session['uid'], 5)
            results = Markup(results.replace('\n', '<br />'))
        elif request.form['action'] == 'update':
            # run the update action
            results = "Updating the server...<br /><br />"
            results += check_output([app.script, "update"])
            log_action(session['uid'], 7)
            results = Markup(results.replace('\n', '<br />'))
        else:
            # invalid action!
            results = "INVALID ACTION!"

    g.db = connect_db()
    cur = g.db.execute('SELECT time, (SELECT users.login FROM users WHERE users.id = loggedactions.user), actions.action FROM loggedactions LEFT JOIN actions ON loggedactions.action = actions.id ORDER BY time DESC LIMIT 10;')
    actions = [dict(time=row[0], user=row[1], action=row[2]) for row in cur.fetchall()]
    g.db.close()
    return render_template('index.html', actions=actions, results=results, acp=session['priv'], username=session['username'])

#
# WELCOME PAGE
#
__init__.py 文件源码 项目:dodscp 作者: seancallaway 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def logs():
    g.db = connect_db()
    cur = g.db.execute('SELECT time, (SELECT users.login FROM users WHERE users.id = loggedactions.user), actions.action FROM loggedactions LEFT JOIN actions ON loggedactions.action = actions.id ORDER BY time DESC LIMIT 50;')
    actions = [dict(time=row[0], user=row[1], action=row[2]) for row in cur.fetchall()]
    g.db.close()
    return render_template('logs.html', actions=actions, acp=session['priv'], username=session['username'])

#
# ADD USER PAGE
#
__init__.py 文件源码 项目:flask-vue-example 作者: levi-lq 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def before_request():
    g.db = db
    g.cache = redis_cache
run.py 文件源码 项目:sample-platform 作者: CCExtractor 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def before_request():
    g.menu_entries = {}
    g.db = create_session(app.config['DATABASE_URI'])
    g.mailer = Mailer(app.config.get('EMAIL_DOMAIN', ''),
                      app.config.get('EMAIL_API_KEY', ''),
                      'CCExtractor.org CI Platform')
    g.version = "0.1"
    g.log = log
    g.github = {
        'deploy_key': app.config.get('GITHUB_DEPLOY_KEY', ''),
        'ci_key': app.config.get('GITHUB_CI_KEY', ''),
        'bot_token': app.config.get('GITHUB_TOKEN', ''),
        'repository_owner': app.config.get('GITHUB_OWNER', ''),
        'repository': app.config.get('GITHUB_REPOSITORY', '')
    }
run.py 文件源码 项目:sample-platform 作者: CCExtractor 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def teardown(exception):
    db = g.get('db', None)
    if db is not None:
        db.remove()


# Register blueprints
controllers.py 文件源码 项目:sample-platform 作者: CCExtractor 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def kvm_processor_linux(db, repository, delay):
    from run import config
    kvm_name = config.get('KVM_LINUX_NAME', '')
    return kvm_processor(
        db, kvm_name, TestPlatform.linux, repository, delay)
controllers.py 文件源码 项目:sample-platform 作者: CCExtractor 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def queue_test(db, gh_commit, commit, test_type, branch="master", pr_nr=0):
    """
    Function to store test details into Test model separately for various
    vm. Post status to GitHub
    """
    from run import log
    fork = Fork.query.filter(Fork.github.like(
        "%/CCExtractor/ccextractor.git")).first()
    if test_type == TestType.pull_request:
        branch = "pull_request"
    # Create Linux test entry
    linux = Test(TestPlatform.linux, test_type, fork.id, branch, commit,
                 pr_nr)
    db.add(linux)
    # Create Windows test entry
    windows = Test(TestPlatform.windows, test_type, fork.id, branch,
                   commit, pr_nr)
    db.add(windows)
    db.commit()
    # Update statuses on GitHub
    if gh_commit is not None:
        test_ids = [linux.id, windows.id]
        ci_names = [linux.platform.value, windows.platform.value]
        for idx in range(len(ci_names)):
            try:
                gh_commit.post(
                    state=Status.PENDING, description="Tests queued",
                    context="CI - {name}".format(name=ci_names[idx]),
                    target_url=url_for(
                        'test.by_id', test_id=test_ids[idx], _external=True))
            except ApiError as a:
                log.critical(
                    'Could not post to GitHub! Response: {res}'.format(
                        res=a.response)
                )

    # We wait for the cron to kick off the CI VM's
    log.debug("Created tests, waiting for cron...")
controllers.py 文件源码 项目:sample-platform 作者: CCExtractor 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def in_maintenance_mode(platform):
    try:
        platform = TestPlatform.from_string(platform)
    except ValueError:
        return 'ERROR'

    status = MaintenanceMode.query.filter(
        MaintenanceMode.platform == platform).first()
    if status is None:
        status = MaintenanceMode(platform, False)
        g.db.add(status)
        g.db.commit()

    return "True" if status.disabled else "False"
app.py 文件源码 项目:ImgPy 作者: vladlenomg 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def connect_db():
    return sqlite3.connect('db.db')
app.py 文件源码 项目:ImgPy 作者: vladlenomg 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def before_request():
    g.db = connect_db()
app.py 文件源码 项目:ImgPy 作者: vladlenomg 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def recentlyUploaded():
    #SELECT imgpath FROM pics ORDER BY id DESC LIMIT 8
    recently = []
    n = g.db.execute('SELECT imgpath,url FROM pics ORDER BY id DESC LIMIT 12')
    for i in n:
        recently.append(i)
    return recently
app.py 文件源码 项目:ImgPy 作者: vladlenomg 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get_last_id():
    #SELECT id FROM pics ORDER BY id DESC LIMIT 1;
    n = g.db.execute('SELECT id FROM pics ORDER BY id DESC LIMIT 1;').fetchone()[0]
    return n
app.py 文件源码 项目:ImgPy 作者: vladlenomg 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def upload_img():
    #http://flask.pocoo.org/docs/0.10/patterns/fileuploads/
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            try:
                filename = secure_filename(file.filename)
                if len(filename) > 30:
                    filename = filename[0:30]+'~.'+filename.split('.')[-1]
                new_id = get_last_id() + 1
                new_filename = filename
                new_url = short_url.encode_url(new_id)
                img_path = new_url+'.'+filename.split('.')[-1]
                file.save(os.path.join(UPLOAD_FOLDER, img_path))
                g.db.execute("INSERT INTO pics (id, filename, url, imgpath) VALUES (?, ?, ?, ?)", (new_id, new_filename, new_url, img_path))
                g.db.commit()
                save_thumbnail(img_path)
                #return redirect(url_for('upload_img', filename=filename))
                return redirect('/show/'+new_url)
            except Exception as e:
                return str(e)
        else:
            return "Wrong file!"
    else:
        recent = recentlyUploaded()
        return render_template('index.html', STATIC_DIR = STATIC_DIR, TEMPLATES_DIR=TEMPLATES_DIR, recent = recent,)
gaode.py 文件源码 项目:my-scrapy 作者: azraelkuan 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def before_request():
    if not hasattr(g, 'db'):
        user = GaodeConfig.USER
        password = GaodeConfig.PASSWORD
        databse = GaodeConfig.DATABASE
        g.db = Models(databse, user, password)
gaode.py 文件源码 项目:my-scrapy 作者: azraelkuan 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def teardown_request(exception):
    if hasattr(g, 'db'):
        g.db.close_db()
gaode.py 文件源码 项目:my-scrapy 作者: azraelkuan 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def create_table():
    table_name = request.args.get('table_name')
    data = g.db.create_table(table_name)
    return json.dumps(data)
gaode.py 文件源码 项目:my-scrapy 作者: azraelkuan 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_table():
    conn = g.db.conn
    cur = conn.cursor()
    sql = "select table_name from information_schema.tables"
    cur.execute(sql)
    table_names = cur.fetchall()
    table = []
    for each in table_names:
        if "web_" in each[0]:
            table.append(each[0])
    return json.dumps(table)
dianping.py 文件源码 项目:my-scrapy 作者: azraelkuan 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def teardown_request(exception):
    if hasattr(g, 'db'):
        g.db.close_db()


问题


面经


文章

微信
公众号

扫码关注公众号