本文整理匯總了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']),
})
示例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']),
})
示例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()
示例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
示例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):
示例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)
示例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
示例8: reinit_db
def reinit_db():
global db
db = SQLAlchemy(app)
db.create_all()
示例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,
示例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):