From 1e278de4cc9a4181e0747640a960e80efcea1ca9 Mon Sep 17 00:00:00 2001 From: Mike Bayer Date: Sun, 6 Jan 2019 01:19:47 -0500 Subject: Post black reformatting Applied on top of a pure run of black -l 79 in I7eda77fed3d8e73df84b3651fd6cfcfe858d4dc9, this set of changes resolves all remaining flake8 conditions for those codes we have enabled in setup.cfg. Included are resolutions for all remaining flake8 issues including shadowed builtins, long lines, import order, unused imports, duplicate imports, and docstring issues. Change-Id: I4f72d3ba1380dd601610ff80b8fb06a2aff8b0fe --- examples/adjacency_list/adjacency_list.py | 11 ++- examples/association/basic_association.py | 22 +++--- examples/association/dict_of_sets_with_default.py | 16 +++-- examples/association/proxied_association.py | 22 +++--- examples/custom_attributes/custom_management.py | 32 ++++----- examples/dogpile_caching/__init__.py | 13 ++-- examples/dogpile_caching/advanced.py | 9 ++- examples/dogpile_caching/caching_query.py | 23 +++--- examples/dogpile_caching/environment.py | 18 +++-- examples/dogpile_caching/fixture_data.py | 16 +++-- examples/dogpile_caching/helloworld.py | 3 +- examples/dogpile_caching/local_session_caching.py | 3 +- examples/dogpile_caching/model.py | 8 ++- examples/dogpile_caching/relationship_caching.py | 10 ++- examples/dynamic_dict/dynamic_dict.py | 14 ++-- examples/elementtree/adjacency_list.py | 83 +++++++++++++--------- examples/elementtree/optimized_al.py | 83 +++++++++++++--------- examples/elementtree/pickle.py | 42 ++++++----- examples/generic_associations/__init__.py | 2 +- .../discriminator_on_association.py | 13 +++- examples/generic_associations/generic_fk.py | 15 +++- .../generic_associations/table_per_association.py | 20 +++--- examples/generic_associations/table_per_related.py | 12 +++- examples/graphs/directed_graph.py | 9 ++- examples/inheritance/concrete.py | 22 +++--- examples/inheritance/joined.py | 21 +++--- examples/inheritance/single.py | 24 ++++--- examples/join_conditions/cast.py | 11 ++- examples/join_conditions/threeway.py | 13 +++- examples/large_collection/large_collection.py | 27 +++---- examples/materialized_paths/materialized_paths.py | 15 +++- examples/nested_sets/nested_sets.py | 22 +++--- examples/performance/__init__.py | 10 +-- examples/performance/__main__.py | 1 + examples/performance/bulk_inserts.py | 10 ++- examples/performance/bulk_updates.py | 9 ++- examples/performance/large_resultsets.py | 14 ++-- examples/performance/short_selects.py | 24 +++---- examples/performance/single_inserts.py | 11 ++- examples/postgis/__init__.py | 3 +- examples/postgis/postgis.py | 26 ++++--- examples/sharding/__init__.py | 2 +- examples/sharding/attribute_shard.py | 31 ++++---- examples/space_invaders/space_invaders.py | 29 +++++--- examples/versioned_history/__init__.py | 4 +- examples/versioned_history/history_meta.py | 24 ++++--- examples/versioned_history/test_versioning.py | 42 +++++------ examples/versioned_rows/versioned_map.py | 26 +++---- examples/versioned_rows/versioned_rows.py | 20 +++--- .../versioned_rows/versioned_rows_w_versionid.py | 34 ++++----- .../versioned_rows/versioned_update_old_row.py | 38 +++++----- examples/vertical/dictlike-polymorphic.py | 4 +- 52 files changed, 593 insertions(+), 423 deletions(-) (limited to 'examples') diff --git a/examples/adjacency_list/adjacency_list.py b/examples/adjacency_list/adjacency_list.py index f1628a632..8cdd88540 100644 --- a/examples/adjacency_list/adjacency_list.py +++ b/examples/adjacency_list/adjacency_list.py @@ -1,6 +1,13 @@ -from sqlalchemy import Column, ForeignKey, Integer, String, create_engine -from sqlalchemy.orm import Session, relationship, backref, joinedload_all +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import backref +from sqlalchemy.orm import joinedload_all +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session from sqlalchemy.orm.collections import attribute_mapped_collection diff --git a/examples/association/basic_association.py b/examples/association/basic_association.py index 52476f184..d2271ad43 100644 --- a/examples/association/basic_association.py +++ b/examples/association/basic_association.py @@ -12,18 +12,18 @@ of "items", with a particular price paid associated with each "item". from datetime import datetime -from sqlalchemy import ( - create_engine, - Column, - Integer, - String, - DateTime, - Float, - ForeignKey, - and_, -) -from sqlalchemy.orm import relationship, Session +from sqlalchemy import and_ +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import DateTime +from sqlalchemy import Float +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session + Base = declarative_base() diff --git a/examples/association/dict_of_sets_with_default.py b/examples/association/dict_of_sets_with_default.py index 7f668c087..435761d3f 100644 --- a/examples/association/dict_of_sets_with_default.py +++ b/examples/association/dict_of_sets_with_default.py @@ -12,13 +12,19 @@ upon access of a non-existent key, in the same manner as Python's """ -from sqlalchemy import String, Integer, Column, create_engine, ForeignKey -from sqlalchemy.orm import relationship, Session -from sqlalchemy.orm.collections import MappedCollection -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.ext.associationproxy import association_proxy import operator +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import String +from sqlalchemy.ext.associationproxy import association_proxy +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session +from sqlalchemy.orm.collections import MappedCollection + class Base(object): id = Column(Integer, primary_key=True) diff --git a/examples/association/proxied_association.py b/examples/association/proxied_association.py index 46785c6e2..0ec8fa899 100644 --- a/examples/association/proxied_association.py +++ b/examples/association/proxied_association.py @@ -7,18 +7,18 @@ to ``OrderItem`` optional. from datetime import datetime -from sqlalchemy import ( - create_engine, - Column, - Integer, - String, - DateTime, - Float, - ForeignKey, -) -from sqlalchemy.orm import relationship, Session -from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import DateTime +from sqlalchemy import Float +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import String from sqlalchemy.ext.associationproxy import association_proxy +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session + Base = declarative_base() diff --git a/examples/custom_attributes/custom_management.py b/examples/custom_attributes/custom_management.py index 812385906..6cddfe7bd 100644 --- a/examples/custom_attributes/custom_management.py +++ b/examples/custom_attributes/custom_management.py @@ -9,25 +9,21 @@ descriptors with a user-defined system. """ -from sqlalchemy import ( - create_engine, - MetaData, - Table, - Column, - Integer, - Text, - ForeignKey, -) -from sqlalchemy.orm import mapper, relationship, Session - -from sqlalchemy.orm.attributes import ( - set_attribute, - get_attribute, - del_attribute, -) -from sqlalchemy.orm.instrumentation import is_instrumented - +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import MetaData +from sqlalchemy import Table +from sqlalchemy import Text from sqlalchemy.ext.instrumentation import InstrumentationManager +from sqlalchemy.orm import mapper +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session +from sqlalchemy.orm.attributes import del_attribute +from sqlalchemy.orm.attributes import get_attribute +from sqlalchemy.orm.attributes import set_attribute +from sqlalchemy.orm.instrumentation import is_instrumented class MyClassState(InstrumentationManager): diff --git a/examples/dogpile_caching/__init__.py b/examples/dogpile_caching/__init__.py index 0f19854e9..91105dc02 100644 --- a/examples/dogpile_caching/__init__.py +++ b/examples/dogpile_caching/__init__.py @@ -1,13 +1,8 @@ """ -Illustrates how to embed `dogpile.cache `_ -functionality within -the :class:`.Query` object, allowing full cache control as well as the -ability to pull "lazy loaded" attributes from long term cache -as well. - -.. versionchanged:: 0.8 The example was modernized to use - dogpile.cache, replacing Beaker as the caching library in - use. +Illustrates how to embed +`dogpile.cache `_ +functionality within the :class:`.Query` object, allowing full cache control +as well as the ability to pull "lazy loaded" attributes from long term cache. In this demo, the following techniques are illustrated: diff --git a/examples/dogpile_caching/advanced.py b/examples/dogpile_caching/advanced.py index 8f395bd7b..d2ef82556 100644 --- a/examples/dogpile_caching/advanced.py +++ b/examples/dogpile_caching/advanced.py @@ -3,9 +3,11 @@ including front-end loading, cache invalidation and collection caching. """ +from .caching_query import FromCache +from .caching_query import RelationshipCache from .environment import Session -from .model import Person, cache_address_bits -from .caching_query import FromCache, RelationshipCache +from .model import cache_address_bits +from .model import Person def load_name_range(start, end, invalidate=False): @@ -68,7 +70,8 @@ print(", ".join([p.name for p in load_name_range(25, 40, True)])) # illustrate the address loading from either cache/already # on the Person print( - "\n\nPeople plus addresses, two through twelve, addresses possibly from cache" + "\n\nPeople plus addresses, two through twelve, addresses " + "possibly from cache" ) for p in load_name_range(2, 12): print(p.format_full()) diff --git a/examples/dogpile_caching/caching_query.py b/examples/dogpile_caching/caching_query.py index 060c14613..3d528b880 100644 --- a/examples/dogpile_caching/caching_query.py +++ b/examples/dogpile_caching/caching_query.py @@ -17,9 +17,10 @@ The rest of what's here are standard SQLAlchemy and dogpile.cache constructs. """ +from dogpile.cache.api import NO_VALUE + from sqlalchemy.orm.interfaces import MapperOption from sqlalchemy.orm.query import Query -from dogpile.cache.api import NO_VALUE class CachingQuery(Query): @@ -187,14 +188,14 @@ class FromCache(MapperOption): """Construct a new FromCache. :param region: the cache region. Should be a - region configured in the dictionary of dogpile - regions. + region configured in the dictionary of dogpile + regions. :param cache_key: optional. A string cache key - that will serve as the key to the query. Use this - if your query has a huge amount of parameters (such - as when using in_()) which correspond more simply to - some other identifier. + that will serve as the key to the query. Use this + if your query has a huge amount of parameters (such + as when using in_()) which correspond more simply to + some other identifier. """ self.region = region @@ -215,14 +216,14 @@ class RelationshipCache(MapperOption): """Construct a new RelationshipCache. :param attribute: A Class.attribute which - indicates a particular class relationship() whose - lazy loader should be pulled from the cache. + indicates a particular class relationship() whose + lazy loader should be pulled from the cache. :param region: name of the cache region. :param cache_key: optional. A string cache key - that will serve as the key to the query, bypassing - the usual means of forming a key from the Query itself. + that will serve as the key to the query, bypassing + the usual means of forming a key from the Query itself. """ self.region = region diff --git a/examples/dogpile_caching/environment.py b/examples/dogpile_caching/environment.py index 13bd0a310..723ee653d 100644 --- a/examples/dogpile_caching/environment.py +++ b/examples/dogpile_caching/environment.py @@ -2,19 +2,23 @@ bootstrap fixture data if necessary. """ -from . import caching_query -from sqlalchemy import create_engine -from sqlalchemy.orm import scoped_session, sessionmaker -from sqlalchemy.ext.declarative import declarative_base -from dogpile.cache.region import make_region -import os from hashlib import md5 +import os import sys +from dogpile.cache.region import make_region + +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import scoped_session +from sqlalchemy.orm import sessionmaker +from . import caching_query + + py2k = sys.version_info < (3, 0) if py2k: - input = raw_input + input = raw_input # noqa # dogpile cache regions. A home base for cache configurations. regions = {} diff --git a/examples/dogpile_caching/fixture_data.py b/examples/dogpile_caching/fixture_data.py index e301db2a4..8387a2cb2 100644 --- a/examples/dogpile_caching/fixture_data.py +++ b/examples/dogpile_caching/fixture_data.py @@ -1,12 +1,18 @@ -"""Installs some sample data. Here we have a handful of postal codes for a few US/ -Canadian cities. Then, 100 Person records are installed, each with a -randomly selected postal code. +"""Installs some sample data. Here we have a handful of postal codes for +a few US/Canadian cities. Then, 100 Person records are installed, each +with a randomly selected postal code. """ -from .environment import Session, Base -from .model import City, Country, PostalCode, Person, Address import random +from .environment import Base +from .environment import Session +from .model import Address +from .model import City +from .model import Country +from .model import Person +from .model import PostalCode + def install(): Base.metadata.create_all(Session().bind) diff --git a/examples/dogpile_caching/helloworld.py b/examples/dogpile_caching/helloworld.py index eb565344e..6b03afbdb 100644 --- a/examples/dogpile_caching/helloworld.py +++ b/examples/dogpile_caching/helloworld.py @@ -2,9 +2,10 @@ """ +from .caching_query import FromCache from .environment import Session from .model import Person -from .caching_query import FromCache + # load Person objects. cache the result in the "default" cache region print("loading people....") diff --git a/examples/dogpile_caching/local_session_caching.py b/examples/dogpile_caching/local_session_caching.py index 358886bf0..1700c7a63 100644 --- a/examples/dogpile_caching/local_session_caching.py +++ b/examples/dogpile_caching/local_session_caching.py @@ -10,7 +10,8 @@ with the basic operation of CachingQuery. """ -from dogpile.cache.api import CacheBackend, NO_VALUE +from dogpile.cache.api import CacheBackend +from dogpile.cache.api import NO_VALUE from dogpile.cache.region import register_backend diff --git a/examples/dogpile_caching/model.py b/examples/dogpile_caching/model.py index f6a259820..cae2ae277 100644 --- a/examples/dogpile_caching/model.py +++ b/examples/dogpile_caching/model.py @@ -7,10 +7,14 @@ PostalCode --(has a)--> City City --(has a)--> Country """ -from sqlalchemy import Column, Integer, String, ForeignKey +from sqlalchemy import Column +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import String from sqlalchemy.orm import relationship from .caching_query import RelationshipCache -from .environment import Base, bootstrap +from .environment import Base +from .environment import bootstrap class Country(Base): diff --git a/examples/dogpile_caching/relationship_caching.py b/examples/dogpile_caching/relationship_caching.py index 76c7e767f..6b261ade9 100644 --- a/examples/dogpile_caching/relationship_caching.py +++ b/examples/dogpile_caching/relationship_caching.py @@ -6,11 +6,15 @@ related PostalCode, City, Country objects should be pulled from long term cache. """ -from .environment import Session, root -from .model import Person, cache_address_bits -from sqlalchemy.orm import joinedload import os +from sqlalchemy.orm import joinedload +from .environment import root +from .environment import Session +from .model import cache_address_bits +from .model import Person + + for p in Session.query(Person).options( joinedload(Person.addresses), cache_address_bits ): diff --git a/examples/dynamic_dict/dynamic_dict.py b/examples/dynamic_dict/dynamic_dict.py index 62da55c38..63a23bffb 100644 --- a/examples/dynamic_dict/dynamic_dict.py +++ b/examples/dynamic_dict/dynamic_dict.py @@ -1,3 +1,13 @@ +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import String +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import relationship +from sqlalchemy.orm import sessionmaker + + class ProxyDict(object): def __init__(self, parent, collection_name, childclass, keyname): self.parent = parent @@ -29,10 +39,6 @@ class ProxyDict(object): self.collection.append(value) -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy import create_engine, Column, Integer, String, ForeignKey -from sqlalchemy.orm import sessionmaker, relationship - engine = create_engine("sqlite://", echo=True) Base = declarative_base(engine) diff --git a/examples/elementtree/adjacency_list.py b/examples/elementtree/adjacency_list.py index 1f7161212..6dd88c797 100644 --- a/examples/elementtree/adjacency_list.py +++ b/examples/elementtree/adjacency_list.py @@ -1,4 +1,6 @@ -"""Illustrates an explicit way to persist an XML document expressed using ElementTree. +""" +Illustrates an explicit way to persist an XML document expressed using +ElementTree. Each DOM node is stored in an individual table row, with attributes represented in a separate table. The @@ -8,34 +10,37 @@ along any path with a given structure of attributes, basically a (very narrow) subset of xpath. This example explicitly marshals/unmarshals the ElementTree document into -mapped entities which have their own tables. Compare to pickle.py which -uses pickle to accomplish the same task. Note that the usage of both -styles of persistence are identical, as is the structure of the main Document class. +mapped entities which have their own tables. Compare to pickle.py which uses +pickle to accomplish the same task. Note that the usage of both styles of +persistence are identical, as is the structure of the main Document class. """ -################################# PART I - Imports/Coniguration #################################### -from sqlalchemy import ( - MetaData, - Table, - Column, - Integer, - String, - ForeignKey, - Unicode, - and_, - create_engine, -) -from sqlalchemy.orm import mapper, relationship, Session, lazyload +# PART I - Imports/Configuration +import io +import os +import re +from xml.etree import ElementTree -import sys, os, io, re +from sqlalchemy import and_ +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import MetaData +from sqlalchemy import String +from sqlalchemy import Table +from sqlalchemy import Unicode +from sqlalchemy.orm import lazyload +from sqlalchemy.orm import mapper +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session -from xml.etree import ElementTree e = create_engine("sqlite://") meta = MetaData() -################################# PART II - Table Metadata ######################################### +# PART II - Table Metadata # stores a top level record of an XML document. documents = Table( @@ -75,10 +80,12 @@ attributes = Table( meta.create_all(e) -#################################### PART III - Model ############################################# +# PART III - Model # our document class. contains a string name, # and the ElementTree root element. + + class Document(object): def __init__(self, name, element): self.filename = name @@ -90,19 +97,22 @@ class Document(object): return buf.getvalue() -#################################### PART IV - Persistence Mapping ################################# +# PART IV - Persistence Mapping + +# Node class. a non-public class which will represent the DB-persisted +# Element/SubElement object. We cannot create mappers for ElementTree elements +# directly because they are at the very least not new-style classes, and also +# may be backed by native implementations. so here we construct an adapter. + -# Node class. a non-public class which will represent -# the DB-persisted Element/SubElement object. We cannot create mappers for -# ElementTree elements directly because they are at the very least not new-style -# classes, and also may be backed by native implementations. -# so here we construct an adapter. class _Node(object): pass -# Attribute class. also internal, this will represent the key/value attributes stored for -# a particular Node. +# Attribute class. also internal, this will represent the key/value attributes +# stored for a particular Node. + + class _Attribute(object): def __init__(self, name, value): self.name = name @@ -130,9 +140,12 @@ mapper( mapper(_Attribute, attributes) -# define marshalling functions that convert from _Node/_Attribute to/from ElementTree objects. -# this will set the ElementTree element as "document._element", and append the root _Node -# object to the "_root" mapped collection. +# define marshalling functions that convert from _Node/_Attribute to/from +# ElementTree objects. this will set the ElementTree element as +# "document._element", and append the root _Node object to the "_root" mapped +# collection. + + class ElementTreeMarshal(object): def __get__(self, document, owner): if document is None: @@ -180,7 +193,7 @@ class ElementTreeMarshal(object): # override Document's "element" attribute with the marshaller. Document.element = ElementTreeMarshal() -########################################### PART V - Basic Persistence Example ##################### +# PART V - Basic Persistence Example line = "\n--------------------------------------------------------" @@ -202,7 +215,7 @@ document = session.query(Document).filter_by(filename="test.xml").first() print(document) -############################################ PART VI - Searching for Paths ######################### +# PART VI - Searching for Paths # manually search for a document which contains "/somefile/header/field1:hi" d = ( @@ -218,6 +231,8 @@ d = ( print(d) # generalize the above approach into an extremely impoverished xpath function: + + def find_document(path, compareto): j = documents prev_elements = None diff --git a/examples/elementtree/optimized_al.py b/examples/elementtree/optimized_al.py index 8e9c48b96..b66ada19d 100644 --- a/examples/elementtree/optimized_al.py +++ b/examples/elementtree/optimized_al.py @@ -7,28 +7,32 @@ """ -##################### PART I - Imports/Configuration ######################### -from sqlalchemy import ( - MetaData, - Table, - Column, - Integer, - String, - ForeignKey, - Unicode, - and_, - create_engine, -) -from sqlalchemy.orm import mapper, relationship, Session, lazyload - -import sys, os, io, re +# PART I - Imports/Configuration +import io +import os +import re from xml.etree import ElementTree +from sqlalchemy import and_ +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import MetaData +from sqlalchemy import String +from sqlalchemy import Table +from sqlalchemy import Unicode +from sqlalchemy.orm import lazyload +from sqlalchemy.orm import mapper +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session + + e = create_engine("sqlite://", echo=True) meta = MetaData() -####################### PART II - Table Metadata ############################# +# PART II - Table Metadata # stores a top level record of an XML document. documents = Table( @@ -68,10 +72,12 @@ attributes = Table( meta.create_all(e) -########################### PART III - Model ################################# +# PART III - Model # our document class. contains a string name, # and the ElementTree root element. + + class Document(object): def __init__(self, name, element): self.filename = name @@ -83,19 +89,22 @@ class Document(object): return buf.getvalue() -########################## PART IV - Persistence Mapping ##################### +# PART IV - Persistence Mapping + +# Node class. a non-public class which will represent the DB-persisted +# Element/SubElement object. We cannot create mappers for ElementTree elements +# directly because they are at the very least not new-style classes, and also +# may be backed by native implementations. so here we construct an adapter. + -# Node class. a non-public class which will represent -# the DB-persisted Element/SubElement object. We cannot create mappers for -# ElementTree elements directly because they are at the very least not new-style -# classes, and also may be backed by native implementations. -# so here we construct an adapter. class _Node(object): pass -# Attribute class. also internal, this will represent the key/value attributes stored for -# a particular Node. +# Attribute class. also internal, this will represent the key/value attributes +# stored for a particular Node. + + class _Attribute(object): def __init__(self, name, value): self.name = name @@ -115,10 +124,11 @@ mapper( }, ) -# the _Node objects change the way they load so that a list of _Nodes will organize -# themselves hierarchically using the ElementTreeMarshal. this depends on the ordering of -# nodes being hierarchical as well; relationship() always applies at least ROWID/primary key -# ordering to rows which will suffice. +# the _Node objects change the way they load so that a list of _Nodes will +# organize themselves hierarchically using the ElementTreeMarshal. this +# depends on the ordering of nodes being hierarchical as well; relationship() +# always applies at least ROWID/primary key ordering to rows which will +# suffice. mapper( _Node, elements, @@ -134,9 +144,12 @@ mapper( mapper(_Attribute, attributes) -# define marshalling functions that convert from _Node/_Attribute to/from ElementTree objects. -# this will set the ElementTree element as "document._element", and append the root _Node -# object to the "_nodes" mapped collection. +# define marshalling functions that convert from _Node/_Attribute to/from +# ElementTree objects. this will set the ElementTree element as +# "document._element", and append the root _Node object to the "_nodes" mapped +# collection. + + class ElementTreeMarshal(object): def __get__(self, document, owner): if document is None: @@ -188,7 +201,7 @@ class ElementTreeMarshal(object): # override Document's "element" attribute with the marshaller. Document.element = ElementTreeMarshal() -###################### PART V - Basic Persistence Example #################### +# PART V - Basic Persistence Example line = "\n--------------------------------------------------------" @@ -210,7 +223,7 @@ document = session.query(Document).filter_by(filename="test.xml").first() print(document) -######################## PART VI - Searching for Paths ####################### +# PART VI - Searching for Paths # manually search for a document which contains "/somefile/header/field1:hi" print("\nManual search for /somefile/header/field1=='hi':", line) @@ -227,6 +240,8 @@ d = ( print(d) # generalize the above approach into an extremely impoverished xpath function: + + def find_document(path, compareto): j = documents prev_elements = None diff --git a/examples/elementtree/pickle.py b/examples/elementtree/pickle.py index a86fe30e5..ca2c65504 100644 --- a/examples/elementtree/pickle.py +++ b/examples/elementtree/pickle.py @@ -1,31 +1,37 @@ -"""illustrates a quick and dirty way to persist an XML document expressed using ElementTree and pickle. +""" +illustrates a quick and dirty way to persist an XML document expressed using +ElementTree and pickle. This is a trivial example using PickleType to marshal/unmarshal the ElementTree -document into a binary column. Compare to explicit.py which stores the individual components of the ElementTree -structure in distinct rows using two additional mapped entities. Note that the usage of both -styles of persistence are identical, as is the structure of the main Document class. +document into a binary column. Compare to explicit.py which stores the +individual components of the ElementTree structure in distinct rows using two +additional mapped entities. Note that the usage of both styles of persistence +are identical, as is the structure of the main Document class. + """ -from sqlalchemy import ( - create_engine, - MetaData, - Table, - Column, - Integer, - String, - PickleType, -) -from sqlalchemy.orm import mapper, Session +import os +import sys +from xml.etree import ElementTree -import sys, os +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import Integer +from sqlalchemy import MetaData +from sqlalchemy import PickleType +from sqlalchemy import String +from sqlalchemy import Table +from sqlalchemy.orm import mapper +from sqlalchemy.orm import Session -from xml.etree import ElementTree e = create_engine("sqlite://") meta = MetaData() # setup a comparator for the PickleType since it's a mutable # element. + + def are_elements_equal(x, y): return x == y @@ -44,6 +50,8 @@ meta.create_all(e) # our document class. contains a string name, # and the ElementTree root element. + + class Document(object): def __init__(self, name, element): self.filename = name @@ -53,7 +61,7 @@ class Document(object): # setup mapper. mapper(Document, documents) -###### time to test ! ######### +# time to test ! # get ElementTree document filename = os.path.join(os.path.dirname(__file__), "test.xml") diff --git a/examples/generic_associations/__init__.py b/examples/generic_associations/__init__.py index 9d103b73e..dd6f5321b 100644 --- a/examples/generic_associations/__init__.py +++ b/examples/generic_associations/__init__.py @@ -15,4 +15,4 @@ are modernized versions of recipes presented in the 2007 blog post .. autosource:: -""" +""" # noqa diff --git a/examples/generic_associations/discriminator_on_association.py b/examples/generic_associations/discriminator_on_association.py index 38f2370f3..950208846 100644 --- a/examples/generic_associations/discriminator_on_association.py +++ b/examples/generic_associations/discriminator_on_association.py @@ -15,10 +15,17 @@ it uses a fixed number of tables to serve any number of potential parent objects, but is also slightly more complex. """ -from sqlalchemy.ext.declarative import as_declarative, declared_attr -from sqlalchemy import create_engine, Integer, Column, String, ForeignKey -from sqlalchemy.orm import Session, relationship, backref +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import String from sqlalchemy.ext.associationproxy import association_proxy +from sqlalchemy.ext.declarative import as_declarative +from sqlalchemy.ext.declarative import declared_attr +from sqlalchemy.orm import backref +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session @as_declarative() diff --git a/examples/generic_associations/generic_fk.py b/examples/generic_associations/generic_fk.py index ded8f749d..23145ed4c 100644 --- a/examples/generic_associations/generic_fk.py +++ b/examples/generic_associations/generic_fk.py @@ -19,10 +19,19 @@ or "table_per_association" instead of this approach. .. versionadded:: 0.8.3 """ -from sqlalchemy.ext.declarative import as_declarative, declared_attr -from sqlalchemy import create_engine, Integer, Column, String, and_ -from sqlalchemy.orm import Session, relationship, foreign, remote, backref +from sqlalchemy import and_ +from sqlalchemy import Column +from sqlalchemy import create_engine from sqlalchemy import event +from sqlalchemy import Integer +from sqlalchemy import String +from sqlalchemy.ext.declarative import as_declarative +from sqlalchemy.ext.declarative import declared_attr +from sqlalchemy.orm import backref +from sqlalchemy.orm import foreign +from sqlalchemy.orm import relationship +from sqlalchemy.orm import remote +from sqlalchemy.orm import Session @as_declarative() diff --git a/examples/generic_associations/table_per_association.py b/examples/generic_associations/table_per_association.py index 7de246934..98c76ef7b 100644 --- a/examples/generic_associations/table_per_association.py +++ b/examples/generic_associations/table_per_association.py @@ -11,16 +11,16 @@ has no dependency on the system. """ -from sqlalchemy.ext.declarative import as_declarative, declared_attr -from sqlalchemy import ( - create_engine, - Integer, - Column, - String, - ForeignKey, - Table, -) -from sqlalchemy.orm import Session, relationship +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import String +from sqlalchemy import Table +from sqlalchemy.ext.declarative import as_declarative +from sqlalchemy.ext.declarative import declared_attr +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session @as_declarative() diff --git a/examples/generic_associations/table_per_related.py b/examples/generic_associations/table_per_related.py index 9c5e0e179..3f09e538b 100644 --- a/examples/generic_associations/table_per_related.py +++ b/examples/generic_associations/table_per_related.py @@ -16,9 +16,15 @@ but there really isn't any - the management and targeting of these tables is completely automated. """ -from sqlalchemy.ext.declarative import as_declarative, declared_attr -from sqlalchemy import create_engine, Integer, Column, String, ForeignKey -from sqlalchemy.orm import Session, relationship +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import String +from sqlalchemy.ext.declarative import as_declarative +from sqlalchemy.ext.declarative import declared_attr +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session @as_declarative() diff --git a/examples/graphs/directed_graph.py b/examples/graphs/directed_graph.py index af85a4295..d6611eaa7 100644 --- a/examples/graphs/directed_graph.py +++ b/examples/graphs/directed_graph.py @@ -1,8 +1,13 @@ """a directed graph example.""" -from sqlalchemy import Column, Integer, ForeignKey, create_engine -from sqlalchemy.orm import relationship, sessionmaker +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import Integer from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import relationship +from sqlalchemy.orm import sessionmaker + Base = declarative_base() diff --git a/examples/inheritance/concrete.py b/examples/inheritance/concrete.py index 2245aa4e0..4eb89984a 100644 --- a/examples/inheritance/concrete.py +++ b/examples/inheritance/concrete.py @@ -1,17 +1,17 @@ """Concrete-table (table-per-class) inheritance example.""" -from sqlalchemy import ( - Column, - Integer, - String, - ForeignKey, - create_engine, - inspect, - or_, -) -from sqlalchemy.orm import relationship, Session, with_polymorphic -from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import inspect +from sqlalchemy import Integer +from sqlalchemy import or_ +from sqlalchemy import String from sqlalchemy.ext.declarative import ConcreteBase +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session +from sqlalchemy.orm import with_polymorphic Base = declarative_base() diff --git a/examples/inheritance/joined.py b/examples/inheritance/joined.py index a3a61d763..74a6e3649 100644 --- a/examples/inheritance/joined.py +++ b/examples/inheritance/joined.py @@ -1,16 +1,17 @@ """Joined-table (table-per-subclass) inheritance example.""" -from sqlalchemy import ( - Column, - Integer, - String, - ForeignKey, - create_engine, - inspect, - or_, -) -from sqlalchemy.orm import relationship, Session, with_polymorphic +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import inspect +from sqlalchemy import Integer +from sqlalchemy import or_ +from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session +from sqlalchemy.orm import with_polymorphic + Base = declarative_base() diff --git a/examples/inheritance/single.py b/examples/inheritance/single.py index 46d690c94..0d5871cb1 100644 --- a/examples/inheritance/single.py +++ b/examples/inheritance/single.py @@ -1,16 +1,18 @@ """Single-table (table-per-hierarchy) inheritance example.""" -from sqlalchemy import ( - Column, - Integer, - String, - ForeignKey, - create_engine, - inspect, - or_, -) -from sqlalchemy.orm import relationship, Session, with_polymorphic -from sqlalchemy.ext.declarative import declarative_base, declared_attr +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import inspect +from sqlalchemy import Integer +from sqlalchemy import or_ +from sqlalchemy import String +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.ext.declarative import declared_attr +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session +from sqlalchemy.orm import with_polymorphic + Base = declarative_base() diff --git a/examples/join_conditions/cast.py b/examples/join_conditions/cast.py index 7ea775689..e175bc227 100644 --- a/examples/join_conditions/cast.py +++ b/examples/join_conditions/cast.py @@ -29,9 +29,16 @@ in order to note to the ORM that ``B.a_id`` should be treated like the "foreign key" column. """ -from sqlalchemy import * -from sqlalchemy.orm import * + +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import Integer +from sqlalchemy import String +from sqlalchemy import TypeDecorator from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session + Base = declarative_base() diff --git a/examples/join_conditions/threeway.py b/examples/join_conditions/threeway.py index 257002637..aca3b0c2f 100644 --- a/examples/join_conditions/threeway.py +++ b/examples/join_conditions/threeway.py @@ -33,9 +33,18 @@ a Query (or a :func:`.relationship`). """ -from sqlalchemy import * -from sqlalchemy.orm import * +from sqlalchemy import and_ +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import Integer +from sqlalchemy import join +from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import foreign +from sqlalchemy.orm import mapper +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session + Base = declarative_base() diff --git a/examples/large_collection/large_collection.py b/examples/large_collection/large_collection.py index eb014c6cb..0f34c54dc 100644 --- a/examples/large_collection/large_collection.py +++ b/examples/large_collection/large_collection.py @@ -1,13 +1,13 @@ -from sqlalchemy import ( - MetaData, - Table, - Column, - Integer, - String, - ForeignKey, - create_engine, -) -from sqlalchemy.orm import mapper, relationship, sessionmaker +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import MetaData +from sqlalchemy import String +from sqlalchemy import Table +from sqlalchemy.orm import mapper +from sqlalchemy.orm import relationship +from sqlalchemy.orm import sessionmaker meta = MetaData() @@ -56,8 +56,8 @@ mapper( # Member objects "belong" to their parent, are deleted when # removed from the collection cascade="all, delete-orphan", - # "delete, delete-orphan" cascade does not load in objects on delete, - # allows ON DELETE CASCADE to handle it. + # "delete, delete-orphan" cascade does not load in objects on + # delete, allows ON DELETE CASCADE to handle it. # this only works with a database that supports ON DELETE CASCADE - # *not* sqlite or MySQL with MyISAM passive_deletes=True, @@ -108,7 +108,8 @@ if __name__ == "__main__": # disappear automatically without the need for additional SQL. sess.delete(org) print( - "-------------------------\nflush three - delete org, delete members in one statement\n" + "-------------------------\nflush three - delete org, " + "delete members in one statement\n" ) sess.commit() diff --git a/examples/materialized_paths/materialized_paths.py b/examples/materialized_paths/materialized_paths.py index 45ae0c193..f777f131b 100644 --- a/examples/materialized_paths/materialized_paths.py +++ b/examples/materialized_paths/materialized_paths.py @@ -26,11 +26,20 @@ already stored in the path itself. Updates require going through all descendants and changing the prefix. """ -from sqlalchemy import Column, Integer, String, func, select, create_engine -from sqlalchemy.orm import remote, foreign, relationship, Session +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import func +from sqlalchemy import Integer +from sqlalchemy import select +from sqlalchemy import String +from sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import foreign +from sqlalchemy.orm import relationship +from sqlalchemy.orm import remote +from sqlalchemy.orm import Session from sqlalchemy.sql.expression import cast -from sqlalchemy.dialects.postgresql import ARRAY + Base = declarative_base() diff --git a/examples/nested_sets/nested_sets.py b/examples/nested_sets/nested_sets.py index 705a3d279..ba45231ce 100644 --- a/examples/nested_sets/nested_sets.py +++ b/examples/nested_sets/nested_sets.py @@ -4,18 +4,18 @@ http://www.intelligententerprise.com/001020/celko.jhtml """ -from sqlalchemy import ( - create_engine, - Column, - Integer, - String, - select, - case, - func, -) -from sqlalchemy.orm import Session, aliased -from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy import case +from sqlalchemy import Column +from sqlalchemy import create_engine from sqlalchemy import event +from sqlalchemy import func +from sqlalchemy import Integer +from sqlalchemy import select +from sqlalchemy import String +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import aliased +from sqlalchemy.orm import Session + Base = declarative_base() diff --git a/examples/performance/__init__.py b/examples/performance/__init__.py index b66199f3c..f1f59026c 100644 --- a/examples/performance/__init__.py +++ b/examples/performance/__init__.py @@ -31,8 +31,8 @@ individual suites to be run:: -h, --help show this help message and exit --test TEST run specific test name --dburl DBURL database URL, default sqlite:///profile.db - --num NUM Number of iterations/items/etc for tests; default is 0 - module-specific + --num NUM Number of iterations/items/etc for tests; + default is module-specific --profile run profiling and dump call counts --dump dump full call profile (implies --profile) --runsnake invoke runsnakerun (implies --profile) @@ -217,14 +217,14 @@ As well as see RunSnake output for an individual test:: $ python test_loads.py --num 100 --runsnake --test test_joinedload -""" +""" # noqa import argparse import cProfile -import pstats import os -import time +import pstats import re import sys +import time class Profiler(object): diff --git a/examples/performance/__main__.py b/examples/performance/__main__.py index 945458651..aeb124e1d 100644 --- a/examples/performance/__main__.py +++ b/examples/performance/__main__.py @@ -2,5 +2,6 @@ from . import Profiler + if __name__ == "__main__": Profiler.main() diff --git a/examples/performance/bulk_inserts.py b/examples/performance/bulk_inserts.py index 52f0f32e6..49469581d 100644 --- a/examples/performance/bulk_inserts.py +++ b/examples/performance/bulk_inserts.py @@ -3,11 +3,15 @@ of rows in bulk. """ -from . import Profiler - +from sqlalchemy import bindparam +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import Integer +from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy import Column, Integer, String, create_engine, bindparam from sqlalchemy.orm import Session +from . import Profiler + Base = declarative_base() engine = None diff --git a/examples/performance/bulk_updates.py b/examples/performance/bulk_updates.py index ebb700068..0657c96f3 100644 --- a/examples/performance/bulk_updates.py +++ b/examples/performance/bulk_updates.py @@ -3,11 +3,14 @@ of rows in bulk. """ -from . import Profiler - +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import Integer +from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy import Column, Integer, String, create_engine, bindparam from sqlalchemy.orm import Session +from . import Profiler + Base = declarative_base() engine = None diff --git a/examples/performance/large_resultsets.py b/examples/performance/large_resultsets.py index ad1c23194..2945040b5 100644 --- a/examples/performance/large_resultsets.py +++ b/examples/performance/large_resultsets.py @@ -13,11 +13,15 @@ full blown ORM doesn't do terribly either even though mapped objects provide a huge amount of functionality. """ +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import Integer +from sqlalchemy import String +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import Bundle +from sqlalchemy.orm import Session from . import Profiler -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy import Column, Integer, String, create_engine -from sqlalchemy.orm import Session, Bundle Base = declarative_base() engine = None @@ -165,8 +169,8 @@ def _test_dbapi_raw(n, make_objects): # going to do this, so see how this pushes you right back into # ORM land anyway :) class SimpleCustomer(object): - def __init__(self, id, name, description): - self.id = id + def __init__(self, id_, name, description): + self.id = id_ self.name = name self.description = description diff --git a/examples/performance/short_selects.py b/examples/performance/short_selects.py index 4a8d401ad..376f18f02 100644 --- a/examples/performance/short_selects.py +++ b/examples/performance/short_selects.py @@ -3,20 +3,20 @@ record by primary key """ -from . import Profiler +import random -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy import ( - Column, - Integer, - String, - create_engine, - bindparam, - select, -) -from sqlalchemy.orm import Session, deferred +from sqlalchemy import bindparam +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import Integer +from sqlalchemy import select +from sqlalchemy import String from sqlalchemy.ext import baked -import random +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import deferred +from sqlalchemy.orm import Session +from . import Profiler + Base = declarative_base() engine = None diff --git a/examples/performance/single_inserts.py b/examples/performance/single_inserts.py index 79e34dfe6..428eb5c41 100644 --- a/examples/performance/single_inserts.py +++ b/examples/performance/single_inserts.py @@ -4,11 +4,16 @@ within a distinct transaction, and afterwards returns to essentially a a database connection, inserts the row, commits and closes. """ -from . import Profiler - +from sqlalchemy import bindparam +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import Integer +from sqlalchemy import pool +from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy import Column, Integer, String, create_engine, bindparam, pool from sqlalchemy.orm import Session +from . import Profiler + Base = declarative_base() engine = None diff --git a/examples/postgis/__init__.py b/examples/postgis/__init__.py index 66ae65d3c..963a561f3 100644 --- a/examples/postgis/__init__.py +++ b/examples/postgis/__init__.py @@ -31,7 +31,8 @@ and simple to use extension points. E.g.:: - print session.query(Road).filter(Road.road_geom.intersects(r1.road_geom)).all() + print session.query(Road).filter( + Road.road_geom.intersects(r1.road_geom)).all() .. autosource:: diff --git a/examples/postgis/postgis.py b/examples/postgis/postgis.py index 508d63398..868d3d055 100644 --- a/examples/postgis/postgis.py +++ b/examples/postgis/postgis.py @@ -1,8 +1,12 @@ -from sqlalchemy.types import UserDefinedType, _Binary, TypeDecorator -from sqlalchemy.sql import expression, type_coerce -from sqlalchemy import event, Table import binascii +from sqlalchemy import event +from sqlalchemy import Table +from sqlalchemy.sql import expression +from sqlalchemy.sql import type_coerce +from sqlalchemy.types import UserDefinedType + + # Python datatypes @@ -278,7 +282,8 @@ if __name__ == "__main__": ] ) - # or use an explicit TextualGisElement (similar to saying func.GeomFromText()) + # or use an explicit TextualGisElement + # (similar to saying func.GeomFromText()) r = Road( road_name="Dave Cres", road_geom=TextualGisElement( @@ -292,7 +297,8 @@ if __name__ == "__main__": session.commit() - # after flush and/or commit, all the TextualGisElements become PersistentGisElements. + # after flush and/or commit, all the TextualGisElements + # become PersistentGisElements. assert str(r.road_geom) == "LINESTRING(198231 263418,198213 268322)" r1 = session.query(Road).filter(Road.road_name == "Graeme Ave").one() @@ -318,16 +324,16 @@ if __name__ == "__main__": ) print(session.execute(stmt).fetchall()) - # TODO: for some reason the auto-generated labels have the internal replacement - # strings exposed, even though PG doesn't complain + # TODO: for some reason the auto-generated labels have the internal + # replacement strings exposed, even though PG doesn't complain # look up the hex binary version, using SQLAlchemy casts as_binary = session.scalar( select([type_coerce(r.road_geom, Geometry(coerce_="binary"))]) ) - assert ( - as_binary.as_hex - == "01020000000200000000000000b832084100000000e813104100000000283208410000000088601041" + assert as_binary.as_hex == ( + "01020000000200000000000000b832084100000000" + "e813104100000000283208410000000088601041" ) # back again, same method ! diff --git a/examples/sharding/__init__.py b/examples/sharding/__init__.py index 59d26a217..eb8e10686 100644 --- a/examples/sharding/__init__.py +++ b/examples/sharding/__init__.py @@ -8,7 +8,7 @@ The basic components of a "sharded" mapping are: * a function which can return a single shard id, given an instance to be saved; this is called "shard_chooser" * a function which can return a list of shard ids which apply to a particular - instance identifier; this is called "id_chooser". If it returns all shard ids, + instance identifier; this is called "id_chooser".If it returns all shard ids, all shards will be searched. * a function which can return a list of shard ids to try, given a particular Query ("query_chooser"). If it returns all shard ids, all shards will be diff --git a/examples/sharding/attribute_shard.py b/examples/sharding/attribute_shard.py index 48a3dc932..608f0f9c3 100644 --- a/examples/sharding/attribute_shard.py +++ b/examples/sharding/attribute_shard.py @@ -1,20 +1,21 @@ -from sqlalchemy import ( - create_engine, - Table, - Column, - Integer, - String, - ForeignKey, - Float, - DateTime, -) -from sqlalchemy.orm import sessionmaker, relationship -from sqlalchemy.ext.horizontal_shard import ShardedSession -from sqlalchemy.sql import operators, visitors -from sqlalchemy.ext.declarative import declarative_base +import datetime + +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import DateTime +from sqlalchemy import Float +from sqlalchemy import ForeignKey from sqlalchemy import inspect +from sqlalchemy import Integer +from sqlalchemy import String +from sqlalchemy import Table +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.ext.horizontal_shard import ShardedSession +from sqlalchemy.orm import relationship +from sqlalchemy.orm import sessionmaker +from sqlalchemy.sql import operators +from sqlalchemy.sql import visitors -import datetime # db1 is used for id generation. The "pool_threadlocal" # causes the id_generator() to use the same connection as that diff --git a/examples/space_invaders/space_invaders.py b/examples/space_invaders/space_invaders.py index d5437d8cf..34d233da1 100644 --- a/examples/space_invaders/space_invaders.py +++ b/examples/space_invaders/space_invaders.py @@ -1,14 +1,24 @@ -import sys -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy import create_engine, Integer, Column, ForeignKey, String, func -from sqlalchemy.orm import relationship, Session, joinedload -from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method import curses -import time -import textwrap -import re -import random import logging +import random +import re +import sys +import textwrap +import time + +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import func +from sqlalchemy import Integer +from sqlalchemy import String +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.ext.hybrid import hybrid_method +from sqlalchemy.ext.hybrid import hybrid_property +from sqlalchemy.orm import joinedload +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session + _PY3 = sys.version_info > (3, 0) if _PY3: @@ -39,7 +49,6 @@ PAUSE_KEY = ord("p") COLOR_MAP = { "K": curses.COLOR_BLACK, - "R": curses.COLOR_RED, "B": curses.COLOR_BLUE, "C": curses.COLOR_CYAN, "G": curses.COLOR_GREEN, diff --git a/examples/versioned_history/__init__.py b/examples/versioned_history/__init__.py index 7670cd613..e6db1fc2c 100644 --- a/examples/versioned_history/__init__.py +++ b/examples/versioned_history/__init__.py @@ -1,7 +1,7 @@ """ Illustrates an extension which creates version tables for entities and stores -records for each change. The given extensions generate an anonymous "history" class which -represents historical versions of the target object. +records for each change. The given extensions generate an anonymous "history" +class which represents historical versions of the target object. Compare to the :ref:`examples_versioned_rows` examples which write updates as new rows in the same table, without using a separate history table. diff --git a/examples/versioned_history/history_meta.py b/examples/versioned_history/history_meta.py index 749a6a5ca..2a331443d 100644 --- a/examples/versioned_history/history_meta.py +++ b/examples/versioned_history/history_meta.py @@ -1,11 +1,19 @@ """Versioned mixin class and other utilities.""" +import datetime + +from sqlalchemy import Column +from sqlalchemy import DateTime +from sqlalchemy import event +from sqlalchemy import ForeignKeyConstraint +from sqlalchemy import Integer +from sqlalchemy import Table +from sqlalchemy import util from sqlalchemy.ext.declarative import declared_attr -from sqlalchemy.orm import mapper, attributes, object_mapper +from sqlalchemy.orm import attributes +from sqlalchemy.orm import mapper +from sqlalchemy.orm import object_mapper from sqlalchemy.orm.exc import UnmappedColumnError -from sqlalchemy import Table, Column, ForeignKeyConstraint, Integer, DateTime -from sqlalchemy import event, util -import datetime from sqlalchemy.orm.properties import RelationshipProperty @@ -165,20 +173,20 @@ def _history_mapper(local_mapper): class Versioned(object): @declared_attr def __mapper_cls__(cls): - def map(cls, *arg, **kw): + def map_(cls, *arg, **kw): mp = mapper(cls, *arg, **kw) _history_mapper(mp) return mp - return map + return map_ __table_args__ = {"sqlite_autoincrement": True} """Use sqlite_autoincrement, to ensure unique integer values are used for new rows even for rows taht have been deleted.""" -def versioned_objects(iter): - for obj in iter: +def versioned_objects(iter_): + for obj in iter_: if hasattr(obj, "__history_mapper__"): yield obj diff --git a/examples/versioned_history/test_versioning.py b/examples/versioned_history/test_versioning.py index 3270ad5fd..44e545749 100644 --- a/examples/versioned_history/test_versioning.py +++ b/examples/versioned_history/test_versioning.py @@ -2,28 +2,30 @@ module functions.""" from unittest import TestCase +import warnings + +from sqlalchemy import Boolean +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import select +from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base -from .history_meta import Versioned, versioned_session -from sqlalchemy import ( - create_engine, - Column, - Integer, - String, - ForeignKey, - Boolean, - select, -) -from sqlalchemy.orm import ( - clear_mappers, - Session, - deferred, - relationship, - column_property, -) -from sqlalchemy.testing import AssertsCompiledSQL, eq_, assert_raises, ne_ -from sqlalchemy.testing.entities import ComparableEntity +from sqlalchemy.orm import clear_mappers +from sqlalchemy.orm import column_property +from sqlalchemy.orm import deferred from sqlalchemy.orm import exc as orm_exc -import warnings +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session +from sqlalchemy.testing import assert_raises +from sqlalchemy.testing import AssertsCompiledSQL +from sqlalchemy.testing import eq_ +from sqlalchemy.testing import ne_ +from sqlalchemy.testing.entities import ComparableEntity +from .history_meta import Versioned +from .history_meta import versioned_session + warnings.simplefilter("error") diff --git a/examples/versioned_rows/versioned_map.py b/examples/versioned_rows/versioned_map.py index 46bdbb783..9abbb3e09 100644 --- a/examples/versioned_rows/versioned_map.py +++ b/examples/versioned_rows/versioned_map.py @@ -28,20 +28,22 @@ those additional values. """ -from sqlalchemy import Column, String, Integer, ForeignKey, create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import ( - attributes, - relationship, - backref, - sessionmaker, - make_transient, - validates, - Session, -) +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import event +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import String from sqlalchemy.ext.associationproxy import association_proxy +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import attributes +from sqlalchemy.orm import backref +from sqlalchemy.orm import make_transient +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session +from sqlalchemy.orm import sessionmaker +from sqlalchemy.orm import validates from sqlalchemy.orm.collections import attribute_mapped_collection -from sqlalchemy import event @event.listens_for(Session, "before_flush") diff --git a/examples/versioned_rows/versioned_rows.py b/examples/versioned_rows/versioned_rows.py index 03e1c3510..01067431c 100644 --- a/examples/versioned_rows/versioned_rows.py +++ b/examples/versioned_rows/versioned_rows.py @@ -3,17 +3,19 @@ an UPDATE statement on a single row into an INSERT statement, so that a new row is inserted with the new data, keeping the old row intact. """ -from sqlalchemy.orm import ( - sessionmaker, - relationship, - make_transient, - backref, - Session, -) -from sqlalchemy import Column, ForeignKey, create_engine, Integer, String +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import event +from sqlalchemy import ForeignKey +from sqlalchemy import Integer +from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import attributes -from sqlalchemy import event +from sqlalchemy.orm import backref +from sqlalchemy.orm import make_transient +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session +from sqlalchemy.orm import sessionmaker class Versioned(object): diff --git a/examples/versioned_rows/versioned_rows_w_versionid.py b/examples/versioned_rows/versioned_rows_w_versionid.py index 5fd6f9fc4..4861fb366 100644 --- a/examples/versioned_rows/versioned_rows_w_versionid.py +++ b/examples/versioned_rows/versioned_rows_w_versionid.py @@ -6,27 +6,23 @@ This example adds a numerical version_id to the Versioned class as well as the ability to see which row is the most "current" vesion. """ -from sqlalchemy.orm import ( - sessionmaker, - relationship, - make_transient, - backref, - Session, - column_property, -) -from sqlalchemy import ( - Column, - ForeignKeyConstraint, - create_engine, - Integer, - String, - Boolean, - select, - func, -) +from sqlalchemy import Boolean +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import event +from sqlalchemy import ForeignKeyConstraint +from sqlalchemy import func +from sqlalchemy import Integer +from sqlalchemy import select +from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import attributes -from sqlalchemy import event +from sqlalchemy.orm import backref +from sqlalchemy.orm import column_property +from sqlalchemy.orm import make_transient +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session +from sqlalchemy.orm import sessionmaker class Versioned(object): diff --git a/examples/versioned_rows/versioned_update_old_row.py b/examples/versioned_rows/versioned_update_old_row.py index 17c82fdc3..5aa0f424a 100644 --- a/examples/versioned_rows/versioned_update_old_row.py +++ b/examples/versioned_rows/versioned_update_old_row.py @@ -5,29 +5,27 @@ to only the most recent version. """ -from sqlalchemy import ( - create_engine, - Integer, - String, - event, - Column, - DateTime, - inspect, - literal, -) -from sqlalchemy.orm import ( - make_transient, - Session, - relationship, - attributes, - backref, - make_transient_to_detached, - Query, -) -from sqlalchemy.ext.declarative import declarative_base import datetime import time +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import DateTime +from sqlalchemy import event +from sqlalchemy import inspect +from sqlalchemy import Integer +from sqlalchemy import literal +from sqlalchemy import String +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import attributes +from sqlalchemy.orm import backref +from sqlalchemy.orm import make_transient +from sqlalchemy.orm import make_transient_to_detached +from sqlalchemy.orm import Query +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session + + Base = declarative_base() # this will be the current time as the test runs diff --git a/examples/vertical/dictlike-polymorphic.py b/examples/vertical/dictlike-polymorphic.py index c000ff3cf..73d12ee4f 100644 --- a/examples/vertical/dictlike-polymorphic.py +++ b/examples/vertical/dictlike-polymorphic.py @@ -24,10 +24,10 @@ date. """ -from sqlalchemy.orm.interfaces import PropComparator -from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy import event from sqlalchemy import literal_column +from sqlalchemy.ext.hybrid import hybrid_property +from sqlalchemy.orm.interfaces import PropComparator from .dictlike import ProxiedDictMixin -- cgit v1.2.1