コード例 #1
0
ファイル: views.py プロジェクト: reberhardt7/hcc-photo-upload
def upload(request):
    if request.content_length/1000000 > 20:
        return error_response(400, 'Sorry, but the file must be under 20MB.')

    # Create photo object in database
    photo = Photo(datetime.today(), request.POST['file'].filename, request.client_addr, request.content_type, request.content_length)
    DBSession.add(photo)
    DBSession.flush()

    # Save uploaded file
    input_file = request.POST['file'].file
    input_file.seek(0)
    if not os.path.exists('data'):
        os.makedirs('data')
    if not os.path.exists('data/uploads'):
        os.makedirs('data/uploads')
    upload_path = os.path.join('data', 'uploads', str(photo.id))
    with open(upload_path, 'w') as f:
        shutil.copyfileobj(input_file, f)

    # Check the content type and rename as appropriate
    mime = magic.from_file(upload_path, mime=True)
    if mime not in ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/tiff', 'image/x-tiff']:
        resp = Response('Sorry, but we can only accept jpg, gif, or png files.')
        resp.status_code = 400
        resp.status_string = '400 Bad Request'
        return resp
    extension = {'image/jpeg': '.jpg', 'image/pjpeg': '.jpg',
                 'image/gif': '.gif', 'image/png': '.png',
                 'image/tiff': '.tiff', 'image/x-tiff': '.tiff'}[mime]
    os.rename(upload_path, upload_path + extension)
    photo.content_type = mime

    return Response('OK')
コード例 #2
0
ファイル: views.py プロジェクト: reberhardt7/hcc-photo-upload
def error_response(code, msg):
    status = {400: '400 Bad Request', 500: '500 Internal Server Error'}[code]
    resp = Response(msg)
    resp.status_code = code
    resp.status_string = status
    return resp