1.需求:支持视频上传并切片,支持通过m3u8文件播放

2.视频切片的上一节已经谈过,这一节主要是视频上传的处理

第一步:upload-module模块安装

-----------首先下载upload-module

-----------然后使用源码编译安装nginx: .configure --add-module=/path/nginx-upload-module/

第二步:确认是否已经安装了upload-module,使用指令:/usr/local/nginx/sbin/nginx -V

第三部:添加配置文件

http {
include mime.types;
default_type application/octet-stream;
client_max_body_size 3000m;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 256k;
fastcgi_buffers 2 256k;
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; add_header Access-Control-Allow-Origin "http://weibo.duoyioa.com";
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS; sendfile on;
#tcp_nopush on; #keepalive_timeout 0;
keepalive_timeout 300; #gzip on; server {
client_max_body_size 3000m;
client_body_buffer_size 400m;
listen 80;
listen 443 ssl; ssl_certificate /usr/local/nginx/ssl/duoyioa.cer;
ssl_certificate_key /usr/local/nginx/ssl/duoyioa.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on; # Upload form should be submitted to this location
location /upload {
# Pass altered request body to this location
upload_pass @python; # Store files to this directory
# The directory is hashed, subdirectories 0 1 2 3 4 5 6 7 8 9 should exist
upload_store /var 1; # Allow uploaded files to be read only by user
upload_store_access user:rw; # Set specified fields in request body
upload_set_form_field $upload_field_name.name "$upload_file_name";
upload_set_form_field $upload_field_name.content_type "$upload_content_type";
upload_set_form_field $upload_field_name.path "$upload_tmp_path"; # Inform backend about hash and size of a file
upload_aggregate_form_field "$upload_field_name.md5" "$upload_file_md5";
upload_aggregate_form_field "$upload_field_name.size" "$upload_file_size"; upload_pass_form_field "^submit$|^description$"; upload_cleanup 400 404 499 500-505;
upload_limit_rate 0;
upload_max_file_size 3000m;
client_max_body_size 3000m;
} error_page 405 =200 @405;
location @405 {
return 200;
} # Pass altered request body to a backend
location @python {
proxy_read_timeout 3000;
proxy_connect_timeout 3000;
proxy_pass http://121.201.116.242:9999;
#return 200;
} location /hls {
types {
application/vnd.apple.mpegurl m3u8;
video/mp2t ts;
video/mp4 f4p f4v m4v mp4;
image/bmp bmp;
image/gif gif;
image/jpeg jpeg jpg;
image/png png;
image/svg+xml svg svgz;
image/tiff tif tiff;
image/vnd.wap.wbmp wbmp;
image/webp webp;
image/x-jng jng;
}
root /var;
add_header Cache-Control no-cache;
add_header Access-Control-Allow-Origin *;
}
}
}

第四步:搭建python后台站点

主要的处理代码如下(有一些是业务处理代码,大体看upload就ok):

# -*- coding: utf-8 -*-
import os
import json
import uuid
import threading
import thread_manager
import datetime
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from logging_manager import single_logger
import logging
import traceback UPLOAD_FILE_PATH = '/var/hls/video/'
ADDVIDEO_WEIBO_URL = "http://10.32.64.194:8233/api/Video/Insert"
UPDATE_WEIBO_JSONDATA = "http://10.32.64.194:8233/api/Video/UpdateJsonData"
VERIFY_VIDEO_TOKEN = 'http://10.32.64.194:8233/api/NoLogin/VerifyVideoToken'
THREAD_MANAGER = thread_manager.Thread_Pool(8) @csrf_exempt
def upload(request):
try:
if verify_to_weibo(request.META['QUERY_STRING']) == False:#权限验证
content = json.dumps({
'message' : 'You have no authority',
'code' : 96
})
response = HttpResponse(content, content_type='application/json; charset=utf-8')
single_logger.info('非法的调用:%s' % request.META['QUERY_STRING'])
return response request_params = request.POST
file_name = request_params['file.name']
file_content_type = request_params['file.content_type']
file_path = request_params['file.path']
file_size = request_params['file.size']
# save file to tmp
today_str = datetime.date.today().strftime("%Y-%m-%d")
new_file_name = str(uuid.uuid1())
dir = '%s/%s' % (UPLOAD_FILE_PATH, today_str)
isExists = os.path.exists(dir)
if not isExists:
os.makedirs(dir)
new_file_path = ''.join([UPLOAD_FILE_PATH, '%s/' % today_str, new_file_name, os.path.splitext(file_name)[-1]])
with open(new_file_path, 'a') as new_file:
with open(file_path, 'rb') as f:
new_file.write(f.read()) orignUrl = ''.join(['/hls/video/', '%s/' % today_str, new_file_name, os.path.splitext(file_name)[-1]])#没切片之前的播放地址
coverImgUrl = ''.join(['/hls/video/', '%s/' % today_str, new_file_name, '.jpg'])#封面图片下载地址
coverImgPath = ''.join(['/var/hls/video/', '%s/' % today_str, new_file_name, '.jpg'])#封面图片存储地址
playTime = getFileTimes(new_file_path)#视频的播放时长
return_data = json.loads(addVideoToWeibo(orignUrl, coverImgUrl, file_name.split('.')[-1], file_size, new_file_path, playTime)) mdu3 = os.system('sh /home/test/plugflow.sh %s' % new_file_name)
content = json.dumps({
'content_type': file_content_type,
'orignUrl': orignUrl,
'size': file_size,
'playTime': playTime,
'guid': return_data['data']['videoData']['guid'],
'mdu3': '',
'coverImgUrl' : coverImgUrl,
'code' : 0
})
response = HttpResponse(content, content_type='application/json; charset=utf-8')
os.system('ffmpeg -i %s -y -f image2 -ss 1 -vframes 1 %s' % (new_file_path, coverImgPath))
THREAD_MANAGER.add_work(function=cutVideo, param=(new_file_name, return_data['data']['videoData']['guid'], '/hls/video/%s/index.m3u8' % new_file_name))
return response
except BaseException as e:
msg = traceback.format_exc()
single_logger.error(msg)
content = json.dumps({
'message' : 'internal error',
'code' : 91
})
response = HttpResponse(content, content_type='application/json; charset=utf-8')
return response def verify_to_weibo(request_params):
email, token = ('', '')
import urllib
import urllib2
for parm in request_params.split('&'):
if 'email' in parm:
email = parm.split('=')[-1].strip()
if 'token' in parm:
token = parm.split('=')[-1].strip()
values = {"email":email,"token":token}
data = urllib.urlencode(values)
request = urllib2.Request( '%s?%s' % (VERIFY_VIDEO_TOKEN, data))
response = urllib2.urlopen(request)
return_data = json.loads(response.read())
return return_data["data"]["correct"] def getFileTimes(filename):
from moviepy.editor import VideoFileClip
clip = VideoFileClip(filename)
return int(clip.duration) #把视频相关数据添加到文件表中
def addVideoToWeibo(orignUrl, coverImgUrl, format, length, path, playTime):
import urllib
import urllib2
values = {"orignUrl":orignUrl,"coverImgUrl":coverImgUrl,"format":format,"length":length,"path":path,"playTime":playTime}
data = urllib.urlencode(values)
request = urllib2.Request(ADDVIDEO_WEIBO_URL, data)
response = urllib2.urlopen(request)
return response.read() #视频切片
def cutVideo((fileName, guid, m3u8Url)):
today_str = datetime.date.today().strftime("%Y-%m-%d")
os.system('sh /home/test/plugflow.sh %s %s' % (today_str, fileName))
if os.path.exists('/var%s' % m3u8Url):
updateVideoToWeibo(guid, m3u8Url) #把切片好的视频地址更新到视频的文件表
def updateVideoToWeibo(guid, m3u8Url):
import urllib
import urllib2
values = {"guid":guid, "m3u8Url":m3u8Url}
data = urllib.urlencode(values)
request = urllib2.Request(UPDATE_WEIBO_JSONDATA, data)
response = urllib2.urlopen(request)
return response.read() '''def timeConvert(size):# 单位换算
M, H = 60, 60**2
if size < M:
return str(size)+'S'
if size < H:
return '%sM%sS'%(int(size/M),int(size%M))
else:
hour = int(size/H)
mine = int(size%H/M)
second = int(size%H%M)
tim_srt = '%sH%sM%sS'%(hour,mine,second)
return tim_srt
'''

11.nginx upload module + python django 后台 实现视频上传与切片的更多相关文章

  1. python django web 端文件上传

    利用Django实现文件上传并且保存到指定路径下,其实并不困难,完全不需要用到django的forms,也不需要django的models,就可以实现,下面开始实现. 第一步:在模板文件中,创建一个f ...

  2. django后台处理前端上传和显示图片

      1:项目根目录存放图片的目录 2:settings.py  添加 MEDIA_ROOT = os.path.join(BASE_DIR, "media") 3:url.py 添 ...

  3. 转:使用 Nginx Upload Module 实现上传文件功能

    普通网站在实现文件上传功能的时候,一般是使用Python,Java等后端程序实现,比较麻烦.Nginx有一个Upload模块,可以非常简单的实现文件上传功能.此模块的原理是先把用户上传的文件保存到临时 ...

  4. Nginx Upload Module 上传模块

    传统站点在处理文件上传请求时,普遍使用后端编程语言处理,如:Java.PHP.Python.Ruby等.今天给大家介绍Nginx的一个模块,Upload Module上传模块,此模块的原理是先把用户上 ...

  5. nginx上传模块—nginx upload module-

    一. nginx upload module原理 官方文档: http://www.grid.net.ru/nginx/upload.en.html Nginx upload module通过ngin ...

  6. 用nginx代理请求,django后台静态文件找不到的问题

    使用谷歌开发者工具,查看静态文件的地址,把相应的地址配置到nginx中 默认的django后台静态文件的路径是 /usr/local/lib/python3.6/site-packages/djang ...

  7. nginx upload module的使用

    现在的网站,总会有一点与用户交互的功能,例如允许用户上传头像,上传照片,上传附件这类的.PHP写的程序,对于上传文件效率不是很高.幸好,nginx有一个名为upload的module可以解决这个问题. ...

  8. 前台利用jcrop做头像选择预览,后台通过django利用Uploadify组件上传图最终使用PIL做图像裁切

    之前一直使用python的PIL自定义裁切图片,今天有需求需要做一个前端的选择预览页面,索性就把这个功能整理一下,分享给大家. 实现思路: 1.前端页面: 用户选择本地一张图片,然后通过鼠标缩放和移动 ...

  9. django中图片的上传和显示

    上传图片实际上是 把图片存在服务器的硬盘中,将图片存储的路径存在数据库中. 1 首先要配置文件上传的路径: 1.1 建立静态文件目录 在项目根目录下 新建一个 static文件夹,下面再建立一个med ...

随机推荐

  1. SGU 520 Fire in the Country(博弈+搜索)

    Description This summer's heat wave and drought unleashed devastating wildfires all across the Earth ...

  2. js经典试题之运算符的优先级

    js经典试题之运算符 1.假设val已经声明,可定义为任何值.则下面js代码有可能输出的结果为: console.log('Value is ' + (val != '0') ? 'define' : ...

  3. 《软件工程实践》第五次作业-WordCount进阶需求 (结对第二次)

    在文章开头给出结对同学的博客链接.本作业博客的链接.你所Fork的同名仓库的Github项目地址 本作业博客链接 github pair c 031602136魏璐炜博客 031602139徐明盛博客 ...

  4. 使用Quartz.Net同时执行多个任务

    在Quartz.Net中可能我们需要在某一时刻执行多个任务操作,而又不想创建多个任务.Quartz.Net为我们提供了多个ScheduleJob的重载来实现多个一次执行多个任务. // 创建一个组任务 ...

  5. HDU 2115 I Love This Game

    http://acm.hdu.edu.cn/showproblem.php?pid=2115 Problem Description Do you like playing basketball ? ...

  6. C++ 普通函数和虚函数调用的区别

    引出:写个类A,声明类A指针指向NULL,调用类A的方法会有什么后果,编译通过吗,运行会通过吗? #include<stdio.h> #include<iostream> us ...

  7. Jenkins系列-Jenkins忘记密码的修复方法

    找回 admin 用户的密码后,可以登录系统修改其他用户的密码. 1. Jenkins 目录结构 Jenkins 没有使用数据库,所有的信息都保存在 JENKINS_HOME 目录下的文件中.其中 J ...

  8. TreeView的使用

    用于显示多级层次关系 每一项是一个节点,也就是一个Node,是一个TreeNode节点,Nodes是该控件节点的集合. selectedNode用户选中的节点,如果没有选中则为null 1. 当选中后 ...

  9. FastReport.net 常用方法

    一.页面设置 情景:FastReport设计器页面默认设置为A4纸,但如果需要显示的字段过多,这时就出现了页面的大小无法满足完整显示所需内容的问题. 解决:出现这个问题后,我们可以在来到"文 ...

  10. matlab exist函数

    函数作用:用于确定某变量或值是否存在. 调用格式: exist主要有两种形式,一个参数和两个参数的,作用都是用于确定某值是否存在:1. b = exist( a) 若 a 存在,则 b = 1: 否则 ...