Python dj_database_url.parse() Examples

The following are 10 code examples of dj_database_url.parse(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module dj_database_url , or try the search function .
Example #1
Source File: fabfile.py    From django-template with MIT License 5 votes vote down vote up
def dump_db(self, destination):
        """
        Dump the database to the given directory and return the path to the file created.
        This creates a gzipped SQL file.
        """
        with self.cd(self.project_root):
            env_file = os.path.join(self.envdir_path, "DATABASE_URL")
            db_credentials = self.run("cat " + env_file, hide=True).stdout.strip()

        db_credentials_dict = dj_database_url.parse(db_credentials)

        if not is_supported_db_engine(db_credentials_dict["ENGINE"]):
            raise NotImplementedError(
                "The dump_db task doesn't support the remote database engine"
            )

        outfile = os.path.join(
            destination, datetime.now().strftime("%Y-%m-%d_%H%M%S.sql.gz")
        )

        self.run(
            "pg_dump -O -x -h '{host}' -U '{user}' '{db}'|gzip > {outfile}".format(
                host=db_credentials_dict["HOST"],
                user=db_credentials_dict["USER"],
                db=db_credentials_dict["NAME"],
                outfile=outfile,
            ),
            env={"PGPASSWORD": db_credentials_dict["PASSWORD"].replace("$", "\$")},
        )

        return outfile 
Example #2
Source File: __init__.py    From environs with MIT License 5 votes vote down vote up
def _dj_db_url_parser(value: str, **kwargs) -> dict:
    try:
        import dj_database_url
    except ImportError as error:
        raise RuntimeError(
            "The dj_db_url parser requires the dj-database-url package. "
            "You can install it with: pip install dj-database-url"
        ) from error
    return dj_database_url.parse(value, **kwargs) 
Example #3
Source File: __init__.py    From environs with MIT License 5 votes vote down vote up
def _dj_email_url_parser(value: str, **kwargs) -> dict:
    try:
        import dj_email_url
    except ImportError as error:
        raise RuntimeError(
            "The dj_email_url parser requires the dj-email-url package. "
            "You can install it with: pip install dj-email-url"
        ) from error
    return dj_email_url.parse(value, **kwargs) 
Example #4
Source File: __init__.py    From environs with MIT License 5 votes vote down vote up
def _dj_cache_url_parser(value: str, **kwargs) -> dict:
    try:
        import django_cache_url
    except ImportError as error:
        raise RuntimeError(
            "The dj_cache_url parser requires the django-cache-url package. "
            "You can install it with: pip install django-cache-url"
        ) from error
    return django_cache_url.parse(value, **kwargs) 
Example #5
Source File: test_environs.py    From environs with MIT License 5 votes vote down vote up
def test_url_cast(self, set_env, env):
        set_env({"URL": "http://stevenloria.com/projects/?foo=42"})
        res = env.url("URL")
        assert isinstance(res, urllib.parse.ParseResult) 
Example #6
Source File: test_environs.py    From environs with MIT License 5 votes vote down vote up
def test_dj_db_url(self, env, set_env):
        db_url = "postgresql://localhost:5432/mydb"
        set_env({"DATABASE_URL": db_url})
        res = env.dj_db_url("DATABASE_URL")
        assert res == dj_database_url.parse(db_url) 
Example #7
Source File: test_environs.py    From environs with MIT License 5 votes vote down vote up
def test_dj_email_url(self, env, set_env):
        email_url = "smtp://user@domain.com:pass@smtp.example.com:465/?ssl=True"
        set_env({"EMAIL_URL": email_url})
        res = env.dj_email_url("EMAIL_URL")
        assert res == dj_email_url.parse(email_url) 
Example #8
Source File: test_environs.py    From environs with MIT License 5 votes vote down vote up
def test_dj_cache_url(self, env, set_env):
        cache_url = "redis://redis:6379/0"
        set_env({"CACHE_URL": cache_url})
        res = env.dj_cache_url("CACHE_URL")
        assert res == django_cache_url.parse(cache_url) 
Example #9
Source File: fabfile.py    From django-template with MIT License 4 votes vote down vote up
def import_db(c, dump_file=None):
    """
    Restore the given database dump.

    The dump must be a gzipped SQL dump. If the dump_file parameter is not set,
    the database will be dumped and retrieved from the remote host.
    """
    db_credentials = os.environ.get("DATABASE_URL")
    if not db_credentials:
        with open("envdir/DATABASE_URL", "r") as db_credentials_file:
            db_credentials = db_credentials_file.read()
    db_credentials_dict = dj_database_url.parse(db_credentials)

    if not is_supported_db_engine(db_credentials_dict["ENGINE"]):
        raise NotImplementedError(
            "The import_db task doesn't support your database engine"
        )

    if dump_file is None:
        dump_file = fetch_db(c)

    pg_opts_mapping = {
        "-h": db_credentials_dict["HOST"],
        "-U": db_credentials_dict["USER"],
    }
    pg_opts = " ".join(
        [f"{option} '{value}'" for option, value in pg_opts_mapping.items() if value]
    )
    db_name = db_credentials_dict["NAME"]
    db_info = {"pg_opts": pg_opts, "db": db_name}

    env = {"PGPASSWORD": db_credentials_dict["PASSWORD"].replace("$", "\\$")}
    close_sessions_command = """
        psql {pg_opts} template1 -c "
            SELECT pg_terminate_backend(pg_stat_activity.pid)
            FROM pg_stat_activity
            WHERE pg_stat_activity.datname = '{db}' AND pid != pg_backend_pid();
        "
    """.strip()
    c.run(close_sessions_command.format(**db_info), env=env, hide="out")
    c.run("dropdb {pg_opts} '{db}'".format(**db_info), env=env)
    c.run("createdb {pg_opts} '{db}'".format(**db_info), env=env)
    c.run(
        "gunzip -c {db_dump}|psql {pg_opts} '{db}'".format(
            db_dump=dump_file, **db_info
        ),
        env=env,
        hide="out",
    ) 
Example #10
Source File: fabfile.py    From django-template with MIT License 4 votes vote down vote up
def push_code_update(c, git_ref):
    """
    Synchronize the remote code repository
    """
    with c.conn.cd(c.conn.project_root):
        # First, check that the remote deployment directory exists
        try:
            c.conn.run("test -d .", hide=True)
        except UnexpectedExit:
            raise Exit(
                "Provisioning not finished, directory {} doesn't exist!".format(
                    c.config["root"]
                )
            )
        # Now make sure there's git, and a git repository
        try:
            c.conn.git("--version", hide=True)
        except UnexpectedExit:
            raise Exit("Provisioning not finished, git not available!")

        try:
            c.conn.git("rev-parse --git-dir", hide=True)
        except UnexpectedExit:
            c.conn.git("init")

    git_remote_url = "ssh://{user}@{host}:{port}/{directory}".format(
        user=c.conn.user,
        host=c.conn.host,
        port=c.conn.port,
        directory=c.conn.project_root,
    )
    # Delete the FABHEAD branch
    with c.conn.cd(c.conn.project_root):
        try:
            c.conn.git("branch -D FABHEAD", hide=True)
        except UnexpectedExit:
            pass
        c.conn.git("checkout -f -B FABHEAD master", hide=True)

        # Now push our code to the remote, always as FABHEAD branch
        porcelain.push(".", git_remote_url, "{}:FABHEAD".format(git_ref), force=True)
        c.conn.git("checkout -f -B master FABHEAD", hide=True)
        c.conn.git("submodule update --init", hide=True)