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']), })
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']), })
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']), })
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']), })
def sql_select(): statement = request.args['sql'] params = request.args['params'] params = json.loads(params) db = SQLAlchemy() result = db.engine.execute(statement, params) return render_template( 'panels/sqlalchemy_select.html', **{ 'result': result.fetchall(), 'headers': result.keys(), 'sql': format_sql(statement, params), 'duration': float(request.args['duration']), })
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()
def sql_explain(): statement = request.args['sql'] params = request.args['params'] params = json.loads(params) db = SQLAlchemy() if db.engine.driver == 'pysqlite': query = 'EXPLAIN QUERY PLAN %s' % statement elif db.engine.driver == 'psycopg2': query = 'EXPLAIN VERBOSE %s' % statement else: query = 'EXPLAIN %s' % statement result = db.engine.execute(query, params) return render_template( 'panels/sqlalchemy_explain.html', **{ 'result': result.fetchall(), 'headers': result.keys(), 'sql': format_sql(statement, params), 'duration': float(request.args['duration']), })
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):
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
from flaskext.sqlalchemy import SQLAlchemy from bookmark import app, settings import logging from werkzeug.security import generate_password_hash from flaskext.login import UserMixin db = SQLAlchemy(app) app.config['SQLALCHEMY_DATABASE_URI'] = settings.SQLALCHEMY_DATABASE_URI logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) tags = db.Table( 'bookmark_tag', db.Column('bookmark_id', db.Integer, db.ForeignKey('bookmark.id'), nullable=False), db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), nullable=False)) class Bookmark(db.Model): id = db.Column(db.Integer, primary_key=True) tags = db.relationship('Tag', secondary=tags, backref=db.backref('bookmarks', lazy='dynamic')) link = db.Column(db.String(255), unique=True) title = db.Column(db.String(100), nullable=False) description = db.Column(db.Text(), nullable=False)
import os import re try: from flask import _app_ctx_stack as stack except ImportError: from flask import _request_ctx_stack as stack try: from flaskext.sqlalchemy import SQLAlchemy except: from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy import desc db = SQLAlchemy() migration_file_regex = re.compile('^(\d+)_([a-z0-9_]+)\.py$') class AppliedMigration(db.Model): """ The SQLAlchemy Model to keep track of the migrations """ version = db.Column(db.Integer, primary_key=True) filename = db.Column(db.String(80), nullable=False) ran_at = db.Column(db.DateTime, default=datetime.datetime.utcnow) @classmethod def latest(cls): return AppliedMigration.query.order_by(desc( AppliedMigration.version)).first()
from operator import itemgetter from itertools import imap from cStringIO import StringIO from .etl import Report, Ticket, TicketChange, Milestone, Enum, get_engine_url from sqlalchemy.exc import ResourceClosedError from sqlalchemy.sql import func, case from sqlalchemy.sql.expression import and_, desc from flask import Flask, jsonify, send_from_directory, abort, request, send_file from flaskext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = get_engine_url() app.config['SQLALCHEMY_ECHO'] = True db = SQLAlchemy(app) def get_closed_tickets(session): q = session.query(Ticket.id).filter(Ticket.status == 'closed').order_by( Ticket.id).all() return list(range_span(imap(itemgetter(0), q))) def range_span(vals): ivals = iter(vals) start = end = next(ivals) for v in ivals: if v == end + 1: end = v else:
from flask_dashed.admin import Admin 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 str(self.name) def __repr__(self): return '<Company %r>' % self.name class Warehouse(db.Model):
_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,
from functools import update_wrapper from flask import Flask, Markup, render_template, json, request, url_for, \ redirect, jsonify, g, session, flash, abort from flaskext.sqlalchemy import SQLAlchemy from flaskext.openid import OpenID from werkzeug.urls import url_decode, url_encode, url_quote from werkzeug.http import parse_date, http_date from werkzeug.utils import cached_property from werkzeug.contrib.atom import AtomFeed app = Flask(__name__) app.config.from_pyfile('defaults.cfg') app.config.from_pyfile('local.cfg') db = SQLAlchemy(app) oid = OpenID(app) # set up the logging system based on debug settings if app.debug: logging.basicConfig(level=logging.DEBUG) else: from logging.handlers import SMTPHandler mail_handler = SMTPHandler(app.config['MAIL_SERVER'], app.config['ERROR_MAIL_SENDER'], app.config['ADMINS'], app.config['ERROR_MAIL_SUBJECT']) mail_handler.setFormatter(logging.Formatter('''\ Message type: %(levelname)s Location: %(pathname)s:%(lineno)d
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)
def reinit_db(): global db db = SQLAlchemy(app) db.create_all()
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):
#!/usr/bin/env python #coding:utf-8 from flask import Flask from flaskext.sqlalchemy import SQLAlchemy DEBUG = True SECRET_KEY = '7\xe9\xcf\x17\x11\x92I^"|\xbc\x85\xc8\xc1u\x18\xbb\xec\xc9\xe2\xbb,\x9fX' SQLALCHEMY_DATABASE_URI = 'sqlite:///todo.sqlite' app = Flask(__name__) app.config.from_object(__name__) db = SQLAlchemy(app) db.init_app(app) class Todo(db.Model): '''数据模型''' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255), nullable=False) posted_on = db.Column(db.Date, default=datetime.utcnow) status = db.Column(db.Boolean(), default=False) def __init__(self, *args, **kwargs): super(Todo, self).__init__(*args, **kwargs) def __repr__(self): return "<Todo '%s'>" % self.title def store_to_db(self): '''保存数据到数据库'''
from flaskext.sqlalchemy import SQLAlchemy # configuration DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///flaskr.db' SQLALCHEMY_ECHO = DEBUG SECRET_KEY = 'development key' USERNAME = '******' PASSWORD = '******' # create our little application :) app = Flask(__name__) app.config.from_object(__name__) app.config.from_envvar('FLASKR_SETTINGS', silent=True) db = SQLAlchemy(app) class Entry(db.Model): __tablename__ = "entries" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.Unicode(200)) text = db.Column(db.UnicodeText) db.create_all() class EntryForm(Form): title = TextField("Title", validators=[Required()]) text = TextAreaField("Text")
from flaskext.sqlalchemy import SQLAlchemy import datetime import flask import hashlib import json app = flask.Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.db' db = SQLAlchemy(app) accounts = db.Table( 'accounts', db.Column('account_id', db.String(32), db.ForeignKey('account.id')), db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.UniqueConstraint('account_id', 'user_id')) class User(db.Model): __table_args__ = (db.UniqueConstraint('name', 'email'), ) #family_id = db.Column(db.Integer,db.ForeignKey('family.id')) id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) password = db.Column(db.String(32)) email = db.Column(db.String(80)) accounts = db.relationship('Account', secondary=accounts, backref=db.backref('users', lazy='dynamic')) def __init__(self, name, email, password): self.name = name self.email = email self.password = hashlib.md5(password).hexdigest()
""" 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 m**********r. 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
from collections import defaultdict from datetime import datetime from flaskext.sqlalchemy import SQLAlchemy, BaseQuery from flask import g from sqlalchemy import orm db = SQLAlchemy() # define models class Project(db.Model): _to_serialize = ("id", "name", "password", "contact_email", "members", "active_members", "balance") id = db.Column(db.String, primary_key=True) name = db.Column(db.UnicodeText) password = db.Column(db.String) contact_email = db.Column(db.String) members = db.relationship("Person", backref="project") @property def active_members(self): return [m for m in self.members if m.activated] @property def balance(self):