python - Python(Django) - 将 URL 从帖子转换为嵌入的 YouTube IFrame
问题描述
基本上我想要实现的是在帖子中找到 URL,例如,如果我发布这个:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
https://www.youtube.com/watch?v=example
它将看起来像这样:Lorem ipsum dolor sit amet、consectetur adipiscing elit、sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。
模型.py:
from django.db import models
class NewsFeed_Articles(models.Model):
title = models.CharField(max_length = 120)
post = models.TextField()
date = models.DateTimeField()
def __str__(self):
return self.title
post.html:
{% extends "Feed/wrapper.html" %}
{% block content %}
<div class="card">
<h2 class="text-info">{{newsfeed_articles.title}}</h2>
<h6 class="text-info">{{newsfeed_articles.date|date:"d-m-Y в H:i:s"}}</h6>
<p>{{newsfeed_articles.post|safe|linebreaks}}<p>
<div class="fakeimg" style="height:200px;">Image</div>
</div>
{% endblock %}
解决方案
使用代码将 YouTube 网址转换为 YouTube 嵌入:
import re
def convert_ytframe(text):
_yt = re.compile(r'(https?://)?(www\.)?((youtu\.be/)|(youtube\.com/watch/?\?v=))([A-Za-z0-9-_]+)', re.I)
_frame_format = '<iframe width="560" height="315" src="https://www.youtube.com/embed/{0}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>'
def replace(match):
groups = match.groups()
return _frame_format.format(groups[5])
return _yt.sub(replace, text)
这是您可以自己测试的工作示例:repl.it/@themisir/AromaticAvariciousMarketing
此外,您可以在此处测试正则表达式:regex101.com/r/97yhSH/1
更新
代码被简化了。
import re
yt_link = re.compile(r'(https?://)?(www\.)?((youtu\.be/)|(youtube\.com/watch/?\?v=))([A-Za-z0-9-_]+)', re.I)
yt_embed = '<iframe width="560" height="315" src="https://www.youtube.com/embed/{0}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>'
def convert_ytframe(text):
return yt_link.sub(lambda match: yt_embed.format(match.groups()[5]), text)
推荐阅读
- python - 为什么 Python for 循环没有循环,里面有一个 while 循环
- c - 计算 e^x 给定 epsilon 和 c 中的 x 值
- react-native - MQTT vs MQTT over websocket 反应原生
- php - 一个月的几个星期
- python - 印尼笑的正则表达式模式 (wkwkwk)
- python - 如何为图像中的对象分别用不同的颜色着色
- node.js - 尝试通过 axios 发送带有另一个参数的 formData
- javascript - 如何控制台.log 下拉菜单中的属性?
- html - Html 视频背景不适用于 Ionic 框架上的 iOS
- kotlin-coroutines - 单元测试 Kotlin Flows 和 toList()