├── .gitignore ├── .travis.yml ├── CHANGELOG.rst ├── LICENSE ├── README.md ├── docs ├── Makefile ├── conf.py ├── index.rst └── requirements.txt ├── flask_sqlalchemy_session └── __init__.py ├── setup.py ├── tests └── test_flask_sqlalchemy_session.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | venv 3 | *.egg* 4 | dist 5 | docs/_build 6 | *.pyc 7 | __pycache__ 8 | .tox 9 | .vagrant 10 | .coverage 11 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | jobs: 3 | include: 4 | - os: linux 5 | python: 3.6 6 | env: TOXENV=py36 7 | - os: linux 8 | python: 3.7 9 | env: TOXENV=py37 10 | - os: linux 11 | python: 3.8 12 | env: TOXENV=py38 13 | - os: linux 14 | python: 2.7 15 | env: TOXENV=py27 16 | 17 | install: 18 | - pip install tox 19 | script: tox 20 | branches: 21 | only: 22 | - master 23 | notifications: 24 | email: false -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========= 3 | 4 | Version 1.1 5 | ----------- 6 | 7 | Released on 2015-05-31. 8 | 9 | - Add support for Python 2.6-3.4, pypy, and SQL Alchemy 0.9-1.0. 10 | 11 | Version 1.0 12 | ----------- 13 | 14 | Released on 2015-02-16. 15 | 16 | - First release. 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Flask-SQLAlchemySession 2 | 3 | [![Build Status](https://travis-ci.org/dtheodor/flask-sqlalchemy-session.svg?branch=master)](https://travis-ci.org/dtheodor/flask-sqlalchemy-session) 4 | [![Coverage Status](https://coveralls.io/repos/dtheodor/flask-sqlalchemy-session/badge.svg)](https://coveralls.io/r/dtheodor/flask-sqlalchemy-session) 5 | 6 | Provides an SQLAlchemy scoped session that creates 7 | unique sessions per Flask request, following the guidelines documented at 8 | [Using Custom Created Scopes](http://docs.sqlalchemy.org/en/rel_0_9/orm/contextual.html#using-custom-created-scopes). 9 | 10 | http://flask-sqlalchemy-session.readthedocs.org 11 | 12 | ### Usage 13 | 14 | Initialize a `flask_scoped_session` as you would a 15 | `scoped_session`, with the addition of a Flask 16 | app. Then use the resulting session to query models: 17 | 18 | ```python 19 | from flask import Flask, abort, jsonify 20 | from flask_sqlalchemy_session import flask_scoped_session 21 | 22 | app = Flask(__name__) 23 | session = flask_scoped_session(session_factory, app) 24 | 25 | @app.route("/users/") 26 | def user(user_id): 27 | user = session.query(User).get(user_id) 28 | if user is None: 29 | abort(404) 30 | return flask.jsonify(**user.to_dict()) 31 | ``` 32 | 33 | The `current_session` is also provided as a convenient accessor to the session 34 | of the current request, in the same spirit of `flask.request` and 35 | `flask.current_app`. 36 | 37 | ```python 38 | from flask_sqlalchemy_session import current_session 39 | 40 | @app.route("/users/") 41 | def user(user_id): 42 | user = current_session.query(User).get(user_id) 43 | if user is None: 44 | abort(404) 45 | return flask.jsonify(**user.to_dict()) 46 | ``` 47 | 48 | 49 | ### Tests 50 | 51 | You can run the tests by invoking `PYTHONPATH=. py.test tests/` in the repository root. 52 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Flask-SQLAlchemySession.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Flask-SQLAlchemySession.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/Flask-SQLAlchemySession" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Flask-SQLAlchemySession" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Flask-SQLAlchemySession documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Feb 10 21:47:00 2015. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | 18 | import alabaster 19 | 20 | # If extensions (or modules to document with autodoc) are in another directory, 21 | # add these directories to sys.path here. If the directory is relative to the 22 | # documentation root, use os.path.abspath to make it absolute, like shown here. 23 | # sys.path.insert(0, os.path.abspath('..')) 24 | sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 25 | 26 | # -- General configuration ------------------------------------------------ 27 | 28 | # If your documentation needs a minimal Sphinx version, state it here. 29 | #needs_sphinx = '1.0' 30 | 31 | # Add any Sphinx extension module names here, as strings. They can be 32 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 33 | # ones. 34 | extensions = [ 35 | 'sphinx.ext.autodoc', 36 | 'sphinx.ext.intersphinx', 37 | 'sphinx.ext.viewcode', 38 | 'alabaster' 39 | ] 40 | 41 | # Add any paths that contain templates here, relative to this directory. 42 | templates_path = ['_templates'] 43 | 44 | # The suffix of source filenames. 45 | source_suffix = '.rst' 46 | 47 | # The encoding of source files. 48 | #source_encoding = 'utf-8-sig' 49 | 50 | # The master toctree document. 51 | master_doc = 'index' 52 | 53 | # General information about the project. 54 | project = u'Flask-SQLAlchemySession' 55 | copyright = u'2015, Dimitris Theodorou' 56 | 57 | # The version info for the project you're documenting, acts as replacement for 58 | # |version| and |release|, also used in various other places throughout the 59 | # built documents. 60 | # 61 | # The short X.Y version. 62 | version = '1.0' 63 | # The full version, including alpha/beta/rc tags. 64 | release = '1.0' 65 | 66 | # The language for content autogenerated by Sphinx. Refer to documentation 67 | # for a list of supported languages. 68 | #language = None 69 | 70 | # There are two options for replacing |today|: either, you set today to some 71 | # non-false value, then it is used: 72 | #today = '' 73 | # Else, today_fmt is used as the format for a strftime call. 74 | #today_fmt = '%B %d, %Y' 75 | 76 | # List of patterns, relative to source directory, that match files and 77 | # directories to ignore when looking for source files. 78 | exclude_patterns = ['_build'] 79 | 80 | # The reST default role (used for this markup: `text`) to use for all 81 | # documents. 82 | #default_role = None 83 | 84 | # If true, '()' will be appended to :func: etc. cross-reference text. 85 | #add_function_parentheses = True 86 | 87 | # If true, the current module name will be prepended to all description 88 | # unit titles (such as .. function::). 89 | #add_module_names = True 90 | 91 | # If true, sectionauthor and moduleauthor directives will be shown in the 92 | # output. They are ignored by default. 93 | #show_authors = False 94 | 95 | # The name of the Pygments (syntax highlighting) style to use. 96 | pygments_style = 'sphinx' 97 | 98 | # A list of ignored prefixes for module index sorting. 99 | #modindex_common_prefix = [] 100 | 101 | # If true, keep warnings as "system message" paragraphs in the built documents. 102 | #keep_warnings = False 103 | 104 | 105 | # -- Options for HTML output ---------------------------------------------- 106 | 107 | html_theme = 'alabaster' 108 | 109 | # Add any paths that contain custom themes here, relative to this directory. 110 | html_theme_path = [alabaster.get_path()] 111 | 112 | html_sidebars = { 113 | '**': [ 114 | #'about.html', 115 | #'navigation.html', 116 | #'searchbox.html', 117 | #'donate.html', 118 | ] 119 | } 120 | 121 | html_theme_options = { 122 | 'github_user': 'dtheodor', 123 | 'github_repo': 'flask-sqlalchemy-session', 124 | "github_banner": True, 125 | "travis_button": False 126 | } 127 | 128 | # The name for this set of Sphinx documents. If None, it defaults to 129 | # " v documentation". 130 | #html_title = None 131 | 132 | # A shorter title for the navigation bar. Default is the same as html_title. 133 | #html_short_title = None 134 | 135 | # The name of an image file (relative to this directory) to place at the top 136 | # of the sidebar. 137 | #html_logo = None 138 | 139 | # The name of an image file (within the static path) to use as favicon of the 140 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 141 | # pixels large. 142 | #html_favicon = None 143 | 144 | # Add any paths that contain custom static files (such as style sheets) here, 145 | # relative to this directory. They are copied after the builtin static files, 146 | # so a file named "default.css" will overwrite the builtin "default.css". 147 | html_static_path = ['_static'] 148 | 149 | # Add any extra paths that contain custom files (such as robots.txt or 150 | # .htaccess) here, relative to this directory. These files are copied 151 | # directly to the root of the documentation. 152 | #html_extra_path = [] 153 | 154 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 155 | # using the given strftime format. 156 | #html_last_updated_fmt = '%b %d, %Y' 157 | 158 | # If true, SmartyPants will be used to convert quotes and dashes to 159 | # typographically correct entities. 160 | #html_use_smartypants = True 161 | 162 | # Custom sidebar templates, maps document names to template names. 163 | #html_sidebars = {} 164 | 165 | # Additional templates that should be rendered to pages, maps page names to 166 | # template names. 167 | #html_additional_pages = {} 168 | 169 | # If false, no module index is generated. 170 | #html_domain_indices = True 171 | 172 | # If false, no index is generated. 173 | #html_use_index = True 174 | 175 | # If true, the index is split into individual pages for each letter. 176 | #html_split_index = False 177 | 178 | # If true, links to the reST sources are added to the pages. 179 | #html_show_sourcelink = True 180 | 181 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 182 | #html_show_sphinx = True 183 | 184 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 185 | #html_show_copyright = True 186 | 187 | # If true, an OpenSearch description file will be output, and all pages will 188 | # contain a tag referring to it. The value of this option must be the 189 | # base URL from which the finished HTML is served. 190 | #html_use_opensearch = '' 191 | 192 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 193 | #html_file_suffix = None 194 | 195 | # Output file base name for HTML help builder. 196 | htmlhelp_basename = 'Flask-SQLAlchemySessiondoc' 197 | 198 | 199 | # -- Options for LaTeX output --------------------------------------------- 200 | 201 | latex_elements = { 202 | # The paper size ('letterpaper' or 'a4paper'). 203 | #'papersize': 'letterpaper', 204 | 205 | # The font size ('10pt', '11pt' or '12pt'). 206 | #'pointsize': '10pt', 207 | 208 | # Additional stuff for the LaTeX preamble. 209 | #'preamble': '', 210 | } 211 | 212 | # Grouping the document tree into LaTeX files. List of tuples 213 | # (source start file, target name, title, 214 | # author, documentclass [howto, manual, or own class]). 215 | latex_documents = [ 216 | ('index', 'Flask-SQLAlchemySession.tex', u'Flask-SQLAlchemySession Documentation', 217 | u'Dimitris Theodorou', 'manual'), 218 | ] 219 | 220 | # The name of an image file (relative to this directory) to place at the top of 221 | # the title page. 222 | #latex_logo = None 223 | 224 | # For "manual" documents, if this is true, then toplevel headings are parts, 225 | # not chapters. 226 | #latex_use_parts = False 227 | 228 | # If true, show page references after internal links. 229 | #latex_show_pagerefs = False 230 | 231 | # If true, show URL addresses after external links. 232 | #latex_show_urls = False 233 | 234 | # Documents to append as an appendix to all manuals. 235 | #latex_appendices = [] 236 | 237 | # If false, no module index is generated. 238 | #latex_domain_indices = True 239 | 240 | 241 | # -- Options for manual page output --------------------------------------- 242 | 243 | # One entry per manual page. List of tuples 244 | # (source start file, name, description, authors, manual section). 245 | man_pages = [ 246 | ('index', 'flask-sqlalchemysession', u'Flask-SQLAlchemySession Documentation', 247 | [u'Dimitris Theodorou'], 1) 248 | ] 249 | 250 | # If true, show URL addresses after external links. 251 | #man_show_urls = False 252 | 253 | 254 | # -- Options for Texinfo output ------------------------------------------- 255 | 256 | # Grouping the document tree into Texinfo files. List of tuples 257 | # (source start file, target name, title, author, 258 | # dir menu entry, description, category) 259 | texinfo_documents = [ 260 | ('index', 'Flask-SQLAlchemySession', u'Flask-SQLAlchemySession Documentation', 261 | u'Dimitris Theodorou', 'Flask-SQLAlchemySession', 'One line description of project.', 262 | 'Miscellaneous'), 263 | ] 264 | 265 | # Documents to append as an appendix to all manuals. 266 | #texinfo_appendices = [] 267 | 268 | # If false, no module index is generated. 269 | #texinfo_domain_indices = True 270 | 271 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 272 | #texinfo_show_urls = 'footnote' 273 | 274 | # If true, do not generate a @detailmenu in the "Top" node's menu. 275 | #texinfo_no_detailmenu = False 276 | 277 | intersphinx_mapping = {'flask': ('http://flask.pocoo.org/docs/0.10/', None), 278 | "sqlalchemy": ("http://docs.sqlalchemy.org/en/rel_0_9/", None)} -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | ======================= 2 | Flask-SQLAlchemy-Session 3 | ======================= 4 | .. toctree:: 5 | :maxdepth: 2 6 | .. currentmodule:: flask_sqlalchemy_session 7 | 8 | Flask-SQLALchemy-Session is a tiny library providing an SQLAlchemy scoped 9 | session that creates 10 | unique sessions per Flask request, following the guidelines documented at 11 | `Using Custom Created Scopes `_. 12 | 13 | .. contents:: 14 | :local: 15 | :backlinks: none 16 | 17 | Basic usage 18 | ----------- 19 | 20 | Initialize a :class:`flask_scoped_session` as you would a 21 | :class:`~sqlalchemy.orm.scoping.scoped_session`, with the addition of a Flask 22 | app. Then use the resulting session to query models:: 23 | 24 | from flask import Flask, abort, jsonify 25 | from flask_sqlalchemy_session import flask_scoped_session 26 | 27 | app = Flask(__name__) 28 | session = flask_scoped_session(session_factory, app) 29 | 30 | @app.route("/users/") 31 | def user(user_id): 32 | user = session.query(User).get(user_id) 33 | if user is None: 34 | abort(404) 35 | return flask.jsonify(**user.to_dict()) 36 | 37 | 38 | 39 | The :data:`current_session` is also provided as a convenient accessor to the session 40 | of the current request, in the same spirit of :class:`~flask.request` and 41 | :data:`~flask.current_app`. 42 | 43 | 44 | Implementation 45 | -------------- 46 | The :class:`flask_scoped_session` is a simple wrapper over the original 47 | :class:`~sqlalchemy.orm.scoping.scoped_session` that sets the scope to the Flask 48 | application context, using the right ``scopefunc`` parameter. The application 49 | context is rougly equivalent to a Flask request (more 50 | `here `_). The session is 51 | destroyed on application context teardown. 52 | 53 | 54 | Full Example 55 | ------------ 56 | 57 | This is a complete example with SQL Alchemy model and engine initialization, 58 | followed by Flask app creation and querying of models within a Flask request. 59 | 60 | Declare your models:: 61 | 62 | from sqlalchemy import Column, Integer, String 63 | from sqlalchemy.ext.declarative import declarative_base 64 | 65 | Base = declarative_base() 66 | 67 | class User(Base): 68 | id = Column(Integer, primary_key=True) 69 | name = Column(String) 70 | 71 | def to_dict(self): 72 | return {"id": self.id, 73 | "name": self.name} 74 | 75 | Initialize the database engine and session:: 76 | 77 | from sqlalchemy import create_engine 78 | from sqlalchemy.orm import sessionmaker 79 | 80 | engine = create_engine("sqlite://") 81 | session_factory = sessionmaker(bind=engine) 82 | 83 | Instantiate a Flask application and query a model within a request:: 84 | 85 | from flask import Flask, abort, jsonify 86 | from flask_sqlalchemy_session import flask_scoped_session 87 | 88 | app = Flask(__name__) 89 | session = flask_scoped_session(session_factory, app) 90 | 91 | @app.route("/users/") 92 | def user(user_id): 93 | user = session.query(User).get(user_id) 94 | if user is None: 95 | abort(404) 96 | return flask.jsonify(**user.to_dict()) 97 | 98 | Or use the equivalent :data:`current_session`:: 99 | 100 | from flask_sqlalchemy_session import current_session 101 | 102 | @app.route("/users/") 103 | def user(user_id): 104 | user = current_session.query(User).get(user_id) 105 | if user is None: 106 | abort(404) 107 | return flask.jsonify(**user.to_dict()) 108 | 109 | 110 | 111 | Comparison with Flask-SQLAlchemy 112 | -------------------------------- 113 | 114 | The `Flask-SQLAlchemy `_ project 115 | also provides a request-scoped session, along with much more. It comes an API 116 | that acts as a facade over various SQL Alchemy APIs (engines, 117 | models, metadata). This API buries the 118 | engine/session initialization behind the Flask app initialization, detracts 119 | from the original by removing decisions, and tightly couples the data layer with 120 | the Flask app. On the good side, it is an API easier to start with than SQL 121 | Alchemy itself. 122 | 123 | Flask-SQLAlchemySession is not 124 | intrusive to the original SQL Alchemy APIs in any way, and 125 | does not force you to couple your data layer with your web application. It's 126 | sole purpose is to enable request-scoped sessions on top of 127 | your SQL Alchemy constructs. 128 | 129 | 130 | API 131 | --- 132 | 133 | .. automodule:: flask_sqlalchemy_session 134 | 135 | .. data:: current_session 136 | 137 | Provides the current SQL Alchemy session within a request. 138 | 139 | .. autoclass:: flask_scoped_session 140 | :members: 141 | :special-members: 142 | 143 | 144 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx==1.2.3 2 | alabaster==0.6.3 -------------------------------------------------------------------------------- /flask_sqlalchemy_session/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Flask-SQLAlchemy-Session 4 | ----------------------- 5 | 6 | Provides an SQLAlchemy scoped session that creates 7 | unique sessions per Flask request 8 | """ 9 | # pylint: disable=invalid-name 10 | from werkzeug.local import LocalProxy 11 | from flask import _app_ctx_stack, current_app 12 | from sqlalchemy.orm import scoped_session 13 | 14 | __all__ = ["current_session", "flask_scoped_session"] 15 | __version__ = 1.1 16 | 17 | 18 | def _get_session(): 19 | # pylint: disable=missing-docstring, protected-access 20 | context = _app_ctx_stack.top 21 | if context is None: 22 | raise RuntimeError( 23 | "Cannot access current_session when outside of an application " 24 | "context.") 25 | app = current_app._get_current_object() 26 | if not hasattr(app, "scoped_session"): 27 | raise AttributeError( 28 | "{0} has no 'scoped_session' attribute. You need to initialize it " 29 | "with a flask_scoped_session.".format(app)) 30 | return app.scoped_session 31 | 32 | 33 | current_session = LocalProxy(_get_session) 34 | """Provides the current SQL Alchemy session within a request. 35 | 36 | Will raise an exception if no :data:`~flask.current_app` is available or it has 37 | not been initialized with a :class:`flask_scoped_session` 38 | """ 39 | 40 | 41 | class flask_scoped_session(scoped_session): 42 | """A :class:`~sqlalchemy.orm.scoping.scoped_session` whose scope is set to 43 | the Flask application context. 44 | """ 45 | def __init__(self, session_factory, app=None): 46 | """ 47 | :param session_factory: A callable that returns a 48 | :class:`~sqlalchemy.orm.session.Session` 49 | :param app: a :class:`~flask.Flask` application 50 | """ 51 | super(flask_scoped_session, self).__init__( 52 | session_factory, 53 | scopefunc=_app_ctx_stack.__ident_func__) 54 | # the _app_ctx_stack.__ident_func__ is the greenlet.get_current, or 55 | # thread.get_ident if no greenlets are used. 56 | # each Flask request is launched in a seperate greenlet/thread, so our 57 | # session is unique per request 58 | # _app_ctx_stack looks like internal API but is the only way to get to 59 | # the active application context without adding logic to figure out 60 | # whether threads, greenlets, or something else is used to create new 61 | # application contexts. Keep in mind to refactor if Flask changes its 62 | # public/private API towards this. 63 | if app is not None: 64 | self.init_app(app) 65 | 66 | def init_app(self, app): 67 | """Setup scoped session creation and teardown for the passed ``app``. 68 | 69 | :param app: a :class:`~flask.Flask` application 70 | """ 71 | app.scoped_session = self 72 | 73 | @app.teardown_appcontext 74 | def remove_scoped_session(*args, **kwargs): 75 | # pylint: disable=missing-docstring,unused-argument,unused-variable 76 | app.scoped_session.remove() 77 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Flask-SQLAlchemy-Session 4 | ----------------------- 5 | 6 | Provides an SQLAlchemy scoped session that creates 7 | unique sessions per Flask request 8 | """ 9 | import sys 10 | import os 11 | from setuptools import setup 12 | 13 | if sys.version_info < (2, 6): 14 | raise Exception("Flask-SQLAlchemy-Session requires Python 2.6 or higher.") 15 | 16 | # Hard linking doesn't work inside VirtualBox shared folders. This means that 17 | # you can't use tox in a directory that is being shared with Vagrant, 18 | # since tox relies on `python setup.py sdist` which uses hard links. As a 19 | # workaround, disable hard-linking if setup.py is a descendant of /vagrant. 20 | # See 21 | # https://stackoverflow.com/questions/7719380/python-setup-py-sdist-error-operation-not-permitted 22 | # for more details. 23 | if os.path.abspath(__file__).split(os.path.sep)[1] == 'vagrant': 24 | del os.link 25 | 26 | setup( 27 | name="Flask-SQLAlchemy-Session", 28 | version="1.1", 29 | packages=["flask_sqlalchemy_session"], 30 | author="Dimitris Theodorou", 31 | author_email="dimitris.theodorou@gmail.com", 32 | url='http://github.com/dtheodor/flask-sqlalchemy-session', 33 | license="MIT", 34 | description='SQL Alchemy session scoped on Flask requests.', 35 | long_description=__doc__, 36 | classifiers=[ 37 | 'Development Status :: 5 - Production/Stable', 38 | 'Intended Audience :: Developers', 39 | 'Environment :: Web Environment', 40 | 'License :: OSI Approved :: MIT License', 41 | 'Programming Language :: Python :: 2', 42 | 'Programming Language :: Python :: 3', 43 | 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 44 | 'Topic :: Software Development :: Libraries :: Python Modules' 45 | ], 46 | install_requires=["sqlalchemy>=0.9", "Flask>=0.9", "Werkzeug>=0.6.1"], 47 | tests_require=["pytest>=2.6", "mock>=1.0"], 48 | extras_require={ 49 | 'docs': ["Sphinx>=1.2.3", "alabaster>=0.6.3"] 50 | } 51 | ) 52 | -------------------------------------------------------------------------------- /tests/test_flask_sqlalchemy_session.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import pytest 3 | try: 4 | from unittest import mock 5 | except ImportError: 6 | import mock 7 | from flask import Flask 8 | from sqlalchemy import create_engine 9 | from sqlalchemy.orm import Session, sessionmaker 10 | 11 | from flask_sqlalchemy_session import flask_scoped_session, current_session 12 | 13 | 14 | @pytest.fixture 15 | def sqlite_engine(): 16 | """Return an sqlite engine""" 17 | return create_engine("sqlite://") 18 | 19 | 20 | @pytest.fixture 21 | def flask_app(): 22 | """Return a flask app with debug and testing on""" 23 | app = Flask(__name__) 24 | app.testing = True 25 | app.debug = True 26 | return app 27 | 28 | 29 | @pytest.fixture 30 | def unitialized_session(sqlite_engine): 31 | """Return a request_scoped_session that has not been used for a flask app""" 32 | ses = flask_scoped_session(sessionmaker(bind=sqlite_engine)) 33 | _remove = ses.remove 34 | ses.remove = mock.Mock(side_effect=_remove) 35 | return ses 36 | 37 | 38 | @pytest.fixture 39 | def session(unitialized_session, flask_app): 40 | """Return a request_scoped_session initialized on the flask_app fixture""" 41 | unitialized_session.init_app(flask_app) 42 | return unitialized_session 43 | 44 | 45 | def test_constructor(sqlite_engine, flask_app): 46 | """Test init_app is called when an app is passed in the constructor""" 47 | with mock.patch.object(flask_scoped_session, "init_app"): 48 | ses = flask_scoped_session(sessionmaker(bind=sqlite_engine), flask_app) 49 | ses.init_app.assert_called_once_with(flask_app) 50 | 51 | 52 | def test_current_session_uninitialized_app(flask_app): 53 | """Test accessing current_session without initializing an app""" 54 | with flask_app.test_request_context(): 55 | with pytest.raises(AttributeError): 56 | current_session() 57 | 58 | 59 | class TestRequestScopedSession(object): 60 | """Test handling of the session in a flask request""" 61 | 62 | def test_session_same_request(self, flask_app, session): 63 | with flask_app.test_request_context(): 64 | assert session.query 65 | assert isinstance(session(), Session) 66 | assert session() is session() 67 | 68 | assert session.remove.call_count == 1 69 | 70 | def test_session_different_request(self, flask_app, session): 71 | with flask_app.test_request_context(): 72 | prev_id = id(session()) 73 | 74 | with flask_app.test_request_context(): 75 | assert prev_id != id(session()) 76 | 77 | assert session.remove.call_count == 2 78 | 79 | 80 | @pytest.mark.usefixtures("session") 81 | class TestCurrentSession(object): 82 | """Test current_session""" 83 | 84 | def test_session_same_request(self, flask_app): 85 | with flask_app.test_request_context(): 86 | assert current_session.query 87 | assert isinstance(current_session._get_current_object()(), Session) 88 | assert current_session._get_current_object()() is \ 89 | current_session._get_current_object()() 90 | 91 | def test_session_different_request(self, flask_app): 92 | with flask_app.test_request_context(): 93 | prev_id = id(current_session._get_current_object()()) 94 | 95 | with flask_app.test_request_context(): 96 | assert prev_id != id(current_session._get_current_object()()) 97 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | # Tox (http://tox.testrun.org/) is a tool for running tests 2 | # in multiple virtualenvs. This configuration file will run the 3 | # test suite on all supported python versions. To use it, "pip install tox" 4 | # and then run "tox" from this directory. 5 | 6 | [tox] 7 | envlist = py27, py35, py36, py37 8 | 9 | [testenv] 10 | # VIRTUALENV_ALWAYS_COPY: need this for venv creation in virtualbox shared 11 | # folders, which do not allow symlinks that virtualenv will use by default 12 | # PYTHONPATH: pytest will not include the main module in the sys.path without it 13 | # and tests will fail with import errors 14 | setenv = 15 | VIRTUALENV_ALWAYS_COPY = 1 16 | PYTHONPATH = {toxinidir}/. 17 | commands = py.test tests/ 18 | deps = 19 | pytest==4.0 20 | py27: mock==1.0 21 | sqla9: SQLAlchemy>=0.9,<1.0 22 | 23 | [testenv:lint] 24 | commands = 25 | pep8 flask_sqlalchemy_session/ 26 | pylint flask_sqlalchemy_session/ -r n 27 | deps = 28 | pep8==1.6.2 29 | pylint==1.4.3 30 | 31 | [testenv:coverage] 32 | passenv = TRAVIS TRAVIS_JOB_ID TRAVIS_BRANCH 33 | commands = 34 | py.test tests/ --cov flask_sqlalchemy_session 35 | coveralls 36 | deps = 37 | pytest==5.4 38 | pytest-cov==2.10 39 | mock==1.0 40 | coveralls --------------------------------------------------------------------------------