當前位置: 首頁>>代碼示例>>Python>>正文


Python sqlalchemy.SQLAlchemy類代碼示例

本文整理匯總了Python中flaskext.sqlalchemy.SQLAlchemy的典型用法代碼示例。如果您正苦於以下問題:Python SQLAlchemy類的具體用法?Python SQLAlchemy怎麽用?Python SQLAlchemy使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了SQLAlchemy類的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: sql_explain

def sql_explain():
    statement = request.args['sql']
    params = request.args['params']

    # Validate hash
    hash = hashlib.sha1(
        current_app.config['SECRET_KEY'] + statement + params).hexdigest()
    if hash != request.args['hash']:
        return abort(406)

    # Make sure it is a select statement
    if not statement.lower().strip().startswith('select'):
        return abort(406)

    params = json.loads(params)

    engine = SQLAlchemy().get_engine(current_app)

    if engine.driver == 'pysqlite':
        query = 'EXPLAIN QUERY PLAN %s' % statement
    else:
        query = 'EXPLAIN %s' % statement

    result = engine.execute(query, params)
    return g.debug_toolbar.render('panels/sqlalchemy_explain.html', {
        'result': result.fetchall(),
        'headers': result.keys(),
        'sql': format_sql(statement, params),
        'duration': float(request.args['duration']),
    })
開發者ID:jparise,項目名稱:flask-debugtoolbar,代碼行數:30,代碼來源:sqlalchemy.py

示例2: sql_select

def sql_select():
    return ''
    statement = request.args['sql']
    params = request.args['params']

    # Validate hash
    hash = hashlib.sha1(
        current_app.config['SECRET_KEY'] + statement + params).hexdigest()
    if hash != request.args['hash']:
        return abort(406)

    # Make sure it is a select statement
    if not statement.lower().strip().startswith('select'):
        return abort(406)

    params = simplejson.loads(params)

    engine = SQLAlchemy().get_engine(current_app)

    result = engine.execute(statement, params)
    return g.debug_toolbar.render('panels/sqlalchemy_select.html', {
        'result': result.fetchall(),
        'headers': result.keys(),
        'sql': format_sql(statement, params),
        'duration': float(request.args['duration']),
    })
開發者ID:jparise,項目名稱:flask-debugtoolbar,代碼行數:26,代碼來源:sqlalchemy.py

示例3: main

def main():
    global app, db, web, database, pages
    parser = OptionParser()
    parser.add_option("-t", "--test-all", action="store_true", default=False, dest="test_all", help="Run all the tests.")
    parser.add_option("-d", "--test-db", action="store_true", default=False, dest="test_db", help="Run the database tests.")
    parser.add_option("-w", "--test-web", action="store_true", default=False, dest="test_web", help="Run the web tests.")
    parser.add_option("-r", "--reset-db", action="store_true", default=False, dest="reset_db", help="Reset the database.")
    parser.add_option("-s", "--script", metavar="SCRIPT", dest="script", default=None)
    parser.add_option("--server",  action="store_true", default=False, dest="start_server", help="Run the test webserver.")
    (options, args) = parser.parse_args()
    
    if options.test_all or options.test_db or options.test_web:
        app = Flask(__name__.split('.')[0])
        app.config['TESTING'] = True
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db = SQLAlchemy(app)
        suite = unittest.TestSuite()
        if options.test_all or options.test_db:
            import tests.database
            suite.addTest(tests.database.suite)
        if options.test_all or options.test_web:
            import tests.web
            suite.addTest(tests.web.suite)
        unittest.TextTestRunner(verbosity=2).run(suite)
    elif options.script is not None:
        app = Flask(__name__.split('.')[0])
        app.config.from_object(config.FlaskConfig)
        db = SQLAlchemy(app)
        import scripts
        scripts = scripts.load_scripts()
        if options.script in scripts:
            scripts[options.script].main()
    elif options.reset_db or options.start_server:
        # Setup the application and database
        app = Flask(__name__.split('.')[0])
        app.config.from_object(config.FlaskConfig)
        app.jinja_env.add_extension('jinja2.ext.do')
        db = SQLAlchemy(app)
        import database
        import web
        if options.reset_db:
            db.drop_all()
            db.create_all()
            dataset.populate()
            print 'Database reset.'
            exit(0)
        import pages
        app.run(host='0.0.0.0', port=config.dev_port, use_reloader=True)
    else:
        parser.print_help()
開發者ID:gclawes,項目名稱:eecis-accounts,代碼行數:50,代碼來源:__init__.py

示例4: Flask

