def upload_view(): res = dict(code=-1, msg=None) logger.debug(request.files) f = request.files.get('file') if f and allowed_file(f.filename): filename = secure_filename(gen_rnd_filename() + "." + f.filename.split('.')[-1]) #随机命名 basedir = Upyun['basedir'] if Upyun['basedir'].startswith( '/') else "/" + Upyun['basedir'] imgUrl = os.path.join(basedir, filename) try: upres = api.put(imgUrl, f.stream.read()) except Exception, e: logger.error(e, exc_info=True) res.update(code=2, msg="Storage failure") else: imgId = md5(filename) imgUrl = Upyun['dn'].strip("/") + imgUrl upres.update(ctime=get_current_timestamp(), imgUrl=imgUrl, imgId=imgId) try: pipe = g.redis.pipeline() pipe.sadd(picKey, imgId) pipe.hmset("{}:{}".format(GLOBAL['ProcessName'], imgId), upres) pipe.execute() except Exception, e: logger.error(e, exc_info=True) res.update( code=0, msg= "It has been uploaded, but the server has encountered an unknown error" ) else:
def useruploadpub(): # 通过表单形式上传图片 res = dict(code=1, msg=None) logger.debug(request.files) f = request.files.get('file') callableAction = request.args.get("callableAction") if f and allowed_file(f.filename): filename = gen_rnd_filename() + "." + secure_filename( f.filename).split('.')[-1] # 随机命名 # 判断是否上传到又拍云还是保存到本地 if Upyun['enable'] in ('true', 'True', True): basedir = Upyun['basedir'] if Upyun['basedir'].startswith( '/') else "/" + Upyun['basedir'] imgUrl = os.path.join(basedir, filename) try: # 又拍云存储封装接口 UploadImage2Upyun(imgUrl, f.stream.read()) except Exception, e: logger.error(e, exc_info=True) res.update(code=2, msg="System is abnormal") else: imgUrl = Upyun['dn'].strip("/") + imgUrl res.update(data=dict(src=imgUrl), code=0) else: if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) f.save(os.path.join(UPLOAD_FOLDER, filename)) imgUrl = request.url_root + IMAGE_FOLDER + filename res.update(data=dict(src=imgUrl), code=0)
def test_utils(self): self.assertEqual("900150983cd24fb0d6963f7d28e17f72", md5("abc")) self.assertEqual("a9993e364706816aba3e25717850c26c9cd0d89d", sha1("abc")) self.assertEqual("picbed:a:b", rsp("a", "b")) self.assertEqual(parse_valid_comma("a,b, c,"), ["a", "b", "c"]) self.assertEqual(parse_valid_verticaline("a|b| c"), ["a", "b", "c"]) self.assertTrue(is_true(1)) self.assertTrue(is_true("on")) self.assertTrue(is_true("true")) self.assertFalse(is_true(0)) self.assertIsInstance(get_current_timestamp(), int) self.assertTrue(allowed_file("test.PNG")) self.assertTrue(allowed_file(".jpeg")) self.assertFalse(allowed_file("my.psd")) self.assertFalse(allowed_file("ha.gif", ["jpg"])) self.assertFalse(allowed_file("ha.jpeg", ["jpg"])) self.assertFalse(allowed_file("ha.png", ["jpg"])) self.assertTrue(allowed_file("ha.jpg", ["jpg"])) v = "6afa9046a9579cad143a384c1b564b9a250d27d6f6a63f9f20bf3a7594c9e2c6" self.assertEqual(v, hmac_sha256('key', 'text')) self.assertEqual(v, hmac_sha256(b'key', b'text')) self.assertEqual(v, hmac_sha256(u'key', u'text')) self.assertEqual( "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", sha256("abc"))
def useruploadpub(): # 通过表单形式上传图片 res = dict(code=1, msg=None) logger.debug(request.files) f = request.files.get('file') callableAction = request.args.get("callableAction") if f and allowed_file(f.filename): filename = gen_rnd_filename() + "." + secure_filename( f.filename).split('.')[-1] # 随机命名 # 判断是否上传到又拍云还是保存到本地 if PICBED['enable'] in ('true', 'True', True): try: files = { 'picbed': (filename, f.stream.read(), 'image/%s' % filename.split(".")[-1]) } resp = requests.post( PICBED["api"], files=files, data=dict(album="passport"), headers=dict(Authorization="LinkToken %s" % PICBED["LinkToken"]), timeout=5).json() if not isinstance(resp, dict): raise except Exception as e: res.update(code=4, msg=e) else: if resp.get('code') == 0: res.update(data=dict(src=resp['src']), code=0) else: res.update(resp) elif Upyun['enable'] in ('true', 'True', True): basedir = Upyun['basedir'] if Upyun['basedir'].startswith( '/') else "/" + Upyun['basedir'] imgUrl = os.path.join(basedir, filename) try: # 又拍云存储封装接口 UploadImage2Upyun(imgUrl, f.stream.read()) except Exception, e: logger.error(e, exc_info=True) res.update(code=2, msg="System is abnormal") else: imgUrl = Upyun['dn'].strip("/") + imgUrl res.update(data=dict(src=imgUrl), code=0) else: if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) f.save(os.path.join(UPLOAD_FOLDER, filename)) imgUrl = request.url_root + IMAGE_FOLDER + filename res.update(data=dict(src=imgUrl), code=0)
def upload_view(): res = dict(code=-1, msg=None) label = request.args.get("label") _has_label = lambda label: g.redis.sismember( current_app.config["labelKey"], label ) and g.redis.exists("{}:label:{}".format(GLOBAL['ProcessName'], label) ) or label == current_app.config["labelDefault"] if not label: label = current_app.config["labelDefault"] if label and _has_label(label): f = request.files.get('file') if f and allowed_file(f.filename): filename = secure_filename(gen_rnd_filename() + "." + f.filename.split('.')[-1]) #随机命名 basedir = Upyun['basedir'] if Upyun['basedir'].startswith( '/') else "/" + Upyun['basedir'] imgUrl = os.path.join(basedir, filename) try: upres = api.put(imgUrl, f.stream.read()) except Exception, e: logger.error(e, exc_info=True) res.update(code=2, msg="Storage failure") else: imgId = md5(filename) imgUrl = Upyun['dn'].strip("/") + imgUrl upres.update(ctime=get_current_timestamp(), imgUrl=imgUrl, imgId=imgId, label=label) try: pipe = g.redis.pipeline() pipe.sadd(current_app.config["picKey"], imgId) pipe.hmset("{}:{}".format(GLOBAL['ProcessName'], imgId), upres) pipe.hincrby( "{}:label:{}".format(GLOBAL['ProcessName'], label), "imgNum") pipe.execute() except Exception, e: logger.error(e, exc_info=True) res.update( code=0, msg= "It has been uploaded, but the server has encountered an unknown error" ) else: logger.info( "Upload to Upyun file saved, its url is %s, result is %s, imgId is %s" % (imgUrl, upres, imgId)) res.update(code=0, imgUrl=imgUrl)
def useruploadpub(): # 通过表单形式上传图片 res = dict(code=1, msg=None) logger.debug(request.files) f = request.files.get('file') callableAction = request.args.get("callableAction") if f and allowed_file(f.filename): filename = secure_filename(gen_rnd_filename() + "." + f.filename.split('.')[-1]) # 随机命名 basedir = Upyun['basedir'] if Upyun['basedir'].startswith('/') else "/" + Upyun['basedir'] imgUrl = os.path.join(basedir, filename) try: # 又拍云存储封装接口 upyunapi = CloudStorage(timeout=15) upyunapi.put(imgUrl, f.stream.read()) except Exception, e: logger.error(e, exc_info=True) res.update(code=2, msg="System is abnormal") else: imgUrl = Upyun['dn'].strip("/") + imgUrl res.update(data=dict(src=imgUrl), code=0)
def test_utils(self): self.assertEqual("900150983cd24fb0d6963f7d28e17f72", md5("abc")) self.assertEqual("a9993e364706816aba3e25717850c26c9cd0d89d", sha1("abc")) self.assertEqual("picbed:a:b", rsp("a", "b")) self.assertEqual(parse_valid_comma("a,b, c,"), ["a", "b", "c"]) self.assertEqual(parse_valid_verticaline("a|b| c"), ["a", "b", "c"]) self.assertTrue(is_true(1)) self.assertTrue(is_true("on")) self.assertTrue(is_true("true")) self.assertFalse(is_true(0)) self.assertIsInstance(get_current_timestamp(), int) self.assertTrue(allowed_file("test.PNG")) self.assertTrue(allowed_file(".jpeg")) self.assertFalse(allowed_file("my.psd")) self.assertFalse(allowed_file("ha.gif", ["jpg"])) self.assertFalse(allowed_file("ha.jpeg", ["jpg"])) self.assertFalse(allowed_file("ha.png", ["jpg"])) self.assertTrue(allowed_file("ha.jpg", ["jpg"])) v = "6afa9046a9579cad143a384c1b564b9a250d27d6f6a63f9f20bf3a7594c9e2c6" self.assertEqual(v, hmac_sha256("key", "text")) self.assertEqual(v, hmac_sha256(b"key", b"text")) self.assertEqual(v, hmac_sha256(u"key", u"text")) self.assertEqual( "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", sha256("abc"), ) #: test format_upload_src baseimg = "img-url" basefmt = {"src": baseimg} self.assertEqual(format_upload_src(123, baseimg), basefmt) self.assertEqual(format_upload_src(None, baseimg), basefmt) self.assertEqual(format_upload_src([0], baseimg), basefmt) self.assertEqual(format_upload_src("", baseimg), basefmt) self.assertEqual(format_upload_src(".", baseimg), basefmt) self.assertEqual(format_upload_src(".1", baseimg), basefmt) self.assertEqual(format_upload_src("1.", baseimg), basefmt) self.assertEqual(format_upload_src(1.1, baseimg), basefmt) self.assertEqual(format_upload_src("1.1", baseimg), {"1": { "1": baseimg }}) self.assertEqual(format_upload_src("u", baseimg), basefmt) self.assertEqual(format_upload_src("im", baseimg), {"im": baseimg}) self.assertEqual(format_upload_src("url", baseimg), {"url": baseimg}) self.assertEqual(format_upload_src("i.am.src", baseimg), basefmt) self.assertEqual(format_upload_src("src.url", baseimg), {"src": { "url": baseimg }}) #: test format_apires self.assertEqual(format_apires({"code": 0}, "success", "bool"), {"success": True}) self.assertEqual(format_apires({"code": 0}, oc="200"), {"code": 200}) self.assertEqual(format_apires({"code": -1}, "status", "bool"), {"status": False}) self.assertEqual( format_apires(dict(code=-1, msg="xxx"), "errno", "200"), { "errno": -1, "msg": "xxx" }, ) self.assertEqual( format_apires(dict(code=-1, msg="xxx"), "errno", "200", "errmsg"), { "errno": -1, "errmsg": "xxx" }, ) self.assertEqual( format_apires(dict(code=0, msg="xxx"), "", "200", "errmsg"), { "code": 200, "errmsg": "xxx" }, ) self.assertEqual(len(generate_random()), 6) self.assertIn("Mozilla/5.0", gen_ua()) # bleach self.assertEqual(bleach_html("<i>abc</i>"), "<i>abc</i>") self.assertEqual( bleach_html("<script>var abc</script>"), "<script>var abc</script>", ) # re self.assertEqual(parse_author_mail("staugur"), ("staugur", None)) self.assertEqual(parse_author_mail("staugur <mail>"), ("staugur", "mail"))
def test_utils(self): self.assertEqual("900150983cd24fb0d6963f7d28e17f72", md5("abc")) self.assertEqual( "a9993e364706816aba3e25717850c26c9cd0d89d", sha1("abc") ) self.assertEqual("picbed:a:b", rsp("a", "b")) self.assertEqual(parse_valid_comma("a,b, c,"), ["a", "b", "c"]) self.assertEqual(parse_valid_verticaline("a|b| c"), ["a", "b", "c"]) self.assertTrue(is_true(1)) self.assertTrue(is_true("on")) self.assertTrue(is_true("true")) self.assertFalse(is_true(0)) self.assertIsInstance(get_current_timestamp(), int) self.assertTrue(allowed_file("test.PNG")) self.assertTrue(allowed_file(".jpeg")) self.assertFalse(allowed_file("my.psd")) self.assertFalse(allowed_file("ha.gif", ["jpg"])) self.assertFalse(allowed_file("ha.jpeg", ["jpg"])) self.assertFalse(allowed_file("ha.png", ["jpg"])) self.assertTrue(allowed_file("ha.jpg", ["jpg"])) v = "6afa9046a9579cad143a384c1b564b9a250d27d6f6a63f9f20bf3a7594c9e2c6" self.assertEqual(v, hmac_sha256('key', 'text')) self.assertEqual(v, hmac_sha256(b'key', b'text')) self.assertEqual(v, hmac_sha256(u'key', u'text')) self.assertEqual( "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", sha256("abc") ) #: test format_upload_src baseimg = 'img-url' basefmt = {'src': baseimg} self.assertEqual(format_upload_src(123, baseimg), basefmt) self.assertEqual(format_upload_src(None, baseimg), basefmt) self.assertEqual(format_upload_src([0], baseimg), basefmt) self.assertEqual(format_upload_src('', baseimg), basefmt) self.assertEqual(format_upload_src('.', baseimg), basefmt) self.assertEqual(format_upload_src('.1', baseimg), basefmt) self.assertEqual(format_upload_src('1.', baseimg), basefmt) self.assertEqual(format_upload_src(1.1, baseimg), basefmt) self.assertEqual( format_upload_src('1.1', baseimg), {'1': {'1': baseimg}} ) self.assertEqual(format_upload_src('u', baseimg), basefmt) self.assertEqual(format_upload_src('im', baseimg), {'im': baseimg}) self.assertEqual(format_upload_src('url', baseimg), {'url': baseimg}) self.assertEqual(format_upload_src('i.am.src', baseimg), basefmt) self.assertEqual( format_upload_src('src.url', baseimg), {'src': {'url': baseimg}} ) #: test format_apires self.assertEqual( format_apires({'code': 0}, "success", "bool"), {'success': True} ) self.assertEqual( format_apires({'code': 0}, oc="200"), {'code': 200} ) self.assertEqual( format_apires({'code': -1}, "status", "bool"), {'status': False} ) self.assertEqual( format_apires(dict(code=-1, msg='xxx'), 'errno', '200'), {'errno': -1, 'msg': 'xxx'} ) self.assertEqual( format_apires(dict(code=-1, msg='xxx'), 'errno', '200', 'errmsg'), {'errno': -1, 'errmsg': 'xxx'} ) self.assertEqual( format_apires(dict(code=0, msg='xxx'), '', '200', 'errmsg'), {'code': 200, 'errmsg': 'xxx'} ) self.assertEqual(len(generate_random()), 6) self.assertIn("Mozilla/5.0", gen_ua())