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. 使用Python进行AES加密和解密

    摘录于:http://blog.csdn.net/nurke/article/details/77267081 另外参考:http://www.cnblogs.com/kaituorensheng/p ...

  2. Python为什么会打印两个\

    在Python里面,如果\后面不是一个合法的转移字符,那么,Python会打印两个\,换句话说,Python将\也当成普通字符看待,而不是转义符的标志: >>>S = 'C:\py\ ...

  3. sql update limit1

    更新限制:为了避免全表更新,错误更新影响太多,加上limit1 多了一层保障.

  4. Ubuntu 基础操作 基础命令 热键 man手册使用 关机 重启等命令使用

    . : 关机, 如果将Linux默认运行等级设置为0, 系统将无法启动; -- : 多用户模式, 允许使用网络文件系统, 一般不使用图形界面登陆就是这种模式; -- : 多用户图形界面模式, 该模式下 ...

  5. 【IdentityServer4文档】- 打包和构建

    打包和构建 IdentityServer 由多个 nuget 软件包组成的. IdentityServer4 nuget | github 包含 IdentityServer 核心对象模型,服务和中间 ...

  6. lintcode-36-翻转链表 II

    36-翻转链表 II 翻转链表中第m个节点到第n个节点的部分 注意事项 m,n满足1 ≤ m ≤ n ≤ 链表长度 样例 给出链表1->2->3->4->5->null, ...

  7. xpath教程二 ---- 通过ID和Class检索

    必备知识点 在html中,id是唯一的 在html中,class是可以多处引用的 工具 Python3版本 lxml库[优点是解析快] HTML代码块[从网络中获取或者自己杜撰一个] requests ...

  8. 【bzoj4922】[Lydsy六月月赛]Karp-de-Chant Number 贪心+背包dp

    题目描述 给出 $n$ 个括号序列,从中选出任意个并将它们按照任意顺序连接起来,求以这种方式得到匹配括号序列的最大长度. 输入 第一行包含一个正整数n(1<=n<=300),表示括号序列的 ...

  9. NetScaler + Wireshark = A Perfect Combination!

    NetScaler + Wireshark = A Perfect Combination! https://www.citrix.com/blogs/2014/05/03/netscaler-wir ...

  10. (转)Ubuntu 12.04 LTS安装VMware Tools实现linux和window 互相复制:无法找到kernel header path的问题

    Ubuntu 12.04 LTS安装VMware Tools无法找到kernel header path的问题   ubuntuvmware Ubuntu 12.04 安装 VMware Tools, ...