"""

from flask import Flask
from flaskext.sqlalchemy import SQLAlchemy
from flaskext.uploads import configure_uploads, UploadSet, IMAGES

app = Flask(__name__)

# Load default configuration values, override with whatever is specified
# in configuration file. This is, I think, the sanest approach.
app.config.from_object('kremlin.config_defaults')
app.config.from_envvar('KREMLIN_CONFIGURATION')

# Set database from configuration values
app.config['SQLALCHEMY_DATABASE_URI'] = app.config['DATABASE_URI']
db = SQLAlchemy(app)

uploaded_images = UploadSet("images", IMAGES)

# Create upload set
# and configure like a motherfucker.
uploaded_images = UploadSet("images", IMAGES)
configure_uploads(app, uploaded_images)

# Import relevant modules
# this is done last to avoid touchy situations
import kremlin.dbmodel
import kremlin.core
import kremlin.forms

# Create all database tables
開發者ID:mrdaemon,項目名稱:kremlin,代碼行數:31,代碼來源:__init__.py

示例5: Flask

from flask_dashed.ext.sqlalchemy import ModelAdminModule, model_form

from flaskext.sqlalchemy import SQLAlchemy

from sqlalchemy.orm import aliased, contains_eager


app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.debug = True

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app.jinja_env.trim_blocks = True


db = SQLAlchemy(app)
db_session = db.session


class Company(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), unique=True, nullable=False)

    def __unicode__(self):
        return unicode(self.name)

    def __repr__(self):
        return '<Company %r>' % self.name


class Warehouse(db.Model):
開發者ID:Anioko,項目名稱:Flask-Dashed,代碼行數:31,代碼來源:sqlalchemy_backend.py

示例6: Flask

from flask import Flask
from flaskext.sqlalchemy import SQLAlchemy
from local_settings import DATABASE_LOCATION
#from batman_app import db, app
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_LOCATION

db = SQLAlchemy()
db.init_app(app)

def create_all_db():
    global db, app
    con = app.test_request_context()
    con.push()
    db.create_all()
    con.pop()

def drop_all_db():
    global db, app
    con = app.test_request_context()
    con.push()
    db.drop_all()
    con.pop()


class FloorDate(db.Model):
    __tablename__ = 'floordate'
    proceeding_unix_time = db.Column(db.Integer, primary_key=True)
    proceeding_date = db.Column(db.DateTime)
    add_date = db.Column(db.DateTime)
    duration = db.Column(db.Integer)
開發者ID:sunlightlabs,項目名稱:batman,代碼行數:31,代碼來源:models.py

示例7: Flask

from flask import Flask
from flaskext.sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)


class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))
    body = db.Column(db.Text)
    pub_date = db.Column(db.DateTime)

    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    category = db.relationship('Category',
        backref=db.backref('posts', lazy='dynamic'))

    def __init__(self, title, body, category, pub_date=None):
        self.title = title
        self.body = body
        if pub_date is None:
            pub_date = datetime.utcnow()
        self.pub_date = pub_date
        self.category = category

    def __repr__(self):
        return '<Post %r>' % self.title

開發者ID:bbohrer,項目名稱:waterboard,代碼行數:29,代碼來源:test.py

示例8: reinit_db

def reinit_db():
    global db

    db = SQLAlchemy(app)
    db.create_all()
開發者ID:imbstack,項目名稱:partify,代碼行數:5,代碼來源:database.py

示例9: parse_time_string

_time_regex = re.compile(r'(\d+)([sd]|wk?|yr?|m[io]?)', re.I)
def parse_time_string(s):
    params = collections.defaultdict(int)
    for m in _time_regex.finditer(s):
        params[_time_expansions[m.group(2)]] += int(m.group(1))
    return relativedelta(**params)

app = Flask(__name__)
app.config.from_envvar('SHURT_SETTINGS')
genshi_wrap = Genshi(app)
genshi_wrap.extensions['html'] = 'html5'

photo_set = UploadSet('photos', extensions=IMAGES)
configure_uploads(app, [photo_set])

db = SQLAlchemy(app)

oid = OpenID(app)

def rel_generator(parent, plural, singular=None):
    singular = singular or parent.__name__.lower()
    def deco(cls):
        lower_child = cls.__name__.lower()
        child_fk = db.Column(db.Integer(), db.ForeignKey(cls.id), primary_key=True)
        generated_type = type(parent)(
            cls.__name__ + parent.__name__,
            (parent,),
            {
                '__tablename__': '%s_%s' % (lower_child, plural),
                '__mapper_args__': dict(polymorphic_identity=lower_child),
                'parent_ref_name': lower_child,
開發者ID:habnabit,項目名稱:shurtapp,代碼行數:31,代碼來源:shurts.py

示例10: Flask

from datetime import datetime
from flask import Flask, request, redirect, render_template, flash
from flask.helpers import url_for
from flaskext.sqlalchemy import SQLAlchemy

from knet.api import e24PaymentPipe as gw

app = Flask(__name__)
app.config.from_pyfile('settings.cfg')

# Setting up a default database to be used for knet specific information
# In production, you should probably change this to point to an existing database

#app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///knet.db'
#app.config['SECRET_KEY'] = 'changeme' # change this!
db = SQLAlchemy(app)

# Change these to match your server URLs
# These are required for KNET, but can
# be customized to your needs.

ERROR_URL = app.config['ERROR_URL']
SUCCESS_URL = app.config['SUCCESS_URL']
RESPONSE_URL = app.config['RESPONSE_URL']

knet = gw('resource.cgn', app.config['KNET_ALIAS'])
knet.ERROR_URL = ERROR_URL
knet.RESPONSE_URL = RESPONSE_URL


class Transaction(db.Model):
開發者ID:Ansari92,項目名稱:knet-client,代碼行數:31,代碼來源:main.py


注:本文中的flaskext.sqlalchemy.SQLAlchemy類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。