Login

templatetags - get youtube video id

Author:
agusmakmun
Posted:
December 29, 2017
Language:
Python
Version:
Not specified
Tags:
django templatetags youtube
Score:
1 (after 1 ratings)

Returns Video_ID extracting from the given url of Youtube.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from django import template

register = template.Library()

@register.filter
def get_youtube_video_id(url):
    """
    Returns Video_ID extracting from the given url of Youtube
    Examples of URLs:
      Valid:
        'http://youtu.be/_lOT2p_FCvA',
        'www.youtube.com/watch?v=_lOT2p_FCvA&feature=feedu',
        'http://www.youtube.com/embed/_lOT2p_FCvA',
        'http://www.youtube.com/v/_lOT2p_FCvA?version=3&hl=en_US',
        'https://www.youtube.com/watch?v=rTHlyTphWP0&index=6&list=PLjeDyYvG6-40qawYNR4juzvSOg-ezZ2a6',
        'youtube.com/watch?v=_lOT2p_FCvA',
        'https://www.youtube.com/watch?v=S6q41Rfltsk'
      Invalid:
        'youtu.be/watch?v=_lOT2p_FCvA'
    usage:
        {{ youtube_url|get_youtube_video_id }}
    Source: https://gist.github.com/kmonsoor/2a1afba4ee127cce50a0
    """
    if url.startswith(('youtu', 'www')):
        url = 'http://' + url

    query = urlparse(url)

    if 'youtube' in query.hostname:
        if query.path == '/watch':
            return parse_qs(query.query)['v'][0]
        elif query.path.startswith(('/embed/', '/v/')):
            return query.path.split('/')[2]
    elif 'youtu.be' in query.hostname:
        return query.path[1:]
    else:
        raise ValueError

More like this

Comments

Please login first before commenting.