<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def _to_dsn(hosts):
 """Convert a host URI into a dsn for aiopg. 'postgres://crate@myhostname:4242/mydb' 'postgres://crate@myhostname:4242/doc' 'postgres://hoschi:pw@myhostname:4242/doc?sslmode=require' '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