def _to_dsn(hosts):
    """Convert a host URI into a dsn for aiopg.

    >>> _to_dsn('aiopg://myhostname:4242/mydb')
    'postgres://crate@myhostname:4242/mydb'

    >>> _to_dsn('aiopg://myhostname:4242')
    'postgres://crate@myhostname:4242/doc'

    >>> _to_dsn('aiopg://hoschi:pw@myhostname:4242/doc?sslmode=require')
    'postgres://hoschi:pw@myhostname:4242/doc?sslmode=require'

    >>> _to_dsn('aiopg://myhostname')
    'postgres://crate@myhostname:5432/doc'
    """
    p = urlparse(hosts)
    try:
        user_and_pw, netloc = p.netloc.split('@', maxsplit=1)
    except ValueError:
        netloc = p.netloc
        user_and_pw = 'crate'
    try:
        host, port = netloc.split(':', maxsplit=1)
    except ValueError:
        host = netloc
        port = 5432
    dbname = p.path[1:] if p.path else 'doc'
    dsn = f'postgres://{user_and_pw}@{host}:{port}/{dbname}'
    if p.query:
        dsn += '?' + '&'.join(k + '=' + v[0] for k, v in parse_qs(p.query).items())
    return dsn
Convert a host URI into a dsn for aiopg.

    >>> _to_dsn('aiopg://myhostname:4242/mydb')
    'postgres://crate@myhostname:4242/mydb'

    >>> _to_dsn('aiopg://myhostname:4242')
    'postgres://crate@myhostname:4242/doc'

    >>> _to_dsn('aiopg://hoschi:pw@myhostname:4242/doc?sslmode=require')
    'postgres://hoschi:pw@myhostname:4242/doc?sslmode=require'

    >>> _to_dsn('aiopg://myhostname')
    'postgres://crate@myhostname:5432/doc'