1. 程式人生 > 其它 >173/174-路飛14&15-課程詳情介面/前臺&區間過濾

173/174-路飛14&15-課程詳情介面/前臺&區間過濾

技術標籤:pythonDjangoVue

今日內容

1 課程詳情介面,課程章節介面

1 查詢所有課程介面
2 查詢單個課程介面
	-繼續再查詢所有介面上寫
    -再寫一個檢視類,單獨寫查詢課程詳情介面

4 寫課程章節介面,每個章節下有很多課程
	Linux從入門到精通
    	第一章節:入門
        	1 安裝環境
            2 配置環境
            3 放棄
         第二章節:入土
        	1 哇肯惡搞
            2 挖坑
    
    
    
    
   Python從入門到精通
    	第一章節:入門
        	1
安裝環境 2 配置環境 3 放棄 第二章節:入土 1 哇肯惡搞 2 挖坑

課程詳情介面

class CourseView(GenericViewSet, ListModelMixin,RetrieveModelMixin):
    queryset = Course.objects.filter(is_delete=False, is_show=True).order_by('-orders')
    serializer_class =CourseSerializer
    filter_backends =
[OrderingFilter,DjangoFilterBackend] ordering_fields = ['id', 'price', 'students'] filter_fields = ['course_category'] pagination_class =BasicPagination

課程章節介面(views.py)

class ChapterViewSet(GenericViewSet,ListModelMixin):
    queryset = CourseChapter.objects.filter(is_show=True,is_delete=
False).order_by('orders') serializer_class = CourseChapterSerializer # 加上過濾功能,按課程的id號來過濾 filter_backends = [DjangoFilterBackend] filter_fields = ['course']

序列化類

## 課時序列化類
class CourseSectionSerializer(serializers.ModelSerializer):
    class Meta:
        model = CourseSection
        fields='__all__'


# 課程章節序列化類
class CourseChapterSerializer(serializers.ModelSerializer):
    # 子序列化,課時是多條,一定要寫many=True
    coursesections=CourseSectionSerializer(many=True)
    class Meta:
        model = CourseChapter
        fields=['course','chapter','name','summary','pub_date','coursesections']

路由

router.register('chapters',ChapterViewSet,'ChapterViewSet')

2 課程詳情前臺

# 取路徑中的值
     mounted() {
                //http://localhost:8080/course/detail/79?name=lqz&age=18
                console.log(this.$route.params) //打印出{pk:79}
                console.log(this.$route.query)//打印出{name:lqz,age:18}
        },

3 七牛雲物件儲存託管視訊

1 視訊檔案,圖片檔案之前儲存在自己伺服器
2 搭建自己的儲存伺服器(fastdfs,go-fastdfs)
	-https://sjqzhang.github.io/go-fastdfs/usage.html#python
	-docekr 拉起一個來 http://10.1.5.9:8080/group1/upload
    import requests
    url = 'http://10.1.5.9:8080/group1/upload'
    files = {'file': open('report.xls', 'rb')}
    options={'output':'json','path':'','scene':''} #參閱瀏覽器上傳的選項
    r = requests.post(url,data=options, files=files)
    print(r.text)
    
3 第三方雲端儲存(阿里雲oss,七牛雲端儲存。。。。)
	七牛雲託管視訊(go語言的踐行者)
# from qiniu import Auth, put_file, etag
# import qiniu.config
# #需要填寫你的 Access Key 和 Secret Key
# access_key = '-BoMxfk8dxgDq87mA-qLkgmI_AHYfF27tOFan_NJ'
# secret_key = 'Wijh6Fg6gedtBqoqKElkxrrlySoiVWbFSfQ6I-qM'
# #構建鑑權物件
# q = Auth(access_key, secret_key)
# #要上傳的空間
# bucket_name = 'lqz'
# #上傳後儲存的檔名
# key = 'lqz.mp4'
# #生成上傳 Token,可以指定過期時間等
# token = q.upload_token(bucket_name, key, 3600)
# #要上傳檔案的本地路徑
# localfile = './6-測試功能.mp4'
# ret, info = put_file(token, key, localfile)
# print(info)
# assert ret['key'] == key
# assert ret['hash'] == etag(localfile)



