sqlalchemy.engine.url make_url Example Code

make_url is a callable within the sqlalchemy.engine.url module of the SQLAlchemy project.

Example 1 from CTFd

CTFd (homepage) is a capture the flag (CTF) hacking web app built with SQLAlchemy and Flask. The application can be used as-is to run CTF events, or the code can be modified for custom rules on hacking scenarios. CTFd is open sourced under the Apache License 2.0.

CTFd / tests / helpers.py

# helpers.py
import datetime
import gc
import random
import string
import uuid
from collections import namedtuple
from unittest.mock import Mock, patch

import requests
from flask.testing import FlaskClient
from sqlalchemy.engine.url import make_url
from sqlalchemy_utils import drop_database
from werkzeug.datastructures import Headers

from CTFd import create_app
from CTFd.cache import cache, clear_standings
from CTFd.config import TestingConfig
from CTFd.models import (
    Awards,
    ChallengeFiles,
    Challenges,
    Fails,
    Files,
    Flags,
    Hints,
    Notifications,
    PageFiles,
    Pages,
    Solves,
    Tags,
    Teams,
    Tokens,
    Tracking,
    Unlocks,
    Users,


## ... source file abbreviated to get to make_url examples ...


                if isinstance(headers, dict):
                    headers = Headers(headers)
                headers.extend(api_key_headers)
                kwargs["headers"] = headers
        return super(CTFdTestClient, self).open(*args, **kwargs)


def create_ctfd(
    ctf_name="CTFd",
    ctf_description="CTF description",
    name="admin",
    email="[email protected]",
    password="password",
    user_mode="users",
    setup=True,
    enable_plugins=False,
    application_root="/",
    config=TestingConfig,
):
    if enable_plugins:
        config.SAFE_MODE = False
    else:
        config.SAFE_MODE = True

    config.APPLICATION_ROOT = application_root
    url = make_url(config.SQLALCHEMY_DATABASE_URI)
    if url.database:
        url.database = str(uuid.uuid4())
    config.SQLALCHEMY_DATABASE_URI = str(url)

    app = create_app(config)
    app.test_client_class = CTFdTestClient

    if setup:
        app = setup_ctfd(
            app,
            ctf_name=ctf_name,
            ctf_description=ctf_description,
            name=name,
            email=email,
            password=password,
            user_mode=user_mode,
        )
    return app


def setup_ctfd(
    app,
    ctf_name="CTFd",
    ctf_description="CTF description",


## ... source file continues with no further make_url examples...

Example 2 from flask-sqlalchemy

flask-sqlalchemy (project documentation and PyPI information) is a Flask extension that makes it easier to use SQLAlchemy when building Flask apps. flask-sqlalchemy provides helper functions that reduce the amount of common boilerplate code that you have to frequently write yourself if you did not use this library when combining Flask with SQLAlchemy.

flask-sqlalchemy is provided as open source under the BSD 3-Clause "New" or "Revised" License.

flask-sqlalchemy / src/flask_sqlalchemy / init.py

# __init__.py
import functools
import os
import sys
import warnings
from math import ceil
from operator import itemgetter
from threading import Lock
from time import perf_counter

import sqlalchemy
from flask import _app_ctx_stack
from flask import abort
from flask import current_app
from flask import request
from flask.signals import Namespace
from sqlalchemy import event
from sqlalchemy import inspect
from sqlalchemy import orm
from sqlalchemy.engine.url import make_url
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import DeclarativeMeta
from sqlalchemy.orm.exc import UnmappedClassError
from sqlalchemy.orm.session import Session as SessionBase

from .model import DefaultMeta
from .model import Model

__version__ = "3.0.0.dev"

_signals = Namespace()
models_committed = _signals.signal("models-committed")
before_models_committed = _signals.signal("before-models-committed")


def _make_table(db):
    def _make_table(*args, **kwargs):
        if len(args) > 1 and isinstance(args[1], db.Column):
            args = (args[0], db.metadata) + args[1:]
        info = kwargs.pop("info", None) or {}
        info.setdefault("bind_key", None)
        kwargs["info"] = info
        return sqlalchemy.Table(*args, **kwargs)



## ... source file abbreviated to get to make_url examples ...


class _EngineConnector:
    def __init__(self, sa, app, bind=None):
        self._sa = sa
        self._app = app
        self._engine = None
        self._connected_for = None
        self._bind = bind
        self._lock = Lock()

    def get_uri(self):
        if self._bind is None:
            return self._app.config["SQLALCHEMY_DATABASE_URI"]
        binds = self._app.config.get("SQLALCHEMY_BINDS") or ()
        assert (
            self._bind in binds
        ), f"Bind {self._bind!r} is not configured in 'SQLALCHEMY_BINDS'."
        return binds[self._bind]

    def get_engine(self):
        with self._lock:
            uri = self.get_uri()
            echo = self._app.config["SQLALCHEMY_ECHO"]
            if (uri, echo) == self._connected_for:
                return self._engine

            sa_url = make_url(uri)
            options = self.get_options(sa_url, echo)
            self._engine = rv = self._sa.create_engine(sa_url, options)

            if _record_queries(self._app):
                _EngineDebuggingSignalEvents(
                    self._engine, self._app.import_name
                ).register()

            self._connected_for = (uri, echo)

            return rv

    def get_options(self, sa_url, echo):
        options = {}

        self._sa.apply_driver_hacks(self._app, sa_url, options)

        if echo:
            options["echo"] = echo

        options.update(self._app.config["SQLALCHEMY_ENGINE_OPTIONS"])
        options.update(self._sa._engine_options)
        return options



## ... source file continues with no further make_url examples...

Example 3 from GINO

GINO (project documentation and PyPI package information) is an object-relational mapper (ORM) built on SQLAlchemy that is non-blocking and therefore designed to work properly with asynchronously-run code, for example, an application written with asyncio.

GINO is open sourced under the BSD License.

GINO / src/gino / api.py

# api.py
import weakref

import sqlalchemy as sa
from sqlalchemy.engine.url import make_url, URL
from sqlalchemy.sql.base import Executable
from sqlalchemy.sql.schema import SchemaItem

from . import json_support
from .crud import CRUDModel
from .declarative import declarative_base, declared_attr
from .exceptions import UninitializedError
from .schema import GinoSchemaVisitor, patch_schema


class GinoExecutor:

    __slots__ = ("_query",)

    def __init__(self, query):
        self._query = query

    @property
    def query(self):
        return self._query

    def model(self, model):
        if model is not None:
            model = weakref.ref(model)


## ... source file abbreviated to get to make_url examples ...


                if not hasattr(self, key) and key not in self.no_delegate:
                    setattr(self, key, getattr(mod, key))
        if ext:
            if query_ext:
                Executable.gino = property(self.query_executor)
            if schema_ext:
                SchemaItem.gino = property(self.schema_visitor)
                patch_schema(self)

    @property
    def Model(self):
        return self._model

    @property
    def bind(self):
        if self._bind is None:
            return _PlaceHolder(UninitializedError("Gino engine is not initialized."))
        return self._bind

    @bind.setter
    def bind(self, bind):
        self._bind = bind

    async def set_bind(self, bind, loop=None, **kwargs):
        if isinstance(bind, str):
            bind = make_url(bind)
        if isinstance(bind, URL):
            from . import create_engine

            bind = await create_engine(bind, loop=loop, bakery=self._bakery, **kwargs)
        self.bind = bind
        return bind

    def pop_bind(self):
        from .bakery import Bakery

        self._bakery = Bakery()
        bind, self.bind = self.bind, None
        return bind

    def with_bind(self, bind, loop=None, **kwargs):
        return _BindContext(self, bind, loop, kwargs)

    def __await__(self):
        async def init():
            await self.set_bind(self.bind)
            return self

        return init().__await__()



## ... source file continues with no further make_url examples...

Sponsored By

Sentry logo

Software errors are inevitable. Chaos is not. Try Sentry for free.


AssemblyAI logo

The most accurate speech-to-text API. Built for Python developers.

1. Introduction 2. Development Environments 3. Data 4. Web Development 5. Deployment 6. DevOps Changelog What Full Stack Means About the Author Future Directions Page Statuses SQLAlchemy ExtensionsSQLAlchemy Example CodeSQLAlchemy Modelssqlalchemy.databases mysqlsqlalchemy.dialects mssqlsqlalchemy.dialects mysqlsqlalchemy.dialects oraclesqlalchemy.schema DDLsqlalchemy.dialects postgresqlsqlalchemy.sql.expression Functionsqlalchemy.dialects sqlitesqlalchemy.dialects.mysql pymysqlsqlalchemy.dialects.postgresql ARRAYsqlalchemy.dialects.postgresql BIGINTsqlalchemy.dialects.postgresql BITsqlalchemy.dialects.postgresql DOUBLE_PRECISIONsqlalchemy.dialects.postgresql ExcludeConstraintsqlalchemy.dialects.postgresql INTEGERsqlalchemy.dialects.postgresql JSONsqlalchemy.dialects.postgresql TSVECTORsqlalchemy.dialects.postgresql pypostgresqlsqlalchemy.dialects.postgresql.base PGCompilersqlalchemy.dialects.postgresql.base PGIdentifierPreparersqlalchemy.dialects.postgresql.base PGTypeCompilersqlalchemy.dialects.postgresql.psycopg2 PGDialect_psycopg2sqlalchemy.dialects.sqlite pysqlitesqlalchemy.engine Connectionsqlalchemy.engine Enginesqlalchemy.engine create_enginesqlalchemy.engine defaultsqlalchemy.engine urlsqlalchemy.engine.default DefaultDialectsqlalchemy.engine.interfaces ExecutionContextsqlalchemy.engine.result ResultMetaDatasqlalchemy.engine.result RowProxysqlalchemy.engine.strategies EngineStrategysqlalchemy.engine.strategies MockEngineStrategysqlalchemy.engine.url make_urlsqlalchemy.events SchemaEventTargetsqlalchemy.exc ArgumentErrorsqlalchemy.exc DataErrorsqlalchemy.exc DatabaseErrorsqlalchemy.exc IntegrityErrorsqlalchemy.exc InvalidRequestErrorsqlalchemy.exc NoInspectionAvailablesqlalchemy.exc NoSuchTableErrorsqlalchemy.exc OperationalErrorsqlalchemy.exc ProgrammingErrorsqlalchemy.exc UnsupportedCompilationErrorsqlalchemy.ext compilersqlalchemy.ext.associationproxy AssociationProxysqlalchemy.ext.automap automap_basesqlalchemy.ext.compiler compilessqlalchemy.ext.declarative DeclarativeMetasqlalchemy.ext.declarative declarative_basesqlalchemy.ext.hybrid hybrid_methodsqlalchemy.ext.hybrid hybrid_propertysqlalchemy.ext.mutable Mutablesqlalchemy.inspection inspectsqlalchemy.orm ColumnPropertysqlalchemy.orm CompositePropertysqlalchemy.orm Loadsqlalchemy.orm Querysqlalchemy.orm RelationshipPropertysqlalchemy.orm SynonymPropertysqlalchemy.orm aliasedsqlalchemy.orm attributessqlalchemy.orm backrefsqlalchemy.orm class_mappersqlalchemy.orm column_propertysqlalchemy.orm compositesqlalchemy.orm interfacessqlalchemy.orm mappersqlalchemy.orm mapperlibsqlalchemy.orm object_mappersqlalchemy.orm object_sessionsqlalchemy.orm relationshipsqlalchemy.orm sessionsqlalchemy.orm sessionmakersqlalchemy.orm strategiessqlalchemy.orm.attributes InstrumentedAttributesqlalchemy.orm.attributes QueryableAttributesqlalchemy.orm.attributes flag_modifiedsqlalchemy.orm.collections InstrumentedListsqlalchemy.orm.exc NoResultFoundsqlalchemy.orm.exc UnmappedClassErrorsqlalchemy.orm.exc UnmappedInstanceErrorsqlalchemy.orm.interfaces MapperPropertysqlalchemy.orm.interfaces PropComparatorsqlalchemy.orm.mapper Mappersqlalchemy.orm.properties ColumnPropertysqlalchemy.orm.properties RelationshipPropertysqlalchemy.orm.query Querysqlalchemy.orm.query QueryContextsqlalchemy.orm.relationships RelationshipPropertysqlalchemy.orm.session Sessionsqlalchemy.orm.session object_sessionsqlalchemy.orm.util AliasedClasssqlalchemy.orm.util AliasedInspsqlalchemy.orm.util identity_keysqlalchemy.pool NullPoolsqlalchemy.pool StaticPoolsqlalchemy.schema CheckConstraintsqlalchemy.schema Columnsqlalchemy.schema CreateIndexsqlalchemy.schema CreateTablesqlalchemy.schema DDLElementsqlalchemy.schema ForeignKeysqlalchemy.schema ForeignKeyConstraintsqlalchemy.schema Indexsqlalchemy.schema PrimaryKeyConstraintsqlalchemy.schema Tablesqlalchemy.sql ClauseElementsqlalchemy.sql columnsqlalchemy.sql expressionsqlalchemy.sql extractsqlalchemy.sql functionssqlalchemy.sql operatorssqlalchemy.sql schemasqlalchemy.sql selectsqlalchemy.sql sqltypessqlalchemy.sql tablesqlalchemy.sql.compiler SQLCompilersqlalchemy.sql.elements ColumnElementsqlalchemy.sql.elements Labelsqlalchemy.sql.expression ClauseElementsqlalchemy.sql.expression ColumnClausesqlalchemy.sql.expression ColumnElementsqlalchemy.sql.expression Executablesqlalchemy.sql.expression FunctionElementsqlalchemy.sql.expression UnaryExpressionsqlalchemy.sql.functions FunctionElementsqlalchemy.sql.functions GenericFunctionsqlalchemy.sql.naming convsqlalchemy.sql.schema Columnsqlalchemy.sql.schema SchemaItemsqlalchemy.sql.sqltypes NullTypesqlalchemy.sql.util ClauseAdaptersqlalchemy.sql.visitors traversesqlalchemy.types Booleansqlalchemy.types Datesqlalchemy.types DateTimesqlalchemy.types Enumsqlalchemy.types Floatsqlalchemy.types Integersqlalchemy.types Intervalsqlalchemy.types NULLTYPEsqlalchemy.types Stringsqlalchemy.types Textsqlalchemy.types Timesqlalchemy.types TypeEnginesqlalchemy.types UserDefinedTypesqlalchemy.types to_instancesqlalchemy.util OrderedDictsqlalchemy.util OrderedSetsqlalchemy.util set_creation_ordersqlalchemy.util symbolsqlalchemy.util topologicalsqlalchemy.util.langhelpers public_factorysqlalchemy.util.langhelpers symbol ...or view the full table of contents.

Full Stack Python

Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.
Updates via Twitter & Facebook.

Matt Makai 2012-2020