本文整理匯總了Python中flask_sqlalchemy.SQLAlchemy方法的典型用法代碼示例。如果您正苦於以下問題:Python flask_sqlalchemy.SQLAlchemy方法的具體用法?Python flask_sqlalchemy.SQLAlchemy怎麽用?Python flask_sqlalchemy.SQLAlchemy使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類flask_sqlalchemy
的用法示例。
在下文中一共展示了flask_sqlalchemy.SQLAlchemy方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: DbClient
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def DbClient(app, user, password, host, port, name):
"""
Orion does not need to provide any additional abstractions over the client object created by
SQLAlchemy. This function directly returns the object instantiated by creating a SQLAlchemy
object from the current Flask app.
:param app: Flask application object.
:param user: The username of the MySQL user.
:param password: The password of the MySQL user.
:param host: The host of the MySQL instance.
:param port: The port of the MySQL instance.
:param name: The name of the MySQL database.
:return: A SQLAlchemy object for interacting with the database.
"""
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{user}:{password}@{host}:{port}/{name}'.format(
user=user,
password=password,
host=host,
port=port,
name=name,
)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
return flask_sqlalchemy.SQLAlchemy(app, session_options=session_opts)
示例2: setUp
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def setUp(self):
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class DummyModel(db.Model):
""" SQLAlchemy Dummy Object """
id = db.Column(db.Integer, primary_key=True)
integer = db.Column(db.Integer)
db.create_all()
self.DummyModel = DummyModel
self.define_validators()
self.dummy = DummyModel()
self.app = app
self.db = db
示例3: init_app
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def init_app(self, app, db, **kwargs):
"""
app: The Flask application instance.
"""
if not isinstance(app, Flask):
raise TypeError(
'hobbit_core.HobbitManager.init_app(): '
'Parameter "app" is an instance of class "{}" '
'instead of a subclass of class "flask.Flask".'.format(
app.__class__.__name__))
if not isinstance(db, SQLAlchemy):
raise TypeError('hobbit-core be dependent on SQLAlchemy.')
self.db = db
app.config.setdefault('HOBBIT_UPPER_SEQUENCE_NAME', False)
# Bind hobbit-core to app
app.hobbit_manager = self
示例4: from_model
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def from_model(cls, cmd: commands.Command):
"""This method turns a subclass of commands.Command into an SQLAlchemy model.
The parameters of the command are encoded as a JSON dictionary inside the parameters column.
Args:
cmd (commands.Command): The command to be turned into a database model.
Returns:
Command: The database model, ready to be committed.
"""
c = cls()
assert cmd.request_type is not None
c.request_type = cmd.request_type
c.uuid = cmd.uuid
c.parameters = cmd.parameters
return c
示例5: app_with_scout
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def app_with_scout():
with flask_app_with_scout() as app:
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
# Setup according to https://docs.scoutapm.com/#flask-sqlalchemy
instrument_sqlalchemy(db)
conn = db.engine.connect()
@app.route("/sqlalchemy/")
def sqlalchemy():
result = conn.execute("SELECT 'Hello from the DB!'")
return list(result)[0][0]
try:
yield app
finally:
conn.close()
示例6: generate_context
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def generate_context(config):
"""Create the Flask app context and initializes any extensions such as Celery, Redis, SQLAlchemy, etc.
:param dict config: Partial Flask config dict from generate_config().
:return: The Flask app instance.
"""
flask_app = Flask(__name__)
flask_app.config.update(config)
flask_app.config['TESTING'] = True
flask_app.config['CELERY_ACCEPT_CONTENT'] = ['pickle']
if 'SQLALCHEMY_DATABASE_URI' in flask_app.config:
db = SQLAlchemy(flask_app)
db.engine.execute('DROP TABLE IF EXISTS celery_tasksetmeta;')
elif 'REDIS_URL' in flask_app.config:
redis = Redis(flask_app)
redis.flushdb()
Celery(flask_app)
return flask_app
示例7: init_flask
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def init_flask():
global db
global UserMixin
import docassemble.webapp.database
if docassemble.webapp.database.pool_pre_ping:
from flask_sqlalchemy import SQLAlchemy as _BaseSQLAlchemy
class SQLAlchemy(_BaseSQLAlchemy):
def apply_pool_defaults(self, app, options):
super().apply_pool_defaults(app, options)
options["pool_pre_ping"] = True
else:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
import flask_user
UserMixin = flask_user.UserMixin
return db
示例8: create_docker_init
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def create_docker_init(project_address):
import time
t = time.strftime('%Y/%m/%d %H:%M:%S')
project_name = os.path.basename(project_address)
address = project_address + os.sep + project_name
text = f"""#!/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time : {t}
# @Author: Jtyoui@qq.com
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import CONFIG
env = os.getenv("FLASK_ENV")
db = SQLAlchemy()
app = Flask(__name__)
app.config.from_object(CONFIG.get(env, CONFIG['development']))
db.init_app(app)
"""
if not os.path.exists(address):
os.mkdir(address)
if not os.path.exists(address + os.sep + '__init__.py'):
with open(address + os.sep + '__init__.py', 'w', encoding='utf-8')as wf:
wf.write(text)
else:
warnings.warn('路徑:' + address + os.sep + '__init__.py已存在。默認不覆蓋,請刪除後在執行!')
示例9: db
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def db():
return SQLAlchemy()
示例10: __repr__
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def __repr__(self):
return '<id is %s, creditType is %s, queryType is %s, creditStatus is %s, monitorTime is %s, elapsedTime is %s>' % (
self.id, self.credit_type, self.query_type, self.credit_status, self.monitor_time, self.elapsed_time)
# SQLAlchemy core
示例11: get_monitor_with_orm
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def get_monitor_with_orm():
s = monitor_db.get_connection_session(url)
print(s.query(Monitor).limit(2).all())
print(s.query(Monitor).first())
print(type(s.query(Monitor)))
print(s.query(Monitor).count())
# SQLAlchemy core
示例12: test_replace_send_code
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def test_replace_send_code(app, get_message):
from flask_sqlalchemy import SQLAlchemy
from flask_security.models import fsqla_v2 as fsqla
from flask_security import Security, us_send_security_token
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
db = SQLAlchemy(app)
fsqla.FsModels.set_db_info(db)
class Role(db.Model, fsqla.FsRoleMixin):
pass
class User(db.Model, fsqla.FsUserMixin):
def us_send_security_token(self, method, **kwargs):
assert method == "sms"
us_send_security_token(self, method, **kwargs)
with app.app_context():
db.create_all()
ds = SQLAlchemyUserDatastore(db, User, Role)
app.security = Security(app, datastore=ds)
with app.app_context():
client = app.test_client()
# since we don't use client fixture - have to add user
data = dict(email="trp@lp.com", password="password")
response = client.post("/register", data=data, follow_redirects=True)
assert b"Welcome trp@lp.com" in response.data
logout(client)
set_phone(app, email="trp@lp.com")
data = dict(identity="trp@lp.com", chosen_method="sms")
response = client.post("/us-signin/send-code", data=data, follow_redirects=True)
assert b"Code has been sent" in response.data
示例13: sqlalchemy_setup
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def sqlalchemy_setup(request, app, tmpdir, realdburl):
from flask_sqlalchemy import SQLAlchemy
from flask_security.models import fsqla_v2 as fsqla
if realdburl:
db_url, db_info = _setup_realdb(realdburl)
app.config["SQLALCHEMY_DATABASE_URI"] = db_url
else:
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
db = SQLAlchemy(app)
fsqla.FsModels.set_db_info(db)
class Role(db.Model, fsqla.FsRoleMixin):
pass
class User(db.Model, fsqla.FsUserMixin):
security_number = db.Column(db.Integer, unique=True)
# For testing allow null passwords.
password = db.Column(db.String(255), nullable=True)
def get_security_payload(self):
# Make sure we still properly hook up to flask JSONEncoder
return {"email": str(self.email), "last_update": self.update_datetime}
with app.app_context():
db.create_all()
def tear_down():
if realdburl:
db.drop_all()
_teardown_realdb(db_info)
request.addfinalizer(tear_down)
return SQLAlchemyUserDatastore(db, User, Role)
示例14: setUp
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def setUp(self):
class TestConfig(object):
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_DATABASE_URI = 'sqlite://'
DEBUG = True
TESTING = True
MSEARCH_INDEX_NAME = mkdtemp()
MSEARCH_BACKEND = 'whoosh'
self.app = Flask(__name__)
self.app.config.from_object(TestConfig())
self.db = SQLAlchemy(self.app)
self.search = Search(self.app, db=self.db)
db = self.db
class Post(db.Model, ModelSaveMixin):
__tablename__ = 'basic_posts'
__searchable__ = ['title', 'content']
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(49))
content = db.Column(db.Text)
def __repr__(self):
return '<Post:{}>'.format(self.title)
self.Post = Post
示例15: get_args
# 需要導入模塊: import flask_sqlalchemy [as 別名]
# 或者: from flask_sqlalchemy import SQLAlchemy [as 別名]
def get_args():
parser = argparse.ArgumentParser(description="Generates SQLAlchemy model code from an existing database.")
parser.add_argument("url", nargs="?", help="SQLAlchemy url to the database")
parser.add_argument("--version", action="store_true", help="print the version number and exit")
parser.add_argument("--host", default="0.0.0.0", help="host (interface ip) to run")
parser.add_argument("--port", default=5000, type=int, help="host (interface ip) to run")
parser.add_argument("--models", default=None, help="Load models from file instead of generating them dynamically")
parser.add_argument("--schema", help="load tables from an alternate schema")
parser.add_argument("--tables", help="tables to process (comma-separated, default: all)")
parser.add_argument("--noviews", action="store_true", help="ignore views")
parser.add_argument("--noindexes", action="store_true", help="ignore indexes")
parser.add_argument("--noconstraints", action="store_true", help="ignore constraints")
parser.add_argument("--nojoined", action="store_true", help="don't autodetect joined table inheritance")
parser.add_argument("--noinflect", action="store_true", help="don't try to convert tables names to singular form")
parser.add_argument("--noclasses", action="store_true", help="don't generate classes, only tables")
parser.add_argument("--outfile", help="file to write output to (default: stdout)")
args = parser.parse_args()
if args.version:
version = pkg_resources.get_distribution("sqlacodegen").parsed_version # noqa: F821
print(version.public)
exit()
if not args.url:
print("You must supply a url\n", file=sys.stderr)
parser.print_help()
exit(1)
return args