Here are the examples of the python api sqlalchemy.exc.ArgumentError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
69 Examples
3
Example 1
View licensedef __init__(self, precision=None, scale=None, asdecimal=True, **kw): if isinstance(self, (REAL, DOUBLE)) and \ ( (precision is None and scale is not None) or (precision is not None and scale is None) ): raise exc.ArgumentError( "You must specify both precision and scale or omit " "both altogether.") super(_FloatType, self).__init__(precision=precision, asdecimal=asdecimal, **kw) self.scale = scale
3
Example 2
View licensedef __init__(self, precision=None, scale=None, asdecimal=True, **kw): if isinstance(self, (REAL, DOUBLE)) and \ ( (precision is None and scale is not None) or (precision is not None and scale is None) ): raise exc.ArgumentError( "You must specify both precision and scale or omit " "both altogether.") super(_FloatType, self).__init__(precision=precision, asdecimal=asdecimal, **kw) self.scale = scale
3
Example 3
View licensedef __init__(self, precision=None, scale=None, asdecimal=True, **kw): if isinstance(self, (REAL, DOUBLE)) and \ ( (precision is None and scale is not None) or (precision is not None and scale is None) ): raise exc.ArgumentError( "You must specify both precision and scale or omit " "both altogether.") super(_FloatType, self).__init__(precision=precision, asdecimal=asdecimal, **kw) self.scale = scale
3
Example 4
View licensedef test_bitwise_required_for_empty(self): assert_raises_message( exc.ArgumentError, "Can't use the blank value '' in a SET without setting " "retrieve_as_bitwise=True", mysql.SET, "a", "b", '' )
3
Example 5
View licensedef test_unmapped_not_type_error(self): """extension version of the same test in test_mapper. fixes #3408 """ assert_raises_message( sa.exc.ArgumentError, "Class object expected, got '5'.", class_mapper, 5 )
3
Example 6
View licensedef test_unmapped_not_type_error_iter_ok(self): """extension version of the same test in test_mapper. fixes #3408 """ assert_raises_message( sa.exc.ArgumentError, r"Class object expected, got '\(5, 6\)'.", class_mapper, (5, 6) )
3
Example 7
View licensedef test_bind_arg(self): sess = Session() assert_raises_message( sa.exc.ArgumentError, "Not an acceptable bind target: foobar", sess.bind_mapper, "foobar", testing.db ) mapper(self.classes.User, self.tables.users) u_object = self.classes.User() assert_raises_message( sa.exc.ArgumentError, "Not an acceptable bind target: User()", sess.bind_mapper, u_object, testing.db )
3
Example 8
View licensedef test_unknown_legacy_lock_mode(self): User = self.classes.User sess = Session() assert_raises_message( exc.ArgumentError, "Unknown with_lockmode argument: 'unknown_mode'", sess.query(User.id).with_lockmode, 'unknown_mode' )
3
Example 9
View licensedef test_overlapping_attribute_error(self): place, Transition, place_input, Place, transition = (self.tables.place, self.classes.Transition, self.tables.place_input, self.classes.Place, self.tables.transition) mapper(Place, place, properties={ 'transitions': relationship(Transition, secondary=place_input, backref='places') }) mapper(Transition, transition, properties={ 'places': relationship(Place, secondary=place_input, backref='transitions') }) assert_raises_message(sa.exc.ArgumentError, "property of that name exists", sa.orm.configure_mappers)
3
Example 10
View licensedef test_gen_path_invalid_from_col(self): User = self.classes.User l = Load(User) l.path = self._make_path_registry([User, "name"]) assert_raises_message( sa.exc.ArgumentError, "Attribute 'name' of entity 'Mapper|User|users' does " "not refer to a mapped entity", l._generate_path, l.path, User.addresses, "relationship" )
3
Example 11
View licensedef test_gen_path_attr_entity_invalid_raiseerr(self): User = self.classes.User Order = self.classes.Order l = Load(User) assert_raises_message( sa.exc.ArgumentError, "Attribute 'Order.items' does not link from element 'Mapper|User|users'", l._generate_path, inspect(User)._path_registry, Order.items, "relationship", )
3
Example 12
View licensedef _assert_eager_with_entity_exception(self, entity_list, options, message): assert_raises_message(sa.exc.ArgumentError, message, create_session().query(*entity_list).options, *options)
3
Example 13
View licensedef _assert_raises_no_relevant_fks(self, fn, expr, relname, primary, *arg, **kw): assert_raises_message( exc.ArgumentError, r"Could not locate any relevant foreign key columns " r"for %s join condition '%s' on relationship %s. " r"Ensure that referencing columns are associated with " r"a ForeignKey or ForeignKeyConstraint, or are annotated " r"in the join condition with the foreign\(\) annotation." % ( primary, expr, relname ), fn, *arg, **kw )
3
Example 14
View licensedef _assert_raises_no_equality(self, fn, expr, relname, primary, *arg, **kw): assert_raises_message( exc.ArgumentError, "Could not locate any simple equality expressions " "involving locally mapped foreign key columns for %s join " "condition '%s' on relationship %s. " "Ensure that referencing columns are associated with a " "ForeignKey or ForeignKeyConstraint, or are annotated in " r"the join condition with the foreign\(\) annotation. " "To allow comparison operators other than '==', " "the relationship can be marked as viewonly=True." % ( primary, expr, relname ), fn, *arg, **kw )
3
Example 15
View licensedef test_no_table_needs_pl(self): Subset = self.classes.Subset selectable = select([column("x"), column("y"), column("z")]).alias() assert_raises_message( sa.exc.ArgumentError, "could not assemble any primary key columns", mapper, Subset, selectable )
3
Example 16
View licensedef test_illegal_eval(self): User = self.classes.User s = Session() assert_raises_message( exc.ArgumentError, "Valid strategies for session synchronization " "are 'evaluate', 'fetch', False", s.query(User).update, {}, synchronize_session="fake" )
3
Example 17
View licensedef test_literal_interpretation(self): t = table('test', column('col1')) assert_raises(exc.ArgumentError, case, [("x", "y")]) self.assert_compile( case([("x", "y")], value=t.c.col1), "CASE test.col1 WHEN :param_1 THEN :param_2 END") self.assert_compile( case([(t.c.col1 == 7, "y")], else_="z"), "CASE WHEN (test.col1 = :col1_1) THEN :param_1 ELSE :param_2 END")
3
Example 18
View licensedef test_missing_bind_kw(self): assert_raises_message( exc.ArgumentError, "This text\(\) construct doesn't define a bound parameter named 'bar'", text(":foo").bindparams, foo=5, bar=7)
3
Example 19
View licensedef test_missing_bind_posn(self): assert_raises_message( exc.ArgumentError, "This text\(\) construct doesn't define a bound parameter named 'bar'", text(":foo").bindparams, bindparam( 'foo', value=5), bindparam( 'bar', value=7))
3
Example 20
View licensedef format_type(self, type_, use_schema=True): if not type_.name: raise exc.ArgumentError("Postgresql ENUM type requires a name.") name = self.quote(type_.name, type_.quote) if not self.omit_schema and use_schema and type_.schema is not None: name = self.quote_schema(type_.schema, type_.quote) + "." + name return name
3
Example 21
View licensedef visit_extract(self, extract, **kw): try: return "CAST(STRFTIME('%s', %s) AS INTEGER)" % ( self.extract_map[extract.field], self.process(extract.expr, **kw)) except KeyError: raise exc.ArgumentError( "%s is not a valid extract argument." % extract.field)
3
Example 22
View licensedef create_connect_args(self, url): if url.username or url.password or url.host or url.port: raise exc.ArgumentError( "Invalid SQLite URL: %s\n" "Valid SQLite URL forms are:\n" " sqlite:///:memory: (or, sqlite://)\n" " sqlite:///relative/path/to/file.db\n" " sqlite:////absolute/path/to/file.db" % (url,)) filename = url.database or ':memory:' opts = url.query.copy() util.coerce_kw_type(opts, 'timeout', float) util.coerce_kw_type(opts, 'isolation_level', str) util.coerce_kw_type(opts, 'detect_types', int) util.coerce_kw_type(opts, 'check_same_thread', bool) util.coerce_kw_type(opts, 'cached_statements', int) return ([filename], opts)
3
Example 23
View licensedef __init__(self, precision=None, scale=None, asdecimal=True, **kw): if isinstance(self, (REAL, DOUBLE)) and \ ( (precision is None and scale is not None) or (precision is not None and scale is None) ): raise exc.ArgumentError( "You must specify both precision and scale or omit " "both altogether.") super(_FloatType, self).__init__(precision=precision, asdecimal=asdecimal, **kw) self.scale = scale
3
Example 24
View licensedef __init__(self, precision=None, scale=None, asdecimal=True, **kw): if isinstance(self, (REAL, DOUBLE)) and \ ( (precision is None and scale is not None) or (precision is not None and scale is None) ): raise exc.ArgumentError( "You must specify both precision and scale or omit " "both altogether.") super(_FloatType, self).__init__(precision=precision, asdecimal=asdecimal, **kw) self.scale = scale
3
Example 25
View licensedef __init__(self, precision=None, scale=None, asdecimal=True, **kw): if isinstance(self, (REAL, DOUBLE)) and \ ( (precision is None and scale is not None) or (precision is not None and scale is None) ): raise exc.ArgumentError( "You must specify both precision and scale or omit " "both altogether.") super(_FloatType, self).__init__(precision=precision, asdecimal=asdecimal, **kw) self.scale = scale
3
Example 26
View licensedef set_isolation_level(self, connection, level): try: level = self._isolation_lookup[level.replace('_', ' ')] except KeyError: raise exc.ArgumentError( "Invalid value '%s' for isolation_level. " "Valid isolation levels for %s are %s" % (level, self.name, ", ".join(self._isolation_lookup)) ) connection.set_isolation_level(level)
3
Example 27
View licensedef visit_extract(self, extract, **kw): try: return "CAST(STRFTIME('%s', %s) AS INTEGER)" % ( self.extract_map[extract.field], self.process(extract.expr, **kw)) except KeyError: raise exc.ArgumentError( "%s is not a valid extract argument." % extract.field)
3
Example 28
View licensedef set_isolation_level(self, connection, level): try: isolation_level = self._isolation_lookup[level.replace('_', ' ')] except KeyError: raise exc.ArgumentError( "Invalid value '%s' for isolation_level. " "Valid isolation levels for %s are %s" % (level, self.name, ", ".join(self._isolation_lookup)) ) cursor = connection.cursor() cursor.execute("PRAGMA read_uncommitted = %d" % isolation_level) cursor.close()
3
Example 29
View licensedef set_isolation_level(self, connection, level): try: level = self._isolation_lookup[level.replace('_', ' ')] except KeyError: raise exc.ArgumentError( "Invalid value '%s' for isolation_level. " "Valid isolation levels for %s are %s" % (level, self.name, ", ".join(self._isolation_lookup)) ) connection.set_isolation_level(level)
3
Example 30
View licensedef visit_extract(self, extract, **kw): try: return "CAST(STRFTIME('%s', %s) AS INTEGER)" % ( self.extract_map[extract.field], self.process(extract.expr, **kw)) except KeyError: raise exc.ArgumentError( "%s is not a valid extract argument." % extract.field)
3
Example 31
View licensedef set_isolation_level(self, connection, level): try: isolation_level = self._isolation_lookup[level.replace('_', ' ')] except KeyError: raise exc.ArgumentError( "Invalid value '%s' for isolation_level. " "Valid isolation levels for %s are %s" % (level, self.name, ", ".join(self._isolation_lookup)) ) cursor = connection.cursor() cursor.execute("PRAGMA read_uncommitted = %d" % isolation_level) cursor.close()
3
Example 32
View license@classmethod def _accept_with(cls, target): if isinstance(target, orm.ScopedSession): if not isinstance(target.session_factory, type) or \ not issubclass(target.session_factory, orm.Session): raise exc.ArgumentError( "Session event listen on a ScopedSession " "requires that its creation callable " "is a Session subclass.") return target.session_factory elif isinstance(target, type): if issubclass(target, orm.ScopedSession): return orm.Session elif issubclass(target, orm.Session): return target elif isinstance(target, orm.Session): return target else: return None
3
Example 33
View license@classmethod def _accept_with(cls, target): if isinstance(target, orm.ScopedSession): if not isinstance(target.session_factory, type) or \ not issubclass(target.session_factory, orm.Session): raise exc.ArgumentError( "Session event listen on a ScopedSession " "requires that its creation callable " "is a Session subclass.") return target.session_factory elif isinstance(target, type): if issubclass(target, orm.ScopedSession): return orm.Session elif issubclass(target, orm.Session): return target elif isinstance(target, orm.Session): return target else: return None
3
Example 34
View licensedef assert_arg_type(arg, argtype, name): if isinstance(arg, argtype): return arg else: if isinstance(argtype, tuple): raise exc.ArgumentError( "Argument '%s' is expected to be one of type %s, got '%s'" % (name, ' or '.join("'%s'" % a for a in argtype), type(arg))) else: raise exc.ArgumentError( "Argument '%s' is expected to be of type '%s', got '%s'" % (name, argtype, type(arg)))
3
Example 35
View licensedef assert_arg_type(arg, argtype, name): if isinstance(arg, argtype): return arg else: if isinstance(argtype, tuple): raise exc.ArgumentError( "Argument '%s' is expected to be one of type %s, got '%s'" % (name, ' or '.join("'%s'" % a for a in argtype), type(arg))) else: raise exc.ArgumentError( "Argument '%s' is expected to be of type '%s', got '%s'" % (name, argtype, type(arg)))
0
Example 36
View licensedef create_connect_args(self, url): if url.username or url.password or url.host or url.port: raise exc.ArgumentError( "Invalid SQLite URL: %s\n" "Valid SQLite URL forms are:\n" " sqlite:///:memory: (or, sqlite://)\n" " sqlite:///relative/path/to/file.db\n" " sqlite:////absolute/path/to/file.db" % (url,)) filename = url.database or ':memory:' if filename != ':memory:': filename = os.path.abspath(filename) opts = url.query.copy() util.coerce_kw_type(opts, 'timeout', float) util.coerce_kw_type(opts, 'isolation_level', str) util.coerce_kw_type(opts, 'detect_types', int) util.coerce_kw_type(opts, 'check_same_thread', bool) util.coerce_kw_type(opts, 'cached_statements', int) return ([filename], opts)
0
Example 37
View licensedef create_connect_args(self, url): if url.username or url.password or url.host or url.port: raise exc.ArgumentError( "Invalid SQLite URL: %s\n" "Valid SQLite URL forms are:\n" " sqlite:///:memory: (or, sqlite://)\n" " sqlite:///relative/path/to/file.db\n" " sqlite:////absolute/path/to/file.db" % (url,)) filename = url.database or ':memory:' if filename != ':memory:': filename = os.path.abspath(filename) opts = url.query.copy() util.coerce_kw_type(opts, 'timeout', float) util.coerce_kw_type(opts, 'isolation_level', str) util.coerce_kw_type(opts, 'detect_types', int) util.coerce_kw_type(opts, 'check_same_thread', bool) util.coerce_kw_type(opts, 'cached_statements', int) return ([filename], opts)
0
Example 38
View licensedef create_connect_args(self, url): if url.username or url.password or url.host or url.port: raise exc.ArgumentError( "Invalid SQLite URL: %s\n" "Valid SQLite URL forms are:\n" " sqlite:///:memory: (or, sqlite://)\n" " sqlite:///relative/path/to/file.db\n" " sqlite:////absolute/path/to/file.db" % (url,)) filename = url.database or ':memory:' if filename != ':memory:': filename = os.path.abspath(filename) opts = url.query.copy() util.coerce_kw_type(opts, 'timeout', float) util.coerce_kw_type(opts, 'isolation_level', str) util.coerce_kw_type(opts, 'detect_types', int) util.coerce_kw_type(opts, 'check_same_thread', bool) util.coerce_kw_type(opts, 'cached_statements', int) return ([filename], opts)
0
Example 39
View licensedef create_connect_args(self, url): if url.username or url.password or url.host or url.port: raise exc.ArgumentError( "Invalid SQLite URL: %s\n" "Valid SQLite URL forms are:\n" " sqlite:///:memory: (or, sqlite://)\n" " sqlite:///relative/path/to/file.db\n" " sqlite:////absolute/path/to/file.db" % (url,)) filename = url.database or ':memory:' if filename != ':memory:': filename = os.path.abspath(filename) opts = url.query.copy() util.coerce_kw_type(opts, 'timeout', float) util.coerce_kw_type(opts, 'isolation_level', str) util.coerce_kw_type(opts, 'detect_types', int) util.coerce_kw_type(opts, 'check_same_thread', bool) util.coerce_kw_type(opts, 'cached_statements', int) return ([filename], opts)
0
Example 40
View licensedef test_reset_on_return(self): dbapi = MockDBAPI(foober=12, lala=18, hoho={'this': 'dict'}, fooz='somevalue') for (value, expected) in [ ('rollback', pool.reset_rollback), ('commit', pool.reset_commit), (None, pool.reset_none), (True, pool.reset_rollback), (False, pool.reset_none), ]: e = create_engine( 'postgresql://', pool_reset_on_return=value, module=dbapi, _initialize=False) assert e.pool._reset_on_return is expected assert_raises( exc.ArgumentError, create_engine, "postgresql://", pool_reset_on_return='hi', module=dbapi, _initialize=False )
0
Example 41
View licensedef test_bad_args(self): assert_raises(exc.ArgumentError, create_engine, 'foobar://', module=mock_dbapi) # bad arg assert_raises(TypeError, create_engine, 'postgresql://', use_ansi=True, module=mock_dbapi) # bad arg assert_raises( TypeError, create_engine, 'oracle://', lala=5, use_ansi=True, module=mock_dbapi, ) assert_raises(TypeError, create_engine, 'postgresql://', lala=5, module=mock_dbapi) assert_raises(TypeError, create_engine, 'sqlite://', lala=5, module=mock_sqlite_dbapi) assert_raises(TypeError, create_engine, 'mysql+mysqldb://', use_unicode=True, module=mock_dbapi)
0
Example 42
View licensedef _assert_eager_with_just_column_exception(self, column, eager_option, message): assert_raises_message(sa.exc.ArgumentError, message, create_session().query(column).options, joinedload(eager_option))
0
Example 43
View licensedef __init__(self, item_type, mutable=True, as_tuple=False): """Construct an ARRAY. E.g.:: Column('myarray', ARRAY(Integer)) Arguments are: :param item_type: The data type of items of this array. Note that dimensionality is irrelevant here, so multi-dimensional arrays like ``INTEGER[][]``, are constructed as ``ARRAY(Integer)``, not as ``ARRAY(ARRAY(Integer))`` or such. The type mapping figures out on the fly :param mutable=True: Specify whether lists passed to this class should be considered mutable. If so, generic copy operations (typically used by the ORM) will shallow-copy values. :param as_tuple=False: Specify whether return results should be converted to tuples from lists. DBAPIs such as psycopg2 return lists by default. When tuples are returned, the results are hashable. This flag can only be set to ``True`` when ``mutable`` is set to ``False``. (new in 0.6.5) """ if isinstance(item_type, ARRAY): raise ValueError("Do not nest ARRAY types; ARRAY(basetype) " "handles multi-dimensional arrays of basetype") if isinstance(item_type, type): item_type = item_type() self.item_type = item_type self.mutable = mutable if mutable and as_tuple: raise exc.ArgumentError( "mutable must be set to False if as_tuple is True." ) self.as_tuple = as_tuple
0
Example 44
View licensedef __init__(self, isolation_level=None, native_datetime=False, **kwargs): default.DefaultDialect.__init__(self, **kwargs) if isolation_level and isolation_level not in ('SERIALIZABLE', 'READ UNCOMMITTED'): raise exc.ArgumentError("Invalid value for isolation_level. " "Valid isolation levels for sqlite are 'SERIALIZABLE' and " "'READ UNCOMMITTED'.") self.isolation_level = isolation_level # this flag used by pysqlite dialect, and perhaps others in the # future, to indicate the driver is handling date/timestamp # conversions (and perhaps datetime/time as well on some # hypothetical driver ?) self.native_datetime = native_datetime if self.dbapi is not None: self.supports_default_values = \ self.dbapi.sqlite_version_info >= (3, 3, 8) self.supports_cast = \ self.dbapi.sqlite_version_info >= (3, 2, 3)
0
Example 45
View licensedef __init__(self, convert_unicode=False, assert_unicode=False, encoding='utf-8', paramstyle=None, dbapi=None, implicit_returning=None, label_length=None, **kwargs): if not getattr(self, 'ported_sqla_06', True): util.warn( "The %s dialect is not yet ported to SQLAlchemy 0.6" % self.name) self.convert_unicode = convert_unicode if assert_unicode: util.warn_deprecated( "assert_unicode is deprecated. " "SQLAlchemy emits a warning in all cases where it " "would otherwise like to encode a Python unicode object " "into a specific encoding but a plain bytestring is " "received. " "This does *not* apply to DBAPIs that coerce Unicode " "natively.") self.encoding = encoding self.positional = False self._ischema = None self.dbapi = dbapi if paramstyle is not None: self.paramstyle = paramstyle elif self.dbapi is not None: self.paramstyle = self.dbapi.paramstyle else: self.paramstyle = self.default_paramstyle if implicit_returning is not None: self.implicit_returning = implicit_returning self.positional = self.paramstyle in ('qmark', 'format', 'numeric') self.identifier_preparer = self.preparer(self) self.type_compiler = self.type_compiler(self) if label_length and label_length > self.max_identifier_length: raise exc.ArgumentError( "Label length of %d is greater than this dialect's" " maximum identifier length of %d" % (label_length, self.max_identifier_length)) self.label_length = label_length if not hasattr(self, 'description_encoding'): self.description_encoding = getattr( self, 'description_encoding', encoding)
0
Example 46
View licensedef __init__(self, dialect, connection, compiled_sql=None, compiled_ddl=None, statement=None, parameters=None): self.dialect = dialect self._connection = self.root_connection = connection self.engine = connection.engine if compiled_ddl is not None: self.compiled = compiled = compiled_ddl self.isddl = True if compiled.statement._execution_options: self.execution_options = compiled.statement._execution_options if connection._execution_options: self.execution_options = self.execution_options.union( connection._execution_options ) if not dialect.supports_unicode_statements: self.unicode_statement = unicode(compiled) self.statement = self.unicode_statement.encode(self.dialect.encoding) else: self.statement = self.unicode_statement = unicode(compiled) self.cursor = self.create_cursor() self.compiled_parameters = [] self.parameters = [self._default_params] elif compiled_sql is not None: self.compiled = compiled = compiled_sql if not compiled.can_execute: raise exc.ArgumentError("Not an executable clause: %s" % compiled) if compiled.statement._execution_options: self.execution_options = compiled.statement._execution_options if connection._execution_options: self.execution_options = self.execution_options.union( connection._execution_options ) # compiled clauseelement. process bind params, process table defaults, # track collections used by ResultProxy to target and process results self.processors = dict( (key, value) for key, value in ( (compiled.bind_names[bindparam], bindparam.bind_processor(self.dialect)) for bindparam in compiled.bind_names ) if value is not None) self.result_map = compiled.result_map if not dialect.supports_unicode_statements: self.unicode_statement = unicode(compiled) self.statement = self.unicode_statement.encode(self.dialect.encoding) else: self.statement = self.unicode_statement = unicode(compiled) self.isinsert = compiled.isinsert self.isupdate = compiled.isupdate self.isdelete = compiled.isdelete if not parameters: self.compiled_parameters = [compiled.construct_params()] else: self.compiled_parameters = [compiled.construct_params(m, _group_number=grp) for grp,m in enumerate(parameters)] self.executemany = len(parameters) > 1 self.cursor = self.create_cursor() if self.isinsert or self.isupdate: self.__process_defaults() self.parameters = self.__convert_compiled_params(self.compiled_parameters) elif statement is not None: # plain text statement if connection._execution_options: self.execution_options = self.execution_options.union(connection._execution_options) self.parameters = self.__encode_param_keys(parameters) self.executemany = len(parameters) > 1 if isinstance(statement, unicode) and not dialect.supports_unicode_statements: self.unicode_statement = statement self.statement = statement.encode(self.dialect.encoding) else: self.statement = self.unicode_statement = statement self.cursor = self.create_cursor() else: # no statement. used for standalone ColumnDefault execution. if connection._execution_options: self.execution_options = self.execution_options.union(connection._execution_options) self.cursor = self.create_cursor()
0
Example 47
View licensedef _parse_rfc1738_args(name): pattern = re.compile(r''' (?P<name>[\w\+]+):// (?: (?P<username>[^:/]*) (?::(?P<password>[^/]*))? @)? (?: (?P<host>[^/:]*) (?::(?P<port>[^/]*))? )? (?:/(?P<database>.*))? ''' , re.X) m = pattern.match(name) if m is not None: components = m.groupdict() if components['database'] is not None: tokens = components['database'].split('?', 2) components['database'] = tokens[0] query = (len(tokens) > 1 and dict(cgi.parse_qsl(tokens[1]))) or None # Py2K if query is not None: query = dict((k.encode('ascii'), query[k]) for k in query) # end Py2K else: query = None components['query'] = query if components['password'] is not None: components['password'] = urllib.unquote_plus(components['password']) name = components.pop('name') return URL(name, **components) else: raise exc.ArgumentError( "Could not parse rfc1738 URL from string '%s'" % name)
0
Example 48
View licensedef criterion_as_pairs(expression, consider_as_foreign_keys=None, consider_as_referenced_keys=None, any_operator=False): """traverse an expression and locate binary criterion pairs.""" if consider_as_foreign_keys and consider_as_referenced_keys: raise exc.ArgumentError("Can only specify one of " "'consider_as_foreign_keys' or " "'consider_as_referenced_keys'") def visit_binary(binary): if not any_operator and binary.operator is not operators.eq: return if not isinstance(binary.left, sql.ColumnElement) or \ not isinstance(binary.right, sql.ColumnElement): return if consider_as_foreign_keys: if binary.left in consider_as_foreign_keys and \ (binary.right is binary.left or binary.right not in consider_as_foreign_keys): pairs.append((binary.right, binary.left)) elif binary.right in consider_as_foreign_keys and \ (binary.left is binary.right or binary.left not in consider_as_foreign_keys): pairs.append((binary.left, binary.right)) elif consider_as_referenced_keys: if binary.left in consider_as_referenced_keys and \ (binary.right is binary.left or binary.right not in consider_as_referenced_keys): pairs.append((binary.left, binary.right)) elif binary.right in consider_as_referenced_keys and \ (binary.left is binary.right or binary.left not in consider_as_referenced_keys): pairs.append((binary.right, binary.left)) else: if isinstance(binary.left, schema.Column) and \ isinstance(binary.right, schema.Column): if binary.left.references(binary.right): pairs.append((binary.right, binary.left)) elif binary.right.references(binary.left): pairs.append((binary.left, binary.right)) pairs = [] visitors.traverse(expression, {}, {'binary':visit_binary}) return pairs
0
Example 49
View licensedef create_connect_args(self, url): if url.username or url.password or url.host or url.port: raise exc.ArgumentError( "Invalid SQLite URL: %s\n" "Valid SQLite URL forms are:\n" " sqlite:///:memory: (or, sqlite://)\n" " sqlite:///relative/path/to/file.db\n" " sqlite:////absolute/path/to/file.db" % (url,)) filename = url.database or ':memory:' if filename != ':memory:': filename = os.path.abspath(filename) opts = url.query.copy() util.coerce_kw_type(opts, 'timeout', float) util.coerce_kw_type(opts, 'isolation_level', str) util.coerce_kw_type(opts, 'detect_types', int) util.coerce_kw_type(opts, 'check_same_thread', bool) util.coerce_kw_type(opts, 'cached_statements', int) return ([filename], opts)
0
Example 50
View licensedef create_engine(uri, relative_to=None, debug=False): """Create a new engine. This works a bit like SQLAlchemy's `create_engine` with the difference that it automaticaly set's MySQL engines to 'utf-8', and paths for SQLite are relative to the path provided as `relative_to`. Furthermore the engine is created with `convert_unicode` by default. """ # special case sqlite. We want nicer urls for that one. if uri.startswith('sqlite:'): match = _sqlite_re.match(uri) if match is None: raise ArgumentError('Could not parse rfc1738 URL') database, query = match.groups() if database is None: database = ':memory:' elif relative_to is not None: database = path.join(relative_to, database) if query: query = url_decode(query).to_dict() else: query = {} info = URL('sqlite', database=database, query=query) else: info = make_url(uri) # if mysql is the database engine and no connection encoding is # provided we set it to utf-8 if info.drivername == 'mysql': info.query.setdefault('charset', 'utf8') options = {'convert_unicode': True} # alternative pool sizes / recycle settings and more. These are # interpreter wide and not from the config for the following reasons: # # - system administrators can set it independently from the webserver # configuration via SetEnv and friends. # - this setting is deployment dependent should not affect a development # server for the same instance or a development shell for key in 'pool_size', 'pool_recycle', 'pool_timeout': value = os.environ.get('ZINE_DATABASE_' + key.upper()) if value is not None: options[key] = int(value) # if debugging is enabled, hook the ConnectionDebugProxy in if debug: options['proxy'] = ConnectionDebugProxy() return sqlalchemy.create_engine(info, **options)