在中使用正则表达式视图.py詹戈?

2024-10-17 06:21:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Django应用程序中有一个表单,其中一个字段名为url。用户可以添加youtube的url。 提交时,我只想保存视频id

我的视图.py像这样:

import re
def video_new(request):
    if request.user.is_authenticated():
        if request.method == "POST":
            form = VideoForm(request.POST)
            if form.is_valid():
                video = form.save(commit=False)
                fullURL = video.url
                youtubeId = re.sub(r'\shttps://www.youtube.com/watch?v=\s', '',fullURL)
                video.url = youtubeId
                video.created_by = request.user
                video.save()
            return redirect('videos:video_detail', video_id=video.pk)
        else:
            form = VideoForm()
    else:
        #if user isn't logged in
        return redirect('login')
    return render(request, 'videos/video_edit.html', {'form': form})

当我在控制台中输出youtubeId时,我实际上看到了完整的Url。在

所以我想我没用re.sub公司对的。 如何正确使用它?在


Tags: reformidurlreturnifyoutubeis
2条回答

您的模式中不需要前导和尾随\s。除此之外,YouTube的url不能用一种模式进行三层解析,因为对于https://youtu.be/...形式的每个url都有一个简短的形式。在

最好使用^{}解析url:

from urllib.parse import urlparse

def parse_youtube_url(url_str):
    parsed_url = urlparse(url_str)
    if parsed_url.netloc in ('www.youtube.com', 'youtu.be'):
        youtube_id = parsed_url.query.split('&')[0].split('=')[1]
    else:
        raise ValueError('Host is not youtube')
    return youtube_id

url = 'https://www.youtube.com/watch?v=dwyw7esd67'
print(parse_youtube_url(url))
# 'dwyw7esd67'

在python2中,您将使用from urlparse import urlparse。在

您可以使用此函数从复杂的youtube url获取id。在

来源:https://gist.github.com/kmonsoor/2a1afba4ee127cce50a0

def get_yt_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',
    """

    try:
        # python 3
        from urllib.parse import urlparse, parse_qs
    except ImportError:
        # python 2
        from urlparse import urlparse, parse_qs

    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

在你的情况下

^{pr2}$

相关问题 更多 >