# 刪除視訊
# from qiniu import Auth
# from qiniu import BucketManager
# access_key = '-BoMxfk8dxgDq87mA-qLkgmI_AHYfF27tOFan_NJ'
# secret_key = 'Wijh6Fg6gedtBqoqKElkxrrlySoiVWbFSfQ6I-qM'
# #初始化Auth狀態
# q = Auth(access_key, secret_key)
# #初始化BucketManager
# bucket = BucketManager(q)
# #你要測試的空間, 並且這個key在你空間中存在
# bucket_name = 'lqz'
# key = 'lqz.mp4'
# #刪除bucket_name 中的檔案 key
# ret, info = bucket.delete(bucket_name, key)
# print(info)

# import requests
#
#
# res=requests.get('https://vd3.bdstatic.com/mda-kkena9xzt4hmb7b7/sc/cae_h264_clips/1605430730/mda-kkena9xzt4hmb7b7.mp4?auth_key=1610529585-0-0-14a58ce4cca097b0a5c823cc506d95da&bcevod_channel=searchbox_feed&pd=1&pt=3&abtest=8656_1')
# with open('致命誘惑.mp4','wb') as f:
#     for line in res.iter_content():
#         f.write(line)






'''

通過該程式下載的視訊和音訊是分成連個檔案的,沒有合成,
視訊為:視訊名_video.mp4
音訊為:視訊名_audio.mp4
修改url的值,換成自己想下載的頁面節課
'''

# 匯入requests模組,模擬傳送請求
import requests
# 匯入json
import json
# 匯入re
import re

# 定義請求頭
headers = {
    'Accept': '*/*',
    'Accept-Language': 'en-US,en;q=0.5',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'
}


# 正則表示式,根據條件匹配出值
def my_match(text, pattern):
    match = re.search(pattern, text)
    print(match.group(1))
    print()
    return json.loads(match.group(1))


def download_video(old_video_url, video_url, audio_url, video_name):
    headers.update({"Referer": old_video_url})
    print("開始下載視訊:%s" % video_name)
    video_content = requests.get(video_url, headers=headers)
    print('%s視訊大小:' % video_name, video_content.headers['content-length'])
    audio_content = requests.get(audio_url, headers=headers)
    print('%s音訊大小:' % video_name, audio_content.headers['content-length'])
    # 下載視訊開始
    received_video = 0
    with open('%s_video.mp4' % video_name, 'ab') as output:
        while int(video_content.headers['content-length']) > received_video:
            headers['Range'] = 'bytes=' + str(received_video) + '-'
            response = requests.get(video_url, headers=headers)
            output.write(response.content)
            received_video += len(response.content)
    # 下載視訊結束
    # 下載音訊開始
    audio_content = requests.get(audio_url, headers=headers)
    received_audio = 0
    with open('%s_audio.mp4' % video_name, 'ab') as output:
        while int(audio_content.headers['content-length']) > received_audio:
            # 視訊分片下載
            headers['Range'] = 'bytes=' + str(received_audio) + '-'
            response = requests.get(audio_url, headers=headers)
            output.write(response.content)
            received_audio += len(response.content)
    # 下載音訊結束
    return video_name


if __name__ == '__main__':
    # 換成你要爬取的視訊地址
    url = 'https://www.bilibili.com/video/BV1TA411H7gQ'
    # 傳送請求,拿回資料
    res = requests.get(url, headers=headers)
    # 視訊詳情json
    playinfo = my_match(res.text, '__playinfo__=(.*?)</script><script>')
    # 視訊內容json
    initial_state = my_match(res.text, r'__INITIAL_STATE__=(.*?);\(function\(\)')
    # 視訊分多種格式,直接取解析度最高的視訊 1080p
    video_url = playinfo['data']['dash']['video'][0]['baseUrl']
    # 取出音訊地址
    audio_url = playinfo['data']['dash']['audio'][0]['baseUrl']
    video_name = initial_state['videoData']['title']
    print('視訊名字為:video_name')
    print('視訊地址為:', video_url)
    print('音訊地址為:', audio_url)
    download_video(url, video_url, audio_url, video_name)

4 區間過濾

1 查詢課程價格大於30小於90的課程
http://127.0.0.1:8000/course/free/?price_ge=30&price_lt=90
2 寫一個過濾類,配置在檢視類中
filter_backends = [SearchByPrice]




 3 通過擴寫django-filter來實現該功能