Flask-SQLAlchemy-2.1/0000755000076500000240000000000012612401275014433 5ustar philstaff00000000000000Flask-SQLAlchemy-2.1/CHANGES0000644000076500000240000000557412612401230015430 0ustar philstaff00000000000000Changelog ========= Here you can see the full list of changes between each Flask-SQLAlchemy release. Version 3.0 ----------- In development, codename Dubnium Version 2.1 ----------- Released on October 23rd 2015, codename Caesium - Table names are automatically generated in more cases, including subclassing mixins and abstract models. - Allow using a custom MetaData object. - Add support for binds parameter to session. Version 2.0 ----------- Released on August 29th 2014, codename Bohrium - Changed how the builtin signals are subscribed to skip non Flask-SQLAlchemy sessions. This will also fix the attribute error about model changes not existing. - Added a way to control how signals for model modifications are tracked. - Made the ``SignallingSession`` a public interface and added a hook for customizing session creation. - If the ``bind`` parameter is given to the signalling session it will no longer cause an error that a parameter is given twice. - Added working table reflection support. - Enabled autoflush by default. - Consider ``SQLALCHEMY_COMMIT_ON_TEARDOWN`` harmful and remove from docs. Version 1.0 ----------- Released on July 20th 2013, codename Aurum - Added Python 3.3 support. - Dropped 2.5 compatibility. - Various bugfixes - Changed versioning format to do major releases for each update now. Version 0.16 ------------ - New distribution format (flask_sqlalchemy) - Added support for Flask 0.9 specifics. Version 0.15 ------------ - Added session support for multiple databases Version 0.14 ------------ - Make relative sqlite paths relative to the application root. Version 0.13 ------------ - Fixed an issue with Flask-SQLAlchemy not selecting the correct binds. Version 0.12 ------------ - Added support for multiple databases. - Expose Flask-SQLAlchemy's BaseQuery as `db.Query`. - Set default query_class for `db.relation`, `db.relationship`, and `db.dynamic_loader` to Flask-SQLAlchemy's BaseQuery. - Improved compatibility with Flask 0.7. Version 0.11 ------------ - Fixed a bug introduced in 0.10 with alternative table constructors. Version 0.10 ------------ - Added support for signals. - Table names are now automatically set from the class name unless overriden. - Model.query now always works for applications directly passed to the SQLAlchemy constructor. Furthermore the property now raises an RuntimeError instead of being None. - added session options to constructor. - fixed a broken `__repr__` - `db.Table` is now a factor function that creates table objects. This makes it possible to omit the metadata. Version 0.9 ----------- - applied changes to pass the Flask extension approval process. Version 0.8 ----------- - added a few configuration keys for creating connections. - automatically activate connection recycling for MySQL connections. - added support for the Flask testing mode. Version 0.7 ----------- - Initial public release Flask-SQLAlchemy-2.1/docs/0000755000076500000240000000000012612401275015363 5ustar philstaff00000000000000Flask-SQLAlchemy-2.1/docs/_static/0000755000076500000240000000000012612401275017011 5ustar philstaff00000000000000Flask-SQLAlchemy-2.1/docs/_static/flask-sqlalchemy-small.png0000644000076500000240000004001512473657260024101 0ustar philstaff00000000000000PNG  IHDR_sBIT|d pHYs&x&xz_\tEXtSoftwarewww.inkscape.org< IDATxw^EǿlBB:II@@z/J ( UD"REA@P"J$HH{?~gy>lv>}iwgN`fTB-MNfnTe jap`'W=U x8nDB 9^ֱBalO-}SE@ ! nD[}LOl~ C-3eIe5p igfTijfq[R:B.O`f6 lBϸ-})S G@: 8nwnS3SA#np x\hf3!}0k~;=3H 0۷ܘ pӎIpx+06 l|?ǁG>>eKIXZ`[`:hm-7&"lpB88!~fvK%D~RwԖڒt'!-Kz3?^o" !0N. nK_Ԏ$+̦=;d[ FGb3!{[?jԶT,/{!5¤ł¾ȁ[!s6B1-5: `U3BxؼPo0a> of#BC*jҗ #aTB;SH*ҳ lk3`f0^6mKMJ,DM-;O_4aS1G@=hfK:ZB_>f69-- 3)o# mf !e, ߖ,Iy+3o\u۫  !| "BNk֧hK_?C_C(6*MZ,a~(/Y03h2mOV+і2hρ/ .DTEu~ ]k[nR8g&M/ w)ǔ6C FLV,?닁0 XrShˏij^@Z4ͻ&[1`#ڀ-76 x2į 9] Oʑ}=\l^E;"yC:\܍L:>lTN2?8+ kB130"I.T+ s=7{ H]bH\Y!M[hTgjȾmf~ |F/ 33xѵys̬fRy@2-fr\?=f*ܥN9rB8a͐unf1!`VoDJ켦?V|6Lej> i>-yOm1քjwA$C? R7 x OH<i!qQ#VBF֫l5C!WIdfWCdfq7BԻC@Y_>@~`"7"0~n -bBѦ?t 2 %Cr琳s+f6E'BAX`3{+p&#'u>a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000Flask-SQLAlchemy-2.1/docs/_templates/sidebarintro.html0000644000076500000240000000227712473657260023117 0ustar philstaff00000000000000

About

Flask-SQLAlchemy provides a SQLAlchemy extension to Flask. Flask is a micro webdevelopment framework for Python. You are currently looking at the documentation of the development version. Things are not stable yet, but if you have some feedback, let me know.

Useful Links

Fork me on GitHub Flask-SQLAlchemy-2.1/docs/_templates/sidebarlogo.html0000644000076500000240000000027112473657260022714 0ustar philstaff00000000000000 Flask-SQLAlchemy-2.1/docs/api.rst0000644000076500000240000000326712555752324016710 0ustar philstaff00000000000000API --- .. module:: flask.ext.sqlalchemy This part of the documentation documents all the public classes and functions in Flask-SQLAlchemy. Configuration ````````````` .. autoclass:: SQLAlchemy :members: .. attribute:: Query The :class:`BaseQuery` class. Models `````` .. autoclass:: Model :members: .. attribute:: __bind_key__ Optionally declares the bind to use. `None` refers to the default bind. For more information see :ref:`binds`. .. attribute:: __tablename__ The name of the table in the database. This is required by SQLAlchemy; however, Flask-SQLAlchemy will set it automatically if a model has a primary key defined. If the ``__table__`` or ``__tablename__`` is set explicitly, that will be used instead. .. autoclass:: BaseQuery :members: get, get_or_404, paginate, first_or_404 .. method:: all() Return the results represented by this query as a list. This results in an execution of the underlying query. .. method:: order_by(*criterion) apply one or more ORDER BY criterion to the query and return the newly resulting query. .. method:: limit(limit) Apply a LIMIT to the query and return the newly resulting query. .. method:: offset(offset) Apply an OFFSET to the query and return the newly resulting query. .. method:: first() Return the first result of this query or `None` if the result doesn’t contain any rows. This results in an execution of the underlying query. Sessions ```````` .. autoclass:: SignallingSession :members: Utilities ````````` .. autoclass:: Pagination :members: .. autofunction:: get_debug_queries Flask-SQLAlchemy-2.1/docs/binds.rst0000644000076500000240000000532612473657260017236 0ustar philstaff00000000000000.. _binds: .. currentmodule:: flask.ext.sqlalchemy Multiple Databases with Binds ============================= Starting with 0.12 Flask-SQLAlchemy can easily connect to multiple databases. To achieve that it preconfigures SQLAlchemy to support multiple “binds”. What are binds? In SQLAlchemy speak a bind is something that can execute SQL statements and is usually a connection or engine. In Flask-SQLAlchemy binds are always engines that are created for you automatically behind the scenes. Each of these engines is then associated with a short key (the bind key). This key is then used at model declaration time to assocate a model with a specific engine. If no bind key is specified for a model the default connection is used instead (as configured by ``SQLALCHEMY_DATABASE_URI``). Example Configuration --------------------- The following configuration declares three database connections. The special default one as well as two others named `users` (for the users) and `appmeta` (which connects to a sqlite database for read only access to some data the application provides internally):: SQLALCHEMY_DATABASE_URI = 'postgres://localhost/main' SQLALCHEMY_BINDS = { 'users': 'mysqldb://localhost/users', 'appmeta': 'sqlite:////path/to/appmeta.db' } Creating and Dropping Tables ---------------------------- The :meth:`~SQLAlchemy.create_all` and :meth:`~SQLAlchemy.drop_all` methods by default operate on all declared binds, including the default one. This behavior can be customized by providing the `bind` parameter. It takes either a single bind name, ``'__all__'`` to refer to all binds or a list of binds. The default bind (``SQLALCHEMY_DATABASE_URI``) is named `None`: >>> db.create_all() >>> db.create_all(bind=['users']) >>> db.create_all(bind='appmeta') >>> db.drop_all(bind=None) Referring to Binds ------------------ If you declare a model you can specify the bind to use with the :attr:`~Model.__bind_key__` attribute:: class User(db.Model): __bind_key__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) Internally the bind key is stored in the table's `info` dictionary as ``'bind_key'``. This is important to know because when you want to create a table object directly you will have to put it in there:: user_favorites = db.Table('user_favorites', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('message_id', db.Integer, db.ForeignKey('message.id')), info={'bind_key': 'users'} ) If you specified the `__bind_key__` on your models you can use them exactly the way you are used to. The model connects to the specified database connection itself. Flask-SQLAlchemy-2.1/docs/changelog.rst0000644000076500000240000000003012473657260020051 0ustar philstaff00000000000000.. include:: ../CHANGES Flask-SQLAlchemy-2.1/docs/conf.py0000644000076500000240000002032012555752324016671 0ustar philstaff00000000000000# -*- coding: utf-8 -*- # # Flask-SQLAlchemy documentation build configuration file, created by # sphinx-quickstart on Tue Jun 1 14:31:57 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) sys.path.append(os.path.abspath('_themes')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Flask-SQLAlchemy' copyright = u'2010-2014, Armin Ronacher' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. import pkg_resources try: release = pkg_resources.get_distribution('Flask-SQLAlchemy').version except pkg_resources.DistributionNotFound: print('To build the documentation, The distribution information of') print('Flask-SQLAlchemy has to be available. Either install the package') print('into your development environment or run "setup.py develop"') print('to setup the metadata. A virtualenv is recommended!') sys.exit(1) del pkg_resources if 'dev' in release: release = release.split('dev')[0] + 'dev' version = '.'.join(release.split('.')[:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'flask' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { 'index_logo': 'flask-sqlalchemy.png' } # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_themes'] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. Do not set, template magic! #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = { 'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html'], '**': ['sidebarlogo.html', 'localtoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'] } # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. html_use_modindex = False # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'Flask-SQLAlchemydoc' # -- Options for LaTeX output -------------------------------------------------- # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Flask-SQLAlchemy.tex', u'Flask-SQLAlchemy Documentation', u'Armin Ronacher', 'manual'), ] # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. latex_use_modindex = False latex_elements = { 'fontpkg': r'\usepackage{mathpazo}', 'papersize': 'a4paper', 'pointsize': '12pt', 'preamble': r'\usepackage{flaskstyle}' } latex_use_parts = True latex_additional_files = ['flaskstyle.sty', 'logo.pdf'] # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'flask-sqlalchemy', u'Flask-SQLAlchemy Documentation', [u'Armin Ronacher'], 1) ] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None, 'http://flask.pocoo.org/docs/': None, 'http://www.sqlalchemy.org/docs/': None} pygments_style = 'flask_theme_support.FlaskyStyle' # fall back if theme is not there try: __import__('flask_theme_support') except ImportError as e: print('-' * 74) print('Warning: Flask themes unavailable. Building with default theme') print('If you want the Flask themes, run this command and build again:') print() print(' git submodule update --init') print('-' * 74) pygments_style = 'tango' html_theme = 'default' html_theme_options = {} Flask-SQLAlchemy-2.1/docs/config.rst0000644000076500000240000001506012555752324017376 0ustar philstaff00000000000000Configuration ============= The following configuration values exist for Flask-SQLAlchemy. Flask-SQLAlchemy loads these values from your main Flask config which can be populated in various ways. Note that some of those cannot be modified after the engine was created so make sure to configure as early as possible and to not modify them at runtime. Configuration Keys ------------------ A list of configuration keys currently understood by the extension: .. tabularcolumns:: |p{6.5cm}|p{8.5cm}| ================================== ========================================= ``SQLALCHEMY_DATABASE_URI`` The database URI that should be used for the connection. Examples: - ``sqlite:////tmp/test.db`` - ``mysql://username:password@server/db`` ``SQLALCHEMY_BINDS`` A dictionary that maps bind keys to SQLAlchemy connection URIs. For more information about binds see :ref:`binds`. ``SQLALCHEMY_ECHO`` If set to `True` SQLAlchemy will log all the statements issued to stderr which can be useful for debugging. ``SQLALCHEMY_RECORD_QUERIES`` Can be used to explicitly disable or enable query recording. Query recording automatically happens in debug or testing mode. See :func:`get_debug_queries` for more information. ``SQLALCHEMY_NATIVE_UNICODE`` Can be used to explicitly disable native unicode support. This is required for some database adapters (like PostgreSQL on some Ubuntu versions) when used with improper database defaults that specify encoding-less databases. ``SQLALCHEMY_POOL_SIZE`` The size of the database pool. Defaults to the engine's default (usually 5) ``SQLALCHEMY_POOL_TIMEOUT`` Specifies the connection timeout for the pool. Defaults to 10. ``SQLALCHEMY_POOL_RECYCLE`` Number of seconds after which a connection is automatically recycled. This is required for MySQL, which removes connections after 8 hours idle by default. Note that Flask-SQLAlchemy automatically sets this to 2 hours if MySQL is used. ``SQLALCHEMY_MAX_OVERFLOW`` Controls the number of connections that can be created after the pool reached its maximum size. When those additional connections are returned to the pool, they are disconnected and discarded. ``SQLALCHEMY_TRACK_MODIFICATIONS`` If set to ``True``, Flask-SQLAlchemy will track modifications of objects and emit signals. The default is ``None``, which enables tracking but issues a warning that it will be disabled by default in the future. This requires extra memory and should be disabled if not needed. ================================== ========================================= .. versionadded:: 0.8 The ``SQLALCHEMY_NATIVE_UNICODE``, ``SQLALCHEMY_POOL_SIZE``, ``SQLALCHEMY_POOL_TIMEOUT`` and ``SQLALCHEMY_POOL_RECYCLE`` configuration keys were added. .. versionadded:: 0.12 The ``SQLALCHEMY_BINDS`` configuration key was added. .. versionadded:: 0.17 The ``SQLALCHEMY_MAX_OVERFLOW`` configuration key was added. .. versionadded:: 2.0 The ``SQLALCHEMY_TRACK_MODIFICATIONS`` configuration key was added. .. versionchanged:: 2.1 ``SQLALCHEMY_TRACK_MODIFICATIONS`` will warn if unset. Connection URI Format --------------------- For a complete list of connection URIs head over to the SQLAlchemy documentation under (`Supported Databases `_). This here shows some common connection strings. SQLAlchemy indicates the source of an Engine as a URI combined with optional keyword arguments to specify options for the Engine. The form of the URI is:: dialect+driver://username:password@host:port/database Many of the parts in the string are optional. If no driver is specified the default one is selected (make sure to *not* include the ``+`` in that case). Postgres:: postgresql://scott:tiger@localhost/mydatabase MySQL:: mysql://scott:tiger@localhost/mydatabase Oracle:: oracle://scott:tiger@127.0.0.1:1521/sidname SQLite (note the four leading slashes):: sqlite:////absolute/path/to/foo.db Using custom MetaData and naming conventions -------------------------------------------- You can optionally construct the :class:`SQLAlchemy` object with a custom :class:`~sqlalchemy.schema.MetaData` object. This allows you to, among other things, specify a `custom constraint naming convention `_. Doing so is important for dealing with database migrations (for instance using `alembic `_ as stated `here `_. Since SQL defines no standard naming conventions, there is no guaranteed nor effective compatibility by default among database implementations. You can define a custom naming convention like this as suggested by the SQLAlchemy docs:: from sqlalchemy import MetaData from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy convention = { "ix": 'ix_%(column_0_label)s', "uq": "uq_%(table_name)s_%(column_0_name)s", "ck": "ck_%(table_name)s_%(constraint_name)s", "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", "pk": "pk_%(table_name)s" } metadata = MetaData(naming_convention=convention) db = SQLAlchemy(app, metadata=metadata) For more info about :class:`~sqlalchemy.schema.MetaData`, `check out the official docs on it `_. Flask-SQLAlchemy-2.1/docs/contents.rst.inc0000644000076500000240000000115612473657260020541 0ustar philstaff00000000000000User's Guide ------------ This part of the documentation will show you how to get started in using Flask-SQLAlchemy with Flask. .. toctree:: :maxdepth: 2 quickstart contexts config models queries binds signals API Reference ------------- If you are looking for information on a specific function, class or method, this part of the documentation is for you. .. toctree:: :maxdepth: 2 api Additional Notes ---------------- See Flask's license_ for legal information governing this project. .. toctree:: :maxdepth: 2 changelog .. _license: http://flask.pocoo.org/docs/license/ Flask-SQLAlchemy-2.1/docs/contexts.rst0000644000076500000240000000365612555752324020010 0ustar philstaff00000000000000.. _contexts: .. currentmodule:: flask.ext.sqlalchemy Introduction into Contexts ========================== If you are planning on using only one application you can largely skip this chapter. Just pass your application to the :class:`SQLAlchemy` constructor and you're usually set. However if you want to use more than one application or create the application dynamically in a function you want to read on. If you define your application in a function, but the :class:`SQLAlchemy` object globally, how does the latter learn about the former? The answer is the :meth:`~SQLAlchemy.init_app` function:: from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def create_app(): app = Flask(__name__) db.init_app(app) return app What it does is prepare the application to work with :class:`SQLAlchemy`. However that does not now bind the :class:`SQLAlchemy` object to your application. Why doesn't it do that? Because there might be more than one application created. So how does :class:`SQLAlchemy` now really know about your application? You will have to setup an application context. If you are working inside a Flask view function, that automatically happens. However if you are working inside the interactive shell, you will have to do that yourself (see `Creating an Application Context `_). In a nutshell, do something like this: >>> from yourapp import create_app >>> app = create_app() >>> app.app_context().push() Inside scripts it makes also sense to use the with-statement:: def my_function(): with app.app_context(): user = db.User(...) db.session.add(user) db.session.commit() Some functions inside Flask-SQLAlchemy also accept optionally the application to operate on: >>> from yourapp import db, create_app >>> db.create_all(app=create_app()) Flask-SQLAlchemy-2.1/docs/flaskstyle.sty0000644000076500000240000000604212473657260020323 0ustar philstaff00000000000000\definecolor{TitleColor}{rgb}{0,0,0} \definecolor{InnerLinkColor}{rgb}{0,0,0} \renewcommand{\maketitle}{% \begin{titlepage}% \let\footnotesize\small \let\footnoterule\relax \ifsphinxpdfoutput \begingroup % This \def is required to deal with multi-line authors; it % changes \\ to ', ' (comma-space), making it pass muster for % generating document info in the PDF file. \def\\{, } \pdfinfo{ /Author (\@author) /Title (\@title) } \endgroup \fi \begin{flushright}% %\sphinxlogo% {\center \vspace*{3cm} \includegraphics{logo.pdf} \vspace{3cm} \par {\rm\Huge \@title \par}% {\em\LARGE \py@release\releaseinfo \par} {\large \@date \par \py@authoraddress \par }}% \end{flushright}%\par \@thanks \end{titlepage}% \cleardoublepage% \setcounter{footnote}{0}% \let\thanks\relax\let\maketitle\relax %\gdef\@thanks{}\gdef\@author{}\gdef\@title{} } \fancypagestyle{normal}{ \fancyhf{} \fancyfoot[LE,RO]{{\thepage}} \fancyfoot[LO]{{\nouppercase{\rightmark}}} \fancyfoot[RE]{{\nouppercase{\leftmark}}} \fancyhead[LE,RO]{{ \@title, \py@release}} \renewcommand{\headrulewidth}{0.4pt} \renewcommand{\footrulewidth}{0.4pt} } \fancypagestyle{plain}{ \fancyhf{} \fancyfoot[LE,RO]{{\thepage}} \renewcommand{\headrulewidth}{0pt} \renewcommand{\footrulewidth}{0.4pt} } \titleformat{\section}{\Large}% {\py@TitleColor\thesection}{0.5em}{\py@TitleColor}{\py@NormalColor} \titleformat{\subsection}{\large}% {\py@TitleColor\thesubsection}{0.5em}{\py@TitleColor}{\py@NormalColor} \titleformat{\subsubsection}{}% {\py@TitleColor\thesubsubsection}{0.5em}{\py@TitleColor}{\py@NormalColor} \titleformat{\paragraph}{\large}% {\py@TitleColor}{0em}{\py@TitleColor}{\py@NormalColor} \ChNameVar{\raggedleft\normalsize} \ChNumVar{\raggedleft \bfseries\Large} \ChTitleVar{\raggedleft \rm\Huge} \renewcommand\thepart{\@Roman\c@part} \renewcommand\part{% \pagestyle{plain} \if@noskipsec \leavevmode \fi \cleardoublepage \vspace*{6cm}% \@afterindentfalse \secdef\@part\@spart} \def\@part[#1]#2{% \ifnum \c@secnumdepth >\m@ne \refstepcounter{part}% \addcontentsline{toc}{part}{\thepart\hspace{1em}#1}% \else \addcontentsline{toc}{part}{#1}% \fi {\parindent \z@ %\center \interlinepenalty \@M \normalfont \ifnum \c@secnumdepth >\m@ne \rm\Large \partname~\thepart \par\nobreak \fi \MakeUppercase{\rm\Huge #2}% \markboth{}{}\par}% \nobreak \vskip 8ex \@afterheading} \def\@spart#1{% {\parindent \z@ %\center \interlinepenalty \@M \normalfont \huge \bfseries #1\par}% \nobreak \vskip 3ex \@afterheading} % use inconsolata font \usepackage{inconsolata} % fix single quotes, for inconsolata. (does not work) %%\usepackage{textcomp} %%\begingroup %% \catcode`'=\active %% \g@addto@macro\@noligs{\let'\textsinglequote} %% \endgroup %%\endinput Flask-SQLAlchemy-2.1/docs/index.rst0000644000076500000240000000107112473657260017237 0ustar philstaff00000000000000:orphan: Flask-SQLAlchemy ================ .. module:: flask.ext.sqlalchemy Flask-SQLAlchemy is an extension for `Flask`_ that adds support for `SQLAlchemy`_ to your application. It requires SQLAlchemy 0.6 or higher. It aims to simplify using SQLAlchemy with Flask by providing useful defaults and extra helpers that make it easier to accomplish common tasks. .. _SQLAlchemy: http://www.sqlalchemy.org/ .. _Flask: http://flask.pocoo.org/ .. _example sourcecode: http://github.com/mitsuhiko/flask-sqlalchemy/tree/master/examples/ .. include:: contents.rst.inc Flask-SQLAlchemy-2.1/docs/logo.pdf0000644000076500000240000005655312473657260017050 0ustar philstaff00000000000000%PDF-1.4 % 3 0 obj << /Length 4 0 R /Filter /FlateDecode >> stream xmIr:&)t51#٫ZHYП s__Z.wJ;Uw+W-߹ͯל]Rw9;x>yrpOr\[3zo}_LNڈgt̶W{o,&]]aUK+{@X1nnugc/apGYuϵ>h}߯I_aOo\n"p͊( pon1ͤbs1Z&rK{ Psa8=F ﻻ7m n;|+B w)DS#,~ +8R\@WWnl?p8mh K,jw{%cX}l>X/~D{xanF2++侗҅bjrThx_hs}OR=M&+~zD׻qۻ-d7 u.sӍ gpq'^khݻ~g/ݫ ɹ<ڿi%-0GW^4}4p4٧/߮ {n0TE@U| L''+_Yq3HNb}w\`ceIY}ۉm/"/&mtnifx{Oq5@ݧ&싷MF pg!Y&&sO~w nm{#@?xuX ݆]99E쭞4sM`;˷@Uem8,Ex1#U``{R{I>K!}U __ t={% ЖϟG`Y3bQ3Ϯ"|p@ikM'F{صG|}~{`pctqB6NB{p8#]_om,sςiCRMBE/i"&݁G6 qdg߸ (f#p/ 75P2uu z}v#obž(H><7YϾD?3;Cco|j >c'xMhVIO7}D Iظir#zg_}Mt=J7gA%3SKWik’DH?bwT}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@x$v8I-};{R$oRXuETO? JT"PEi1ȼpH5vpc{?fI~耊= q #]B) sbKb Vy'y` RE)FY>]jk+( X efNJ~<~t0 5tӠLg93".3~9.9 endstream endobj 4 0 obj 23043 endobj 2 0 obj << /ExtGState << /a0 << /CA 1 /ca 1 >> >> >> endobj 5 0 obj << /Type /Page /Parent 1 0 R /MediaBox [ 0 0 368 144 ] /Contents 3 0 R /Group << /Type /Group /S /Transparency /CS /DeviceRGB >> /Resources 2 0 R >> endobj 1 0 obj << /Type /Pages /Kids [ 5 0 R ] /Count 1 >> endobj 6 0 obj << /Creator (cairo 1.8.6 (http://cairographics.org)) /Producer (cairo 1.8.6 (http://cairographics.org)) >> endobj 7 0 obj << /Type /Catalog /Pages 1 0 R >> endobj xref 0 8 0000000000 65535 f 0000023430 00000 n 0000023158 00000 n 0000000015 00000 n 0000023134 00000 n 0000023230 00000 n 0000023495 00000 n 0000023620 00000 n trailer << /Size 8 /Root 7 0 R /Info 6 0 R >> startxref 23672 %%EOF Flask-SQLAlchemy-2.1/docs/make.bat0000644000076500000240000001003612473657260017004 0ustar philstaff00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Flask-SQLAlchemy.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Flask-SQLAlchemy.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end Flask-SQLAlchemy-2.1/docs/Makefile0000644000076500000240000001102612473657260017037 0ustar philstaff00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Flask-SQLAlchemy.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Flask-SQLAlchemy.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Flask-SQLAlchemy" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Flask-SQLAlchemy" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." Flask-SQLAlchemy-2.1/docs/models.rst0000644000076500000240000001377312473657260017427 0ustar philstaff00000000000000.. _models: .. currentmodule:: flask.ext.sqlalchemy Declaring Models ================ Generally Flask-SQLAlchemy behaves like a properly configured declarative base from the :mod:`~sqlalchemy.ext.declarative` extension. As such we recommend reading the SQLAlchemy docs for a full reference. However the most common use cases are also documented here. Things to keep in mind: - The baseclass for all your models is called `db.Model`. It's stored on the SQLAlchemy instance you have to create. See :ref:`quickstart` for more details. - Some parts that are required in SQLAlchemy are optional in Flask-SQLAlchemy. For instance the table name is automatically set for you unless overridden. It's derived from the class name converted to lowercase and with “CamelCase” converted to “camel_case”. Simple Example -------------- A very simple example:: class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '' % self.username Use :class:`~sqlalchemy.Column` to define a column. The name of the column is the name you assign it to. If you want to use a different name in the table you can provide an optional first argument which is a string with the desired column name. Primary keys are marked with ``primary_key=True``. Multiple keys can be marked as primary keys in which case they become a compound primary key. The types of the column are the first argument to :class:`~sqlalchemy.Column`. You can either provide them directly or call them to further specify them (like providing a length). The following types are the most common: =================== ===================================== `Integer` an integer `String` (size) a string with a maximum length `Text` some longer unicode text `DateTime` date and time expressed as Python :mod:`~datetime.datetime` object. `Float` stores floating point values `Boolean` stores a boolean value `PickleType` stores a pickled Python object `LargeBinary` stores large arbitrary binary data =================== ===================================== One-to-Many Relationships ------------------------- The most common relationships are one-to-many relationships. Because relationships are declared before they are established you can use strings to refer to classes that are not created yet (for instance if `Person` defines a relationship to `Article` which is declared later in the file). Relationships are expressed with the :func:`~sqlalchemy.orm.relationship` function. However the foreign key has to be separately declared with the :class:`sqlalchemy.schema.ForeignKey` class:: class Person(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) addresses = db.relationship('Address', backref='person', lazy='dynamic') class Address(db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(50)) person_id = db.Column(db.Integer, db.ForeignKey('person.id')) What does ``db.relationship()`` do? That function returns a new property that can do multiple things. In this case we told it to point to the `Address` class and load multiple of those. How does it know that this will return more than one address? Because SQLAlchemy guesses a useful default from your declaration. If you would want to have a one-to-one relationship you can pass ``uselist=False`` to :func:`~sqlalchemy.orm.relationship`. So what do `backref` and `lazy` mean? `backref` is a simple way to also declare a new property on the `Address` class. You can then also use ``my_address.person`` to get to the person at that address. `lazy` defines when SQLAlchemy will load the data from the database: - ``'select'`` (which is the default) means that SQLAlchemy will load the data as necessary in one go using a standard select statement. - ``'joined'`` tells SQLAlchemy to load the relationship in the same query as the parent using a `JOIN` statement. - ``'subquery'`` works like ``'joined'`` but instead SQLAlchemy will use a subquery. - ``'dynamic'`` is special and useful if you have many items. Instead of loading the items SQLAlchemy will return another query object which you can further refine before loading the items. This is usually what you want if you expect more than a handful of items for this relationship. How do you define the lazy status for backrefs? By using the :func:`~sqlalchemy.orm.backref` function:: class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) addresses = db.relationship('Address', backref=db.backref('person', lazy='joined'), lazy='dynamic') Many-to-Many Relationships -------------------------- If you want to use many-to-many relationships you will need to define a helper table that is used for the relationship. For this helper table it is strongly recommended to *not* use a model but an actual table:: tags = db.Table('tags', db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')), db.Column('page_id', db.Integer, db.ForeignKey('page.id')) ) class Page(db.Model): id = db.Column(db.Integer, primary_key=True) tags = db.relationship('Tag', secondary=tags, backref=db.backref('pages', lazy='dynamic')) class Tag(db.Model): id = db.Column(db.Integer, primary_key=True) Here we configured `Page.tags` to be a list of tags once loaded because we don't expect too many tags per page. The list of pages per tag (`Tag.pages`) however is a dynamic backref. As mentioned above this means that you will get a query object back you can use to fire a select yourself. Flask-SQLAlchemy-2.1/docs/queries.rst0000644000076500000240000001006412473657260017607 0ustar philstaff00000000000000.. currentmodule:: flask.ext.sqlalchemy Select, Insert, Delete ====================== Now that you have :ref:`declared models ` it's time to query the data from the database. We will be using the model definitions from the :ref:`quickstart` chapter. Inserting Records ----------------- Before we can query something we will have to insert some data. All your models should have a constructor, so make sure to add one if you forgot. Constructors are only used by you, not by SQLAlchemy internally so it's entirely up to you how you define them. Inserting data into the database is a three step process: 1. Create the Python object 2. Add it to the session 3. Commit the session The session here is not the Flask session, but the Flask-SQLAlchemy one. It is essentially a beefed up version of a database transaction. This is how it works: >>> from yourapp import User >>> me = User('admin', 'admin@example.com') >>> db.session.add(me) >>> db.session.commit() Alright, that was not hard. What happens at what point? Before you add the object to the session, SQLAlchemy basically does not plan on adding it to the transaction. That is good because you can still discard the changes. For example think about creating the post at a page but you only want to pass the post to the template for preview rendering instead of storing it in the database. The :func:`~sqlalchemy.orm.session.Session.add` function call then adds the object. It will issue an `INSERT` statement for the database but because the transaction is still not committed you won't get an ID back immediately. If you do the commit, your user will have an ID: >>> me.id 1 Deleting Records ---------------- Deleting records is very similar, instead of :func:`~sqlalchemy.orm.session.Session.add` use :func:`~sqlalchemy.orm.session.Session.delete`: >>> db.session.delete(me) >>> db.session.commit() Querying Records ---------------- So how do we get data back out of our database? For this purpose Flask-SQLAlchemy provides a :attr:`~Model.query` attribute on your :class:`Model` class. When you access it you will get back a new query object over all records. You can then use methods like :func:`~sqlalchemy.orm.query.Query.filter` to filter the records before you fire the select with :func:`~sqlalchemy.orm.query.Query.all` or :func:`~sqlalchemy.orm.query.Query.first`. If you want to go by primary key you can also use :func:`~sqlalchemy.orm.query.Query.get`. The following queries assume following entries in the database: =========== =========== ===================== `id` `username` `email` 1 admin admin@example.com 2 peter peter@example.org 3 guest guest@example.com =========== =========== ===================== Retrieve a user by username: >>> peter = User.query.filter_by(username='peter').first() >>> peter.id 1 >>> peter.email u'peter@example.org' Same as above but for a non existing username gives `None`: >>> missing = User.query.filter_by(username='missing').first() >>> missing is None True Selecting a bunch of users by a more complex expression: >>> User.query.filter(User.email.endswith('@example.com')).all() [, ] Ordering users by something: >>> User.query.order_by(User.username) [, , ] Limiting users: >>> User.query.limit(1).all() [] Getting user by primary key: >>> User.query.get(1) Queries in Views ---------------- If you write a Flask view function it's often very handy to return a 404 error for missing entries. Because this is a very common idiom, Flask-SQLAlchemy provides a helper for this exact purpose. Instead of :meth:`~sqlalchemy.orm.query.Query.get` one can use :meth:`~Query.get_or_404` and instead of :meth:`~sqlalchemy.orm.query.Query.first` :meth:`~Query.first_or_404`. This will raise 404 errors instead of returning `None`:: @app.route('/user/') def show_user(username): user = User.query.filter_by(username=username).first_or_404() return render_template('show_user.html', user=user) Flask-SQLAlchemy-2.1/docs/quickstart.rst0000644000076500000240000001145612555752324020330 0ustar philstaff00000000000000.. _quickstart: Quickstart ========== .. currentmodule:: flask.ext.sqlalchemy Flask-SQLAlchemy is fun to use, incredibly easy for basic applications, and readily extends for larger applications. For the complete guide, checkout the API documentation on the :class:`SQLAlchemy` class. A Minimal Application --------------------- For the common case of having one Flask application all you have to do is to create your Flask application, load the configuration of choice and then create the :class:`SQLAlchemy` object by passing it the application. Once created, that object then contains all the functions and helpers from both :mod:`sqlalchemy` and :mod:`sqlalchemy.orm`. Furthermore it provides a class called `Model` that is a declarative base which can be used to declare models:: from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '' % self.username To create the initial database, just import the `db` object from an interactive Python shell and run the :meth:`SQLAlchemy.create_all` method to create the tables and database: >>> from yourapplication import db >>> db.create_all() Boom, and there is your database. Now to create some users: >>> from yourapplication import User >>> admin = User('admin', 'admin@example.com') >>> guest = User('guest', 'guest@example.com') But they are not yet in the database, so let's make sure they are: >>> db.session.add(admin) >>> db.session.add(guest) >>> db.session.commit() Accessing the data in database is easy as a pie: >>> users = User.query.all() [, ] >>> admin = User.query.filter_by(username='admin').first() Simple Relationships -------------------- SQLAlchemy connects to relational databases and what relational databases are really good at are relations. As such, we shall have an example of an application that uses two tables that have a relationship to each other:: from datetime import datetime 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 '' % self.title class Category(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) def __init__(self, name): self.name = name def __repr__(self): return '' % self.name First let's create some objects: >>> py = Category('Python') >>> p = Post('Hello Python!', 'Python is pretty cool', py) >>> db.session.add(py) >>> db.session.add(p) Now because we declared `posts` as dynamic relationship in the backref it shows up as query: >>> py.posts It behaves like a regular query object so we can ask it for all posts that are associated with our test “Python” category: >>> py.posts.all() [] Road to Enlightenment --------------------- The only things you need to know compared to plain SQLAlchemy are: 1. :class:`SQLAlchemy` gives you access to the following things: - all the functions and classes from :mod:`sqlalchemy` and :mod:`sqlalchemy.orm` - a preconfigured scoped session called `session` - the :attr:`~SQLAlchemy.metadata` - the :attr:`~SQLAlchemy.engine` - a :meth:`SQLAlchemy.create_all` and :meth:`SQLAlchemy.drop_all` methods to create and drop tables according to the models. - a :class:`Model` baseclass that is a configured declarative base. 2. The :class:`Model` declarative base class behaves like a regular Python class but has a `query` attribute attached that can be used to query the model. (:class:`Model` and :class:`BaseQuery`) 3. You have to commit the session, but you don't have to remove it at the end of the request, Flask-SQLAlchemy does that for you. Flask-SQLAlchemy-2.1/docs/signals.rst0000644000076500000240000000162512555752324017573 0ustar philstaff00000000000000Signalling Support ================== Connect to the following signals to get notified before and after changes are committed to the database. These changes are only tracked if ``SQLALCHEMY_TRACK_MODIFICATIONS`` is enabled in the config. .. versionadded:: 0.10 .. versionchanged:: 2.1 ``before_models_committed`` is triggered correctly. .. deprecated:: 2.1 This will be disabled by default in a future version. .. data:: models_committed This signal is sent when changed models were committed to the database. The sender is the application that emitted the changes. The receiver is passed the ``changes`` parameter with a list of tuples in the form ``(model instance, operation)``. The operation is one of ``'insert'``, ``'update'``, and ``'delete'``. .. data:: before_models_committed This signal works exactly like :data:`models_committed` but is emitted before the commit takes place. Flask-SQLAlchemy-2.1/flask_sqlalchemy/0000755000076500000240000000000012612401275017755 5ustar philstaff00000000000000Flask-SQLAlchemy-2.1/flask_sqlalchemy/__init__.py0000644000076500000240000010651612612401275022077 0ustar philstaff00000000000000# -*- coding: utf-8 -*- """ flaskext.sqlalchemy ~~~~~~~~~~~~~~~~~~~ Adds basic SQLAlchemy support to your application. :copyright: (c) 2014 by Armin Ronacher, Daniel Neuhäuser. :license: BSD, see LICENSE for more details. """ from __future__ import with_statement, absolute_import import os import re import sys import time import functools import warnings import sqlalchemy from math import ceil from functools import partial from flask import _request_ctx_stack, abort, has_request_context, request from flask.signals import Namespace from operator import itemgetter from threading import Lock from sqlalchemy import orm, event, inspect from sqlalchemy.orm.exc import UnmappedClassError from sqlalchemy.orm.session import Session as SessionBase from sqlalchemy.engine.url import make_url from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta from flask_sqlalchemy._compat import iteritems, itervalues, xrange, \ string_types # the best timer function for the platform if sys.platform == 'win32': _timer = time.clock else: _timer = time.time try: from flask import _app_ctx_stack except ImportError: _app_ctx_stack = None __version__ = '2.1' # Which stack should we use? _app_ctx_stack is new in 0.9 connection_stack = _app_ctx_stack or _request_ctx_stack _camelcase_re = re.compile(r'([A-Z]+)(?=[a-z0-9])') _signals = Namespace() models_committed = _signals.signal('models-committed') before_models_committed = _signals.signal('before-models-committed') def _make_table(db): def _make_table(*args, **kwargs): if len(args) > 1 and isinstance(args[1], db.Column): args = (args[0], db.metadata) + args[1:] info = kwargs.pop('info', None) or {} info.setdefault('bind_key', None) kwargs['info'] = info return sqlalchemy.Table(*args, **kwargs) return _make_table def _set_default_query_class(d): if 'query_class' not in d: d['query_class'] = BaseQuery def _wrap_with_default_query_class(fn): @functools.wraps(fn) def newfn(*args, **kwargs): _set_default_query_class(kwargs) if "backref" in kwargs: backref = kwargs['backref'] if isinstance(backref, string_types): backref = (backref, {}) _set_default_query_class(backref[1]) return fn(*args, **kwargs) return newfn def _include_sqlalchemy(obj): for module in sqlalchemy, sqlalchemy.orm: for key in module.__all__: if not hasattr(obj, key): setattr(obj, key, getattr(module, key)) # Note: obj.Table does not attempt to be a SQLAlchemy Table class. obj.Table = _make_table(obj) obj.relationship = _wrap_with_default_query_class(obj.relationship) obj.relation = _wrap_with_default_query_class(obj.relation) obj.dynamic_loader = _wrap_with_default_query_class(obj.dynamic_loader) obj.event = event class _DebugQueryTuple(tuple): statement = property(itemgetter(0)) parameters = property(itemgetter(1)) start_time = property(itemgetter(2)) end_time = property(itemgetter(3)) context = property(itemgetter(4)) @property def duration(self): return self.end_time - self.start_time def __repr__(self): return '' % ( self.statement, self.parameters, self.duration ) def _calling_context(app_path): frm = sys._getframe(1) while frm.f_back is not None: name = frm.f_globals.get('__name__') if name and (name == app_path or name.startswith(app_path + '.')): funcname = frm.f_code.co_name return '%s:%s (%s)' % ( frm.f_code.co_filename, frm.f_lineno, funcname ) frm = frm.f_back return '' class SignallingSession(SessionBase): """The signalling session is the default session that Flask-SQLAlchemy uses. It extends the default session system with bind selection and modification tracking. If you want to use a different session you can override the :meth:`SQLAlchemy.create_session` function. .. versionadded:: 2.0 .. versionadded:: 2.1 The `binds` option was added, which allows a session to be joined to an external transaction. """ def __init__(self, db, autocommit=False, autoflush=True, app=None, **options): #: The application that this session belongs to. self.app = app = db.get_app() track_modifications = app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] bind = options.pop('bind', None) or db.engine binds = options.pop('binds', None) or db.get_binds(app) if track_modifications is None or track_modifications: _SessionSignalEvents.register(self) SessionBase.__init__( self, autocommit=autocommit, autoflush=autoflush, bind=bind, binds=binds, **options ) def get_bind(self, mapper=None, clause=None): # mapper is None if someone tries to just get a connection if mapper is not None: info = getattr(mapper.mapped_table, 'info', {}) bind_key = info.get('bind_key') if bind_key is not None: state = get_state(self.app) return state.db.get_engine(self.app, bind=bind_key) return SessionBase.get_bind(self, mapper, clause) class _SessionSignalEvents(object): @classmethod def register(cls, session): if not hasattr(session, '_model_changes'): session._model_changes = {} event.listen(session, 'before_flush', cls.record_ops) event.listen(session, 'before_commit', cls.record_ops) event.listen(session, 'before_commit', cls.before_commit) event.listen(session, 'after_commit', cls.after_commit) event.listen(session, 'after_rollback', cls.after_rollback) @classmethod def unregister(cls, session): if hasattr(session, '_model_changes'): del session._model_changes event.remove(session, 'before_flush', cls.record_ops) event.remove(session, 'before_commit', cls.record_ops) event.remove(session, 'before_commit', cls.before_commit) event.remove(session, 'after_commit', cls.after_commit) event.remove(session, 'after_rollback', cls.after_rollback) @staticmethod def record_ops(session, flush_context=None, instances=None): try: d = session._model_changes except AttributeError: return for targets, operation in ((session.new, 'insert'), (session.dirty, 'update'), (session.deleted, 'delete')): for target in targets: state = inspect(target) key = state.identity_key if state.has_identity else id(target) d[key] = (target, operation) @staticmethod def before_commit(session): try: d = session._model_changes except AttributeError: return if d: before_models_committed.send(session.app, changes=list(d.values())) @staticmethod def after_commit(session): try: d = session._model_changes except AttributeError: return if d: models_committed.send(session.app, changes=list(d.values())) d.clear() @staticmethod def after_rollback(session): try: d = session._model_changes except AttributeError: return d.clear() class _EngineDebuggingSignalEvents(object): """Sets up handlers for two events that let us track the execution time of queries.""" def __init__(self, engine, import_name): self.engine = engine self.app_package = import_name def register(self): event.listen(self.engine, 'before_cursor_execute', self.before_cursor_execute) event.listen(self.engine, 'after_cursor_execute', self.after_cursor_execute) def before_cursor_execute(self, conn, cursor, statement, parameters, context, executemany): if connection_stack.top is not None: context._query_start_time = _timer() def after_cursor_execute(self, conn, cursor, statement, parameters, context, executemany): ctx = connection_stack.top if ctx is not None: queries = getattr(ctx, 'sqlalchemy_queries', None) if queries is None: queries = [] setattr(ctx, 'sqlalchemy_queries', queries) queries.append(_DebugQueryTuple(( statement, parameters, context._query_start_time, _timer(), _calling_context(self.app_package)))) def get_debug_queries(): """In debug mode Flask-SQLAlchemy will log all the SQL queries sent to the database. This information is available until the end of request which makes it possible to easily ensure that the SQL generated is the one expected on errors or in unittesting. If you don't want to enable the DEBUG mode for your unittests you can also enable the query recording by setting the ``'SQLALCHEMY_RECORD_QUERIES'`` config variable to `True`. This is automatically enabled if Flask is in testing mode. The value returned will be a list of named tuples with the following attributes: `statement` The SQL statement issued `parameters` The parameters for the SQL statement `start_time` / `end_time` Time the query started / the results arrived. Please keep in mind that the timer function used depends on your platform. These values are only useful for sorting or comparing. They do not necessarily represent an absolute timestamp. `duration` Time the query took in seconds `context` A string giving a rough estimation of where in your application query was issued. The exact format is undefined so don't try to reconstruct filename or function name. """ return getattr(connection_stack.top, 'sqlalchemy_queries', []) class Pagination(object): """Internal helper class returned by :meth:`BaseQuery.paginate`. You can also construct it from any other SQLAlchemy query object if you are working with other libraries. Additionally it is possible to pass `None` as query object in which case the :meth:`prev` and :meth:`next` will no longer work. """ def __init__(self, query, page, per_page, total, items): #: the unlimited query object that was used to create this #: pagination object. self.query = query #: the current page number (1 indexed) self.page = page #: the number of items to be displayed on a page. self.per_page = per_page #: the total number of items matching the query self.total = total #: the items for the current page self.items = items @property def pages(self): """The total number of pages""" if self.per_page == 0: pages = 0 else: pages = int(ceil(self.total / float(self.per_page))) return pages def prev(self, error_out=False): """Returns a :class:`Pagination` object for the previous page.""" assert self.query is not None, 'a query object is required ' \ 'for this method to work' return self.query.paginate(self.page - 1, self.per_page, error_out) @property def prev_num(self): """Number of the previous page.""" return self.page - 1 @property def has_prev(self): """True if a previous page exists""" return self.page > 1 def next(self, error_out=False): """Returns a :class:`Pagination` object for the next page.""" assert self.query is not None, 'a query object is required ' \ 'for this method to work' return self.query.paginate(self.page + 1, self.per_page, error_out) @property def has_next(self): """True if a next page exists.""" return self.page < self.pages @property def next_num(self): """Number of the next page""" return self.page + 1 def iter_pages(self, left_edge=2, left_current=2, right_current=5, right_edge=2): """Iterates over the page numbers in the pagination. The four parameters control the thresholds how many numbers should be produced from the sides. Skipped page numbers are represented as `None`. This is how you could render such a pagination in the templates: .. sourcecode:: html+jinja {% macro render_pagination(pagination, endpoint) %} {% endmacro %} """ last = 0 for num in xrange(1, self.pages + 1): if num <= left_edge or \ (num > self.page - left_current - 1 and \ num < self.page + right_current) or \ num > self.pages - right_edge: if last + 1 != num: yield None yield num last = num class BaseQuery(orm.Query): """The default query object used for models, and exposed as :attr:`~SQLAlchemy.Query`. This can be subclassed and replaced for individual models by setting the :attr:`~Model.query_class` attribute. This is a subclass of a standard SQLAlchemy :class:`~sqlalchemy.orm.query.Query` class and has all the methods of a standard query as well. """ def get_or_404(self, ident): """Like :meth:`get` but aborts with 404 if not found instead of returning `None`. """ rv = self.get(ident) if rv is None: abort(404) return rv def first_or_404(self): """Like :meth:`first` but aborts with 404 if not found instead of returning `None`. """ rv = self.first() if rv is None: abort(404) return rv def paginate(self, page=None, per_page=None, error_out=True): """Returns `per_page` items from page `page`. By default it will abort with 404 if no items were found and the page was larger than 1. This behavor can be disabled by setting `error_out` to `False`. If page or per_page are None, they will be retrieved from the request query. If the values are not ints and ``error_out`` is true, it will abort with 404. If there is no request or they aren't in the query, they default to page 1 and 20 respectively. Returns an :class:`Pagination` object. """ if has_request_context(): if page is None: try: page = int(request.args.get('page', 1)) except (TypeError, ValueError): if error_out: abort(404) page = 1 if per_page is None: try: per_page = int(request.args.get('per_page', 20)) except (TypeError, ValueError): if error_out: abort(404) per_page = 20 else: if page is None: page = 1 if per_page is None: per_page = 20 if error_out and page < 1: abort(404) items = self.limit(per_page).offset((page - 1) * per_page).all() if not items and page != 1 and error_out: abort(404) # No need to count if we're on the first page and there are fewer # items than we expected. if page == 1 and len(items) < per_page: total = len(items) else: total = self.order_by(None).count() return Pagination(self, page, per_page, total, items) class _QueryProperty(object): def __init__(self, sa): self.sa = sa def __get__(self, obj, type): try: mapper = orm.class_mapper(type) if mapper: return type.query_class(mapper, session=self.sa.session()) except UnmappedClassError: return None def _record_queries(app): if app.debug: return True rq = app.config['SQLALCHEMY_RECORD_QUERIES'] if rq is not None: return rq return bool(app.config.get('TESTING')) class _EngineConnector(object): def __init__(self, sa, app, bind=None): self._sa = sa self._app = app self._engine = None self._connected_for = None self._bind = bind self._lock = Lock() def get_uri(self): if self._bind is None: return self._app.config['SQLALCHEMY_DATABASE_URI'] binds = self._app.config.get('SQLALCHEMY_BINDS') or () assert self._bind in binds, \ 'Bind %r is not specified. Set it in the SQLALCHEMY_BINDS ' \ 'configuration variable' % self._bind return binds[self._bind] def get_engine(self): with self._lock: uri = self.get_uri() echo = self._app.config['SQLALCHEMY_ECHO'] if (uri, echo) == self._connected_for: return self._engine info = make_url(uri) options = {'convert_unicode': True} self._sa.apply_pool_defaults(self._app, options) self._sa.apply_driver_hacks(self._app, info, options) if echo: options['echo'] = True self._engine = rv = sqlalchemy.create_engine(info, **options) if _record_queries(self._app): _EngineDebuggingSignalEvents(self._engine, self._app.import_name).register() self._connected_for = (uri, echo) return rv def _should_set_tablename(bases, d): """Check what values are set by a class and its bases to determine if a tablename should be automatically generated. The class and its bases are checked in order of precedence: the class itself then each base in the order they were given at class definition. Abstract classes do not generate a tablename, although they may have set or inherited a tablename elsewhere. If a class defines a tablename or table, a new one will not be generated. Otherwise, if the class defines a primary key, a new name will be generated. This supports: * Joined table inheritance without explicitly naming sub-models. * Single table inheritance. * Inheriting from mixins or abstract models. :param bases: base classes of new class :param d: new class dict :return: True if tablename should be set """ if '__tablename__' in d or '__table__' in d or '__abstract__' in d: return False if any(v.primary_key for v in itervalues(d) if isinstance(v, sqlalchemy.Column)): return True for base in bases: if hasattr(base, '__tablename__') or hasattr(base, '__table__'): return False for name in dir(base): attr = getattr(base, name) if isinstance(attr, sqlalchemy.Column) and attr.primary_key: return True class _BoundDeclarativeMeta(DeclarativeMeta): def __new__(cls, name, bases, d): if _should_set_tablename(bases, d): def _join(match): word = match.group() if len(word) > 1: return ('_%s_%s' % (word[:-1], word[-1])).lower() return '_' + word.lower() d['__tablename__'] = _camelcase_re.sub(_join, name).lstrip('_') return DeclarativeMeta.__new__(cls, name, bases, d) def __init__(self, name, bases, d): bind_key = d.pop('__bind_key__', None) DeclarativeMeta.__init__(self, name, bases, d) if bind_key is not None: self.__table__.info['bind_key'] = bind_key def get_state(app): """Gets the state for the application""" assert 'sqlalchemy' in app.extensions, \ 'The sqlalchemy extension was not registered to the current ' \ 'application. Please make sure to call init_app() first.' return app.extensions['sqlalchemy'] class _SQLAlchemyState(object): """Remembers configuration for the (db, app) tuple.""" def __init__(self, db, app): self.db = db self.app = app self.connectors = {} class Model(object): """Baseclass for custom user models.""" #: the query class used. The :attr:`query` attribute is an instance #: of this class. By default a :class:`BaseQuery` is used. query_class = BaseQuery #: an instance of :attr:`query_class`. Can be used to query the #: database for instances of this model. query = None class SQLAlchemy(object): """This class is used to control the SQLAlchemy integration to one or more Flask applications. Depending on how you initialize the object it is usable right away or will attach as needed to a Flask application. There are two usage modes which work very similarly. One is binding the instance to a very specific Flask application:: app = Flask(__name__) db = SQLAlchemy(app) The second possibility is to create the object once and configure the application later to support it:: db = SQLAlchemy() def create_app(): app = Flask(__name__) db.init_app(app) return app The difference between the two is that in the first case methods like :meth:`create_all` and :meth:`drop_all` will work all the time but in the second case a :meth:`flask.Flask.app_context` has to exist. By default Flask-SQLAlchemy will apply some backend-specific settings to improve your experience with them. As of SQLAlchemy 0.6 SQLAlchemy will probe the library for native unicode support. If it detects unicode it will let the library handle that, otherwise do that itself. Sometimes this detection can fail in which case you might want to set `use_native_unicode` (or the ``SQLALCHEMY_NATIVE_UNICODE`` configuration key) to `False`. Note that the configuration key overrides the value you pass to the constructor. This class also provides access to all the SQLAlchemy functions and classes from the :mod:`sqlalchemy` and :mod:`sqlalchemy.orm` modules. So you can declare models like this:: class User(db.Model): username = db.Column(db.String(80), unique=True) pw_hash = db.Column(db.String(80)) You can still use :mod:`sqlalchemy` and :mod:`sqlalchemy.orm` directly, but note that Flask-SQLAlchemy customizations are available only through an instance of this :class:`SQLAlchemy` class. Query classes default to :class:`BaseQuery` for `db.Query`, `db.Model.query_class`, and the default query_class for `db.relationship` and `db.backref`. If you use these interfaces through :mod:`sqlalchemy` and :mod:`sqlalchemy.orm` directly, the default query class will be that of :mod:`sqlalchemy`. .. admonition:: Check types carefully Don't perform type or `isinstance` checks against `db.Table`, which emulates `Table` behavior but is not a class. `db.Table` exposes the `Table` interface, but is a function which allows omission of metadata. You may also define your own SessionExtension instances as well when defining your SQLAlchemy class instance. You may pass your custom instances to the `session_extensions` keyword. This can be either a single SessionExtension instance, or a list of SessionExtension instances. In the following use case we use the VersionedListener from the SQLAlchemy versioning examples.:: from history_meta import VersionedMeta, VersionedListener app = Flask(__name__) db = SQLAlchemy(app, session_extensions=[VersionedListener()]) class User(db.Model): __metaclass__ = VersionedMeta username = db.Column(db.String(80), unique=True) pw_hash = db.Column(db.String(80)) The `session_options` parameter can be used to override session options. If provided it's a dict of parameters passed to the session's constructor. .. versionadded:: 0.10 The `session_options` parameter was added. .. versionadded:: 0.16 `scopefunc` is now accepted on `session_options`. It allows specifying a custom function which will define the SQLAlchemy session's scoping. .. versionadded:: 2.1 The `metadata` parameter was added. This allows for setting custom naming conventions among other, non-trivial things. """ def __init__(self, app=None, use_native_unicode=True, session_options=None, metadata=None): if session_options is None: session_options = {} session_options.setdefault('scopefunc', connection_stack.__ident_func__) self.use_native_unicode = use_native_unicode self.session = self.create_scoped_session(session_options) self.Model = self.make_declarative_base(metadata) self.Query = BaseQuery self._engine_lock = Lock() self.app = app _include_sqlalchemy(self) if app is not None: self.init_app(app) @property def metadata(self): """Returns the metadata""" return self.Model.metadata def create_scoped_session(self, options=None): """Helper factory method that creates a scoped session. It internally calls :meth:`create_session`. """ if options is None: options = {} scopefunc = options.pop('scopefunc', None) return orm.scoped_session(partial(self.create_session, options), scopefunc=scopefunc) def create_session(self, options): """Creates the session. The default implementation returns a :class:`SignallingSession`. .. versionadded:: 2.0 """ return SignallingSession(self, **options) def make_declarative_base(self, metadata=None): """Creates the declarative base.""" base = declarative_base(cls=Model, name='Model', metadata=metadata, metaclass=_BoundDeclarativeMeta) base.query = _QueryProperty(self) return base def init_app(self, app): """This callback can be used to initialize an application for the use with this database setup. Never use a database in the context of an application not initialized that way or connections will leak. """ app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite://') app.config.setdefault('SQLALCHEMY_BINDS', None) app.config.setdefault('SQLALCHEMY_NATIVE_UNICODE', None) app.config.setdefault('SQLALCHEMY_ECHO', False) app.config.setdefault('SQLALCHEMY_RECORD_QUERIES', None) app.config.setdefault('SQLALCHEMY_POOL_SIZE', None) app.config.setdefault('SQLALCHEMY_POOL_TIMEOUT', None) app.config.setdefault('SQLALCHEMY_POOL_RECYCLE', None) app.config.setdefault('SQLALCHEMY_MAX_OVERFLOW', None) app.config.setdefault('SQLALCHEMY_COMMIT_ON_TEARDOWN', False) track_modifications = app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', None) if track_modifications is None: warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.') if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['sqlalchemy'] = _SQLAlchemyState(self, app) # 0.9 and later if hasattr(app, 'teardown_appcontext'): teardown = app.teardown_appcontext # 0.7 to 0.8 elif hasattr(app, 'teardown_request'): teardown = app.teardown_request # Older Flask versions else: if app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']: raise RuntimeError("Commit on teardown requires Flask >= 0.7") teardown = app.after_request @teardown def shutdown_session(response_or_exc): if app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']: if response_or_exc is None: self.session.commit() self.session.remove() return response_or_exc def apply_pool_defaults(self, app, options): def _setdefault(optionkey, configkey): value = app.config[configkey] if value is not None: options[optionkey] = value _setdefault('pool_size', 'SQLALCHEMY_POOL_SIZE') _setdefault('pool_timeout', 'SQLALCHEMY_POOL_TIMEOUT') _setdefault('pool_recycle', 'SQLALCHEMY_POOL_RECYCLE') _setdefault('max_overflow', 'SQLALCHEMY_MAX_OVERFLOW') def apply_driver_hacks(self, app, info, options): """This method is called before engine creation and used to inject driver specific hacks into the options. The `options` parameter is a dictionary of keyword arguments that will then be used to call the :func:`sqlalchemy.create_engine` function. The default implementation provides some saner defaults for things like pool sizes for MySQL and sqlite. Also it injects the setting of `SQLALCHEMY_NATIVE_UNICODE`. """ if info.drivername.startswith('mysql'): info.query.setdefault('charset', 'utf8') if info.drivername != 'mysql+gaerdbms': options.setdefault('pool_size', 10) options.setdefault('pool_recycle', 7200) elif info.drivername == 'sqlite': pool_size = options.get('pool_size') detected_in_memory = False # we go to memory and the pool size was explicitly set to 0 # which is fail. Let the user know that if info.database in (None, '', ':memory:'): detected_in_memory = True from sqlalchemy.pool import StaticPool options['poolclass'] = StaticPool if 'connect_args' not in options: options['connect_args'] = {} options['connect_args']['check_same_thread'] = False if pool_size == 0: raise RuntimeError('SQLite in memory database with an ' 'empty queue not possible due to data ' 'loss.') # if pool size is None or explicitly set to 0 we assume the # user did not want a queue for this sqlite connection and # hook in the null pool. elif not pool_size: from sqlalchemy.pool import NullPool options['poolclass'] = NullPool # if it's not an in memory database we make the path absolute. if not detected_in_memory: info.database = os.path.join(app.root_path, info.database) unu = app.config['SQLALCHEMY_NATIVE_UNICODE'] if unu is None: unu = self.use_native_unicode if not unu: options['use_native_unicode'] = False @property def engine(self): """Gives access to the engine. If the database configuration is bound to a specific application (initialized with an application) this will always return a database connection. If however the current application is used this might raise a :exc:`RuntimeError` if no application is active at the moment. """ return self.get_engine(self.get_app()) def make_connector(self, app, bind=None): """Creates the connector for a given state and bind.""" return _EngineConnector(self, app, bind) def get_engine(self, app, bind=None): """Returns a specific engine. .. versionadded:: 0.12 """ with self._engine_lock: state = get_state(app) connector = state.connectors.get(bind) if connector is None: connector = self.make_connector(app, bind) state.connectors[bind] = connector return connector.get_engine() def get_app(self, reference_app=None): """Helper method that implements the logic to look up an application. """ if reference_app is not None: return reference_app if self.app is not None: return self.app ctx = connection_stack.top if ctx is not None: return ctx.app raise RuntimeError('application not registered on db ' 'instance and no application bound ' 'to current context') def get_tables_for_bind(self, bind=None): """Returns a list of all tables relevant for a bind.""" result = [] for table in itervalues(self.Model.metadata.tables): if table.info.get('bind_key') == bind: result.append(table) return result def get_binds(self, app=None): """Returns a dictionary with a table->engine mapping. This is suitable for use of sessionmaker(binds=db.get_binds(app)). """ app = self.get_app(app) binds = [None] + list(app.config.get('SQLALCHEMY_BINDS') or ()) retval = {} for bind in binds: engine = self.get_engine(app, bind) tables = self.get_tables_for_bind(bind) retval.update(dict((table, engine) for table in tables)) return retval def _execute_for_all_tables(self, app, bind, operation, skip_tables=False): app = self.get_app(app) if bind == '__all__': binds = [None] + list(app.config.get('SQLALCHEMY_BINDS') or ()) elif isinstance(bind, string_types) or bind is None: binds = [bind] else: binds = bind for bind in binds: extra = {} if not skip_tables: tables = self.get_tables_for_bind(bind) extra['tables'] = tables op = getattr(self.Model.metadata, operation) op(bind=self.get_engine(app, bind), **extra) def create_all(self, bind='__all__', app=None): """Creates all tables. .. versionchanged:: 0.12 Parameters were added """ self._execute_for_all_tables(app, bind, 'create_all') def drop_all(self, bind='__all__', app=None): """Drops all tables. .. versionchanged:: 0.12 Parameters were added """ self._execute_for_all_tables(app, bind, 'drop_all') def reflect(self, bind='__all__', app=None): """Reflects tables from the database. .. versionchanged:: 0.12 Parameters were added """ self._execute_for_all_tables(app, bind, 'reflect', skip_tables=True) def __repr__(self): app = None if self.app is not None: app = self.app else: ctx = connection_stack.top if ctx is not None: app = ctx.app return '<%s engine=%r>' % ( self.__class__.__name__, app and app.config['SQLALCHEMY_DATABASE_URI'] or None ) Flask-SQLAlchemy-2.1/flask_sqlalchemy/_compat.py0000644000076500000240000000115712473657260021771 0ustar philstaff00000000000000# -*- coding: utf-8 -*- """ flaskext.sqlalchemy._compat ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Internal Python 2.x/3.x compatibility layer. :copyright: (c) 2013 by Daniel Neuhäuser :license: BSD, see LICENSE for more details. """ import sys PY2 = sys.version_info[0] == 2 if PY2: def iteritems(d): return d.iteritems() def itervalues(d): return d.itervalues() xrange = xrange string_types = (unicode, bytes) else: def iteritems(d): return iter(d.items()) def itervalues(d): return iter(d.values()) xrange = range string_types = (str, ) Flask-SQLAlchemy-2.1/Flask_SQLAlchemy.egg-info/0000755000076500000240000000000012612401275021207 5ustar philstaff00000000000000Flask-SQLAlchemy-2.1/Flask_SQLAlchemy.egg-info/dependency_links.txt0000644000076500000240000000000112612401275025255 0ustar philstaff00000000000000 Flask-SQLAlchemy-2.1/Flask_SQLAlchemy.egg-info/not-zip-safe0000644000076500000240000000000112505030216023427 0ustar philstaff00000000000000 Flask-SQLAlchemy-2.1/Flask_SQLAlchemy.egg-info/PKG-INFO0000644000076500000240000000242112612401275022303 0ustar philstaff00000000000000Metadata-Version: 1.1 Name: Flask-SQLAlchemy Version: 2.1 Summary: Adds SQLAlchemy support to your Flask application Home-page: http://github.com/mitsuhiko/flask-sqlalchemy Author: Phil Howell Author-email: phil@quae.co.uk License: BSD Description: Flask-SQLAlchemy ---------------- Adds SQLAlchemy support to your Flask application. Links ````` * `documentation `_ * `development version `_ Platform: any Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Flask-SQLAlchemy-2.1/Flask_SQLAlchemy.egg-info/requires.txt0000644000076500000240000000003312612401275023603 0ustar philstaff00000000000000Flask>=0.10 SQLAlchemy>=0.7Flask-SQLAlchemy-2.1/Flask_SQLAlchemy.egg-info/SOURCES.txt0000644000076500000240000000140312612401275023071 0ustar philstaff00000000000000CHANGES LICENSE MANIFEST.in README setup.cfg setup.py test_sqlalchemy.py Flask_SQLAlchemy.egg-info/PKG-INFO Flask_SQLAlchemy.egg-info/SOURCES.txt Flask_SQLAlchemy.egg-info/dependency_links.txt Flask_SQLAlchemy.egg-info/not-zip-safe Flask_SQLAlchemy.egg-info/requires.txt Flask_SQLAlchemy.egg-info/top_level.txt docs/Makefile docs/api.rst docs/binds.rst docs/changelog.rst docs/conf.py docs/config.rst docs/contents.rst.inc docs/contexts.rst docs/flaskstyle.sty docs/index.rst docs/logo.pdf docs/make.bat docs/models.rst docs/queries.rst docs/quickstart.rst docs/signals.rst docs/_static/flask-sqlalchemy-small.png docs/_static/flask-sqlalchemy.png docs/_templates/sidebarintro.html docs/_templates/sidebarlogo.html flask_sqlalchemy/__init__.py flask_sqlalchemy/_compat.pyFlask-SQLAlchemy-2.1/Flask_SQLAlchemy.egg-info/top_level.txt0000644000076500000240000000002112612401275023732 0ustar philstaff00000000000000flask_sqlalchemy Flask-SQLAlchemy-2.1/LICENSE0000644000076500000240000000266112473657260015461 0ustar philstaff00000000000000Copyright (c) 2014 by Armin Ronacher. Some rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Flask-SQLAlchemy-2.1/MANIFEST.in0000644000076500000240000000023212473657260016202 0ustar philstaff00000000000000include LICENSE CHANGES *.py recursive-include docs * recursive-exclude docs *.pyc recursive-exclude docs *.pyo prune docs/_build prune docs/_themes/.git Flask-SQLAlchemy-2.1/PKG-INFO0000644000076500000240000000242112612401275015527 0ustar philstaff00000000000000Metadata-Version: 1.1 Name: Flask-SQLAlchemy Version: 2.1 Summary: Adds SQLAlchemy support to your Flask application Home-page: http://github.com/mitsuhiko/flask-sqlalchemy Author: Phil Howell Author-email: phil@quae.co.uk License: BSD Description: Flask-SQLAlchemy ---------------- Adds SQLAlchemy support to your Flask application. Links ````` * `documentation `_ * `development version `_ Platform: any Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Flask-SQLAlchemy-2.1/README0000644000076500000240000000266512555752324015336 0ustar philstaff00000000000000 // Flask-SQLAlchemy // ~ What is Flask-SQLAlchemy? Flask-SQLAlchemy is a Flask microframework extension which adds support for the SQLAlchemy SQL toolkit/ORM. ~ What's the latest version? 2.0 is the most recent stable version. 2.1 is slated for release in early February. ~ What do I need? SQLAlchemy, and Flask 0.10 or later. `pip` or `easy_install` will install them for you if you do `pip install Flask-SQLAlchemy`. We encourage you to use a virtualenv. Check the docs for complete installation and usage instructions. ~ Where are the docs? Go to http://flask-sqlalchemy.pocoo.org/ for a prebuilt version of the current documentation. Otherwise build them yourself from the sphinx sources in the docs folder. ~ Where are the tests? Good that you're asking. To run the tests use the `test_sqlalchemy.py` file: $ python test_sqlalchemy.py If you just want one particular testcase to run you can provide it on the command line: $ python test_sqlalchemy.py PaginationTestCase In case you have `tox` installed, you can also run that to have virtualenvs created automatically and tests run inside of them at your convenience. Running just `tox` is enough: $ tox ~ Where can I get help? Join us on the #pocoo IRC channel on irc.freenode.net. Flask-SQLAlchemy-2.1/setup.cfg0000644000076500000240000000022012612401275016246 0ustar philstaff00000000000000[egg_info] tag_date = 0 tag_build = tag_svn_revision = 0 [aliases] release = egg_info -RDb '' [pytest] norecursedirs = .* _* scripts {args} Flask-SQLAlchemy-2.1/setup.py0000644000076500000240000000301712612401275016146 0ustar philstaff00000000000000""" Flask-SQLAlchemy ---------------- Adds SQLAlchemy support to your Flask application. Links ````` * `documentation `_ * `development version `_ """ from setuptools import setup setup( name='Flask-SQLAlchemy', version='2.1', url='http://github.com/mitsuhiko/flask-sqlalchemy', license='BSD', author='Armin Ronacher', author_email='armin.ronacher@active-4.com', maintainer='Phil Howell', maintainer_email='phil@quae.co.uk', description='Adds SQLAlchemy support to your Flask application', long_description=__doc__, packages=['flask_sqlalchemy'], zip_safe=False, platforms='any', install_requires=[ 'Flask>=0.10', 'SQLAlchemy>=0.7' ], test_suite='test_sqlalchemy.suite', classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ] ) Flask-SQLAlchemy-2.1/test_sqlalchemy.py0000644000076500000240000005657012555752324020235 0ustar philstaff00000000000000from __future__ import with_statement import atexit import unittest from datetime import datetime import flask import flask_sqlalchemy as sqlalchemy from sqlalchemy import MetaData from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.orm import sessionmaker def make_todo_model(db): class Todo(db.Model): __tablename__ = 'todos' id = db.Column('todo_id', db.Integer, primary_key=True) title = db.Column(db.String(60)) text = db.Column(db.String) done = db.Column(db.Boolean) pub_date = db.Column(db.DateTime) def __init__(self, title, text): self.title = title self.text = text self.done = False self.pub_date = datetime.utcnow() return Todo class BasicAppTestCase(unittest.TestCase): def setUp(self): app = flask.Flask(__name__) app.config['SQLALCHEMY_ENGINE'] = 'sqlite://' app.config['TESTING'] = True db = sqlalchemy.SQLAlchemy(app) self.Todo = make_todo_model(db) @app.route('/') def index(): return '\n'.join(x.title for x in self.Todo.query.all()) @app.route('/add', methods=['POST']) def add(): form = flask.request.form todo = self.Todo(form['title'], form['text']) db.session.add(todo) db.session.commit() return 'added' db.create_all() self.app = app self.db = db def tearDown(self): self.db.drop_all() def test_basic_insert(self): c = self.app.test_client() c.post('/add', data=dict(title='First Item', text='The text')) c.post('/add', data=dict(title='2nd Item', text='The text')) rv = c.get('/') self.assertEqual(rv.data, b'First Item\n2nd Item') def test_query_recording(self): with self.app.test_request_context(): todo = self.Todo('Test 1', 'test') self.db.session.add(todo) self.db.session.commit() queries = sqlalchemy.get_debug_queries() self.assertEqual(len(queries), 1) query = queries[0] self.assertTrue('insert into' in query.statement.lower()) self.assertEqual(query.parameters[0], 'Test 1') self.assertEqual(query.parameters[1], 'test') self.assertTrue('test_sqlalchemy.py' in query.context) self.assertTrue('test_query_recording' in query.context) def test_helper_api(self): self.assertEqual(self.db.metadata, self.db.Model.metadata) class CustomMetaDataTestCase(unittest.TestCase): def setUp(self): self.app = flask.Flask(__name__) self.app.config['SQLALCHEMY_ENGINE'] = 'sqlite://' self.app.config['TESTING'] = True def test_custom_metadata_positive(self): convention = { "ix": 'ix_%(column_0_label)s', "uq": "uq_%(table_name)s_%(column_0_name)s", "ck": "ck_%(table_name)s_%(constraint_name)s", "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", "pk": "pk_%(table_name)s" } metadata = MetaData(naming_convention=convention) db = sqlalchemy.SQLAlchemy(self.app, metadata=metadata) self.db = db class One(db.Model): id = db.Column(db.Integer, primary_key=True) myindex = db.Column(db.Integer, index=True) class Two(db.Model): id = db.Column(db.Integer, primary_key=True) one_id = db.Column(db.Integer, db.ForeignKey(One.id)) myunique = db.Column(db.Integer, unique=True) self.assertEqual(list(One.__table__.constraints)[0].name, 'pk_one') self.assertEqual(list(One.__table__.indexes)[0].name, 'ix_one_myindex') self.assertTrue('fk_two_one_id_one' in [c.name for c in Two.__table__.constraints]) self.assertTrue('uq_two_myunique' in [c.name for c in Two.__table__.constraints]) self.assertTrue('pk_two' in [c.name for c in Two.__table__.constraints]) def test_custom_metadata_negative(self): db = sqlalchemy.SQLAlchemy(self.app, metadata=None) self.db = db class One(db.Model): id = db.Column(db.Integer, primary_key=True) myindex = db.Column(db.Integer, index=True) class Two(db.Model): id = db.Column(db.Integer, primary_key=True) one_id = db.Column(db.Integer, db.ForeignKey(One.id)) myunique = db.Column(db.Integer, unique=True) self.assertNotEqual(list(One.__table__.constraints)[0].name, 'pk_one') self.assertFalse('fk_two_one_id_one' in [c.name for c in Two.__table__.constraints]) self.assertFalse('uq_two_myunique' in [c.name for c in Two.__table__.constraints]) self.assertFalse('pk_two' in [c.name for c in Two.__table__.constraints]) class TestQueryProperty(unittest.TestCase): def setUp(self): self.app = flask.Flask(__name__) self.app.config['SQLALCHEMY_ENGINE'] = 'sqlite://' self.app.config['TESTING'] = True def test_no_app_bound(self): db = sqlalchemy.SQLAlchemy() db.init_app(self.app) Todo = make_todo_model(db) # If no app is bound to the SQLAlchemy instance, a # request context is required to access Model.query. self.assertRaises(RuntimeError, getattr, Todo, 'query') with self.app.test_request_context(): db.create_all() todo = Todo('Test', 'test') db.session.add(todo) db.session.commit() self.assertEqual(len(Todo.query.all()), 1) def test_app_bound(self): db = sqlalchemy.SQLAlchemy(self.app) Todo = make_todo_model(db) db.create_all() # If an app was passed to the SQLAlchemy constructor, # the query property is always available. todo = Todo('Test', 'test') db.session.add(todo) db.session.commit() self.assertEqual(len(Todo.query.all()), 1) class SignallingTestCase(unittest.TestCase): def setUp(self): self.app = app = flask.Flask(__name__) app.config['SQLALCHEMY_ENGINE'] = 'sqlite://' app.config['TESTING'] = True self.db = sqlalchemy.SQLAlchemy(app) self.Todo = make_todo_model(self.db) self.db.create_all() def tearDown(self): self.db.drop_all() def test_before_committed(self): class Namespace(object): is_received = False def before_committed(sender, changes): Namespace.is_received = True with sqlalchemy.before_models_committed.connected_to(before_committed, sender=self.app): todo = self.Todo('Awesome', 'the text') self.db.session.add(todo) self.db.session.commit() self.assertTrue(Namespace.is_received) def test_model_signals(self): recorded = [] def committed(sender, changes): self.assertTrue(isinstance(changes, list)) recorded.extend(changes) with sqlalchemy.models_committed.connected_to(committed, sender=self.app): todo = self.Todo('Awesome', 'the text') self.db.session.add(todo) self.assertEqual(len(recorded), 0) self.db.session.commit() self.assertEqual(len(recorded), 1) self.assertEqual(recorded[0][0], todo) self.assertEqual(recorded[0][1], 'insert') del recorded[:] todo.text = 'aha' self.db.session.commit() self.assertEqual(len(recorded), 1) self.assertEqual(recorded[0][0], todo) self.assertEqual(recorded[0][1], 'update') del recorded[:] self.db.session.delete(todo) self.db.session.commit() self.assertEqual(len(recorded), 1) self.assertEqual(recorded[0][0], todo) self.assertEqual(recorded[0][1], 'delete') class TablenameTestCase(unittest.TestCase): def test_name(self): app = flask.Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db = sqlalchemy.SQLAlchemy(app) class FOOBar(db.Model): id = db.Column(db.Integer, primary_key=True) class BazBar(db.Model): id = db.Column(db.Integer, primary_key=True) class Ham(db.Model): __tablename__ = 'spam' id = db.Column(db.Integer, primary_key=True) self.assertEqual(FOOBar.__tablename__, 'foo_bar') self.assertEqual(BazBar.__tablename__, 'baz_bar') self.assertEqual(Ham.__tablename__, 'spam') def test_single_name(self): """Single table inheritance should not set a new name.""" app = flask.Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db = sqlalchemy.SQLAlchemy(app) class Duck(db.Model): id = db.Column(db.Integer, primary_key=True) class Mallard(Duck): pass self.assertEqual(Mallard.__tablename__, 'duck') def test_joined_name(self): """Model has a separate primary key; it should set a new name.""" app = flask.Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db = sqlalchemy.SQLAlchemy(app) class Duck(db.Model): id = db.Column(db.Integer, primary_key=True) class Donald(Duck): id = db.Column(db.Integer, db.ForeignKey(Duck.id), primary_key=True) self.assertEqual(Donald.__tablename__, 'donald') def test_mixin_name(self): """Primary key provided by mixin should still allow model to set tablename.""" app = flask.Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db = sqlalchemy.SQLAlchemy(app) class Base(object): id = db.Column(db.Integer, primary_key=True) class Duck(Base, db.Model): pass self.assertFalse(hasattr(Base, '__tablename__')) self.assertEqual(Duck.__tablename__, 'duck') def test_abstract_name(self): """Abstract model should not set a name. Subclass should set a name.""" app = flask.Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db = sqlalchemy.SQLAlchemy(app) class Base(db.Model): __abstract__ = True id = db.Column(db.Integer, primary_key=True) class Duck(Base): pass self.assertFalse(hasattr(Base, '__tablename__')) self.assertEqual(Duck.__tablename__, 'duck') def test_complex_inheritance(self): """Joined table inheritance, but the new primary key is provided by a mixin, not directly on the class.""" app = flask.Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db = sqlalchemy.SQLAlchemy(app) class Duck(db.Model): id = db.Column(db.Integer, primary_key=True) class IdMixin(object): @declared_attr def id(cls): return db.Column(db.Integer, db.ForeignKey(Duck.id), primary_key=True) class RubberDuck(IdMixin, Duck): pass self.assertEqual(RubberDuck.__tablename__, 'rubber_duck') class PaginationTestCase(unittest.TestCase): def test_basic_pagination(self): p = sqlalchemy.Pagination(None, 1, 20, 500, []) self.assertEqual(p.page, 1) self.assertFalse(p.has_prev) self.assertTrue(p.has_next) self.assertEqual(p.total, 500) self.assertEqual(p.pages, 25) self.assertEqual(p.next_num, 2) self.assertEqual(list(p.iter_pages()), [1, 2, 3, 4, 5, None, 24, 25]) p.page = 10 self.assertEqual(list(p.iter_pages()), [1, 2, None, 8, 9, 10, 11, 12, 13, 14, None, 24, 25]) def test_pagination_pages_when_0_items_per_page(self): p = sqlalchemy.Pagination(None, 1, 0, 500, []) self.assertEqual(p.pages, 0) def test_query_paginate(self): app = flask.Flask(__name__) db = sqlalchemy.SQLAlchemy(app) Todo = make_todo_model(db) db.create_all() with app.app_context(): db.session.add_all([Todo('', '') for _ in range(100)]) db.session.commit() @app.route('/') def index(): p = Todo.query.paginate() return '{0} items retrieved'.format(len(p.items)) c = app.test_client() # request default r = c.get('/') self.assertEqual(r.status_code, 200) # request args r = c.get('/?per_page=10') self.assertEqual(r.data.decode('utf8'), '10 items retrieved') with app.app_context(): # query default p = Todo.query.paginate() self.assertEqual(p.total, 100) class BindsTestCase(unittest.TestCase): def test_basic_binds(self): import tempfile _, db1 = tempfile.mkstemp() _, db2 = tempfile.mkstemp() def _remove_files(): import os try: os.remove(db1) os.remove(db2) except IOError: pass atexit.register(_remove_files) app = flask.Flask(__name__) app.config['SQLALCHEMY_ENGINE'] = 'sqlite://' app.config['SQLALCHEMY_BINDS'] = { 'foo': 'sqlite:///' + db1, 'bar': 'sqlite:///' + db2 } db = sqlalchemy.SQLAlchemy(app) class Foo(db.Model): __bind_key__ = 'foo' __table_args__ = {"info": {"bind_key": "foo"}} id = db.Column(db.Integer, primary_key=True) class Bar(db.Model): __bind_key__ = 'bar' id = db.Column(db.Integer, primary_key=True) class Baz(db.Model): id = db.Column(db.Integer, primary_key=True) db.create_all() # simple way to check if the engines are looked up properly self.assertEqual(db.get_engine(app, None), db.engine) for key in 'foo', 'bar': engine = db.get_engine(app, key) connector = app.extensions['sqlalchemy'].connectors[key] self.assertEqual(engine, connector.get_engine()) self.assertEqual(str(engine.url), app.config['SQLALCHEMY_BINDS'][key]) # do the models have the correct engines? self.assertEqual(db.metadata.tables['foo'].info['bind_key'], 'foo') self.assertEqual(db.metadata.tables['bar'].info['bind_key'], 'bar') self.assertEqual(db.metadata.tables['baz'].info.get('bind_key'), None) # see the tables created in an engine metadata = db.MetaData() metadata.reflect(bind=db.get_engine(app, 'foo')) self.assertEqual(len(metadata.tables), 1) self.assertTrue('foo' in metadata.tables) metadata = db.MetaData() metadata.reflect(bind=db.get_engine(app, 'bar')) self.assertEqual(len(metadata.tables), 1) self.assertTrue('bar' in metadata.tables) metadata = db.MetaData() metadata.reflect(bind=db.get_engine(app)) self.assertEqual(len(metadata.tables), 1) self.assertTrue('baz' in metadata.tables) # do the session have the right binds set? self.assertEqual(db.get_binds(app), { Foo.__table__: db.get_engine(app, 'foo'), Bar.__table__: db.get_engine(app, 'bar'), Baz.__table__: db.get_engine(app, None) }) class DefaultQueryClassTestCase(unittest.TestCase): def test_default_query_class(self): app = flask.Flask(__name__) app.config['SQLALCHEMY_ENGINE'] = 'sqlite://' app.config['TESTING'] = True db = sqlalchemy.SQLAlchemy(app) class Parent(db.Model): id = db.Column(db.Integer, primary_key=True) children = db.relationship("Child", backref = "parents", lazy='dynamic') class Child(db.Model): id = db.Column(db.Integer, primary_key=True) parent_id = db.Column(db.Integer, db.ForeignKey('parent.id')) p = Parent() c = Child() c.parent = p self.assertEqual(type(Parent.query), sqlalchemy.BaseQuery) self.assertEqual(type(Child.query), sqlalchemy.BaseQuery) self.assertTrue(isinstance(p.children, sqlalchemy.BaseQuery)) #self.assertTrue(isinstance(c.parents, sqlalchemy.BaseQuery)) class SQLAlchemyIncludesTestCase(unittest.TestCase): def test(self): """Various SQLAlchemy objects are exposed as attributes. """ db = sqlalchemy.SQLAlchemy() import sqlalchemy as sqlalchemy_lib self.assertTrue(db.Column == sqlalchemy_lib.Column) # The Query object we expose is actually our own subclass. from flask_sqlalchemy import BaseQuery self.assertTrue(db.Query == BaseQuery) class RegressionTestCase(unittest.TestCase): def test_joined_inheritance(self): app = flask.Flask(__name__) db = sqlalchemy.SQLAlchemy(app) class Base(db.Model): id = db.Column(db.Integer, primary_key=True) type = db.Column(db.Unicode(20)) __mapper_args__ = {'polymorphic_on': type} class SubBase(Base): id = db.Column(db.Integer, db.ForeignKey('base.id'), primary_key=True) __mapper_args__ = {'polymorphic_identity': 'sub'} self.assertEqual(Base.__tablename__, 'base') self.assertEqual(SubBase.__tablename__, 'sub_base') db.create_all() def test_single_table_inheritance(self): app = flask.Flask(__name__) db = sqlalchemy.SQLAlchemy(app) class Base(db.Model): id = db.Column(db.Integer, primary_key=True) type = db.Column(db.Unicode(20)) __mapper_args__ = {'polymorphic_on': type} class SubBase(Base): __mapper_args__ = {'polymorphic_identity': 'sub'} self.assertEqual(Base.__tablename__, 'base') self.assertEqual(SubBase.__tablename__, 'base') db.create_all() def test_joined_inheritance_relation(self): app = flask.Flask(__name__) db = sqlalchemy.SQLAlchemy(app) class Relation(db.Model): id = db.Column(db.Integer, primary_key=True) base_id = db.Column(db.Integer, db.ForeignKey('base.id')) name = db.Column(db.Unicode(20)) def __init__(self, name): self.name = name class Base(db.Model): id = db.Column(db.Integer, primary_key=True) type = db.Column(db.Unicode(20)) __mapper_args__ = {'polymorphic_on': type} class SubBase(Base): id = db.Column(db.Integer, db.ForeignKey('base.id'), primary_key=True) __mapper_args__ = {'polymorphic_identity': u'sub'} relations = db.relationship(Relation) db.create_all() base = SubBase() base.relations = [Relation(name=u'foo')] db.session.add(base) db.session.commit() base = base.query.one() def test_connection_binds(self): app = flask.Flask(__name__) db = sqlalchemy.SQLAlchemy(app) assert db.session.connection() class SessionScopingTestCase(unittest.TestCase): def test_default_session_scoping(self): app = flask.Flask(__name__) app.config['SQLALCHEMY_ENGINE'] = 'sqlite://' app.config['TESTING'] = True db = sqlalchemy.SQLAlchemy(app) class FOOBar(db.Model): id = db.Column(db.Integer, primary_key=True) db.create_all() with app.test_request_context(): fb = FOOBar() db.session.add(fb) assert fb in db.session def test_session_scoping_changing(self): app = flask.Flask(__name__) app.config['SQLALCHEMY_ENGINE'] = 'sqlite://' app.config['TESTING'] = True def scopefunc(): return id(dict()) db = sqlalchemy.SQLAlchemy(app, session_options=dict(scopefunc=scopefunc)) class FOOBar(db.Model): id = db.Column(db.Integer, primary_key=True) db.create_all() with app.test_request_context(): fb = FOOBar() db.session.add(fb) assert fb not in db.session # because a new scope is generated on each call class CommitOnTeardownTestCase(unittest.TestCase): def setUp(self): app = flask.Flask(__name__) app.config['SQLALCHEMY_ENGINE'] = 'sqlite://' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True db = sqlalchemy.SQLAlchemy(app) Todo = make_todo_model(db) db.create_all() @app.route('/') def index(): return '\n'.join(x.title for x in Todo.query.all()) @app.route('/create', methods=['POST']) def create(): db.session.add(Todo('Test one', 'test')) if flask.request.form.get('fail'): raise RuntimeError("Failing as requested") return 'ok' self.client = app.test_client() def test_commit_on_success(self): resp = self.client.post('/create') self.assertEqual(resp.status_code, 200) self.assertEqual(self.client.get('/').data, b'Test one') def test_roll_back_on_failure(self): resp = self.client.post('/create', data={'fail': 'on'}) self.assertEqual(resp.status_code, 500) self.assertEqual(self.client.get('/').data, b'') class StandardSessionTestCase(unittest.TestCase): def test_insert_update_delete(self): # Ensure _SignalTrackingMapperExtension doesn't croak when # faced with a vanilla SQLAlchemy session. # # Verifies that "AttributeError: 'SessionMaker' object has no attribute '_model_changes'" # is not thrown. app = flask.Flask(__name__) app.config['SQLALCHEMY_ENGINE'] = 'sqlite://' app.config['TESTING'] = True db = sqlalchemy.SQLAlchemy(app) Session = sessionmaker(bind=db.engine) class QazWsx(db.Model): id = db.Column(db.Integer, primary_key=True) x = db.Column(db.String, default='') db.create_all() session = Session() session.add(QazWsx()) session.flush() # issues an INSERT. session.expunge_all() qaz_wsx = session.query(QazWsx).first() assert qaz_wsx.x == '' qaz_wsx.x = 'test' session.flush() # issues an UPDATE. session.expunge_all() qaz_wsx = session.query(QazWsx).first() assert qaz_wsx.x == 'test' session.delete(qaz_wsx) # issues a DELETE. assert session.query(QazWsx).first() is None def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(BasicAppTestCase)) suite.addTest(unittest.makeSuite(CustomMetaDataTestCase)) suite.addTest(unittest.makeSuite(TestQueryProperty)) suite.addTest(unittest.makeSuite(TablenameTestCase)) suite.addTest(unittest.makeSuite(PaginationTestCase)) suite.addTest(unittest.makeSuite(BindsTestCase)) suite.addTest(unittest.makeSuite(DefaultQueryClassTestCase)) suite.addTest(unittest.makeSuite(SQLAlchemyIncludesTestCase)) suite.addTest(unittest.makeSuite(RegressionTestCase)) suite.addTest(unittest.makeSuite(SessionScopingTestCase)) suite.addTest(unittest.makeSuite(CommitOnTeardownTestCase)) if flask.signals_available: suite.addTest(unittest.makeSuite(SignallingTestCase)) suite.addTest(unittest.makeSuite(StandardSessionTestCase)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite')