Skip to content

Instantly share code, notes, and snippets.

@mcchae
Created April 15, 2015 01:20
Show Gist options
  • Save mcchae/47d1e2ad707ae6a74991 to your computer and use it in GitHub Desktop.
Save mcchae/47d1e2ad707ae6a74991 to your computer and use it in GitHub Desktop.
Flask File Upload
##########################################################################################
import os
import sys
import json
import unittest
import pprint
import httplib
import urllib
import datetime
import random
import string
##########################################################################################
def encode_for_upload (file_path, fields=[]):
BOUNDARY = '----------boundary----------'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="file"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
##########################################################################################
def get_info():
info = {
'version' : '7.59425',
'desc': '20150210 설명 정보',
'filename' : '/tmp/v20150226.tgz',
}
return info
##########################################################################################
def uploadFile(filename, info, host='localhost', port=5001):
#=====================================================================================
if not os.path.exists(filename):
raise IOError('Cannot open for file <%s>' % filename)
fields = (('info', str(info)),)
content_type, body = encode_for_upload(filename, fields=fields)
headers = { 'Content-Type': content_type }
conn = httplib.HTTPSConnection(host=host, port=port)
conn.request('POST', '/api/Upload', body, headers)
response = conn.getresponse()
# print response.status, response.reason
data = response.read()
conn.close()
rdict = json.loads(data)
return rdict
##########################################################################################
if __name__ == '__main__':
s_ts = datetime.datetime.now()
filename = '/tmp/v20150226.tgz'
info = get_info()
r = uploadVaccine(filename, vaccine_info, TU.host, TU.port)
_r = r['result']
e_ts = datetime.datetime.now()
print 'result of upload=<%s> takes [%s]' % (_r, e_ts-s_ts)
##########################################################################################
import os
import datetime
import traceback
import time
import pprint
import random
from flask import Flask, request
from flask.ext.restful import reqparse, abort, Api, Resource
##########################################################################################
def set_Info(info):
print 'type(info)=<%s>' % str(type(info))
print 'info=%s' % pprint.pformat(info)
return True
##########################################################################################
class Upload(Resource):
#=====================================================================================
@staticmethod
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ('tgz','tar.gz')
#=====================================================================================
def post(self):
try:
file = request.files['file']
if file and self.allowed_file(file.filename):
filename = os.path.basename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
info = eval(request.form['info'].encode('utf-8'))
rd = {
'result':set_Info(info)
}
return rd
except Exception, e:
rd = {
'result':False
}
return rd
##########################################################################################
if __name__ == '__main__':
host = '127.0.0.1'
port = 5001
g_config.logger.info("Start RestAPI : listen %s:%s" % (host, port))
app = Flask(__name__)
# for upload setting
UPLOAD_FOLDER = '/tmp/upload'
if not os.path.isdir(UPLOAD_FOLDER):
os.mkdir(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
api = Api(app)
## Actually setup the Api resource routing here
api.add_resource(UploadVaccine, '/api/Upload')
from OpenSSL import SSL
context = SSL.Context(SSL.SSLv3_METHOD)## SSL.Context(SSL.SSLv23_METHOD)
cert = '/opt/my.crt'
pkey = '/opt/my.key'
context.use_privatekey_file(pkey)
context.use_certificate_file(cert)
app.run(host=host, port=port, ssl_context=(cert, pkey), threaded=True, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment