def __init__(self, config): appid = int(config["appid"]) key = unicode(config["key"]) secret = unicode(config["secret"]) region = unicode(config["region"]) self.client = qcos.CosClient(appid, key, secret, region)
def init_tencent(): appid = 1254265243 secret_id = u'' secret_key = u'' region_info = 'sh' cos_client = qcloud_cos.CosClient( appid, secret_id, secret_key, region=region_info) return cos_client
def _check_cos_config(self): try: int(self.cos_config["appid"]) except (ValueError, KeyError): raise ValueError("app_id must int value") appid = int(self.cos_config["appid"]) key = unicode(self.cos_config["key"]) secret = unicode(self.cos_config["secret"]) region = unicode(self.cos_config["region"]) qcos.CosClient(appid, key, secret, region)
def __init__(self, **kwargs): dev = kwargs.pop("dev", False) super(QCloudStorage, self).__init__(dev=dev) self._region = kwargs.get("region", QCLOUD_COS_REGION) self._bucket = kwargs.get("bucket", QCLOUD_COS_BUCKET) self._public_access = kwargs.get("publicAccess", True) app_id = kwargs.get("app_id", QCLOUD_COS_APP_ID) secret_id = kwargs.get("secret_id", QCLOUD_COS_SECRET_ID) secret_key = kwargs.get("secret_key", QCLOUD_COS_SECRET_KEY) # FIXME: qcloud_cos api changes self._cos_client = qcloud_cos.CosClient(app_id, secret_id, secret_key, region=self.region) self._cos_config = qcloud_cos.CosConfig( sign_expired=QCLOUD_COS_EXPIRED, region=self.region) self._cos_client.set_config(self._cos_config) download_hostname = self._cos_config.get_download_hostname() self._download_endpoint = "http://{}-{}.{}".format( self.bucket, app_id, download_hostname)
#!/etc/bin/env python # coding:utf-8 # 腾讯云 文件交互操作 # 设置用户属性, 包括appid, secret_id和secret_key # 这些属性可以在cos控制台获取(https://console.qcloud.com/cos) import qcloud_cos appid = 1253472137 # 替换为用户的appid secret_id = u'AKIDteFftzcTs8D8rNxnjT0NTQBj5EBy81FG' # 替换为用户的secret_id secret_key = u'Jk5HJ9nFXcUAduyqqgMqIZdUBfx3ygBT' # 替换为用户的secret_key region_info = "gz" # # 替换为用户的region,目前可以为 sh/gz/tj,分别对应于上海,广州,天津园区 cos_client = qcloud_cos.CosClient(appid, secret_id, secret_key, region=region_info) # 设置要操作的bucket bucket = u'zhangh214' ############################################################################ # 文件操作 # ############################################################################ # 1. 上传文件(默认不覆盖) # 将本地的py_demo.py上传到bucket的根分区下,并命名为py_demo.py # 默认不覆盖, 如果cos上文件存在,则会返回错误 request = qcloud_cos.UploadFileRequest(bucket, u'/demokit.py', u'py_demo2.py') upload_file_ret = cos_client.upload_file(request) print 'upload file ret:', repr(upload_file_ret) # 2. 上传文件(覆盖文件) # 将本地的py_demo2.py上传到bucket的根分区下,覆盖已上传的py_demo.py request = qcloud_cos.UploadFileRequest(bucket, u'/demokit.py', u'py_demo2.py')
def creatSection(request): try: body = request.POST.dict() if 'courseid' not in body: t = loader.get_template('upload.html') return HttpResponse(t.render()) user = tokenActive({'token': body['token']}) if not isinstance(user, User): return pack(code=user) # 如果是学生,那么不让创建 if user.type == 0: return pack(msg='学生无法创建课程') # 获取当前时间戳 now = int(1000 * time.time()) id = random_str() section = EditSection(sectionid=id, creattime=now, creator=user.userid, type=body['type'], title=body['title'], father=body['courseid'], operator=0) # 获取上传的文件,如果没有文件,则默认为None file = request.FILES.get("file", None) if not file: pack(msg="no files for upload!") # 文字文件和视频文件分别处理 if body['type'] == '1': appid = 1252409052 secret_id = u'AKIDQkspaAxYEZItIV7K2axCF6yuhHIDfVr0' secret_key = u'CG8nkZJtJXaS7au1vdJsGtOp4JQQFsRp' region_info = u"tj" cos_client = qcloud_cos.CosClient(appid, secret_id, secret_key, region=region_info) creatSectionFile(file=file, section=section) request = qcloud_cos.UploadFileRequest( u'conlinestatic1', u'/sectionfile/' + section.fileurl, u'' + sectionfiledir + section.fileurl) res = cos_client.upload_file(request) if res['code'] != 0: raise Exception('上传失败') request = qcloud_cos.UpdateFileRequest( u'conlinestatic1', u'/sectionfile/' + section.fileurl) request.set_content_disposition(u'inline; filename=' + section.fileurl) cos_client.update_file(request) os.remove(sectionfiledir + section.fileurl) elif body['type'] == '0': filetype = '.' + str(file).split('.')[1] # 如果是txt或者md那么存到数据库 if filetype == '.txt' or filetype == '.md': filecontent = file.read() # 获取编码方式 encodetype = chardet.detect(filecontent)['encoding'] section.content = filecontent.decode(encodetype) # 如果是pdf那么创建文件 elif filetype == '.pdf': creatSectionFile(file=file, section=section) # 如果是doc那么先转pdf再保存文件 elif filetype == '.doc': creatSectionFile(file=file, section=section) desfile = random_str() + '.pdf' log('des: ' + desfile) log('sre' + section.fileurl) office = subprocess.Popen(['sh', '/home/ubuntu/office.sh']) office.wait() write = subprocess.Popen([ 'python3', '/home/ubuntu/DocumentConverter.py', sectionfiledir + section.fileurl, sectionfiledir + desfile ], stderr=subprocess.PIPE, stdout=subprocess.PIPE) write.wait() if write.stderr.read() != '': log('error: ' + write.stderr.read()) raise Exception('上传出错') section.fileurl = desfile else: raise Exception('文件类型错误') section.save() return pack() except Exception as e: return pack(msg=e)
datefmt='%Y:%m:%d %H:%M:%S', filemode='w') logger = logging.getLogger('mylogger') cp = ConfigParser.SafeConfigParser() cp.read('cloud_album.conf') gpgkeyname = cp.get('gnupg', 'keyname') gpg = gnupg.GPG(gnupghome=cp.get('gnupg', 'home')) appid = int(cp.get('cos', 'appid')) secretid = unicode(cp.get('cos', 'secretid'), "utf-8") secretkey = unicode(cp.get('cos', 'secretkey'), "utf-8") cos_client = qcloud_cos.CosClient(appid, secretid, secretkey) access_token = unicode(cp.get('baiduyun', 'access_token'), "utf-8") baiduyundisk = BaiduPan(access_token) leancloud.init(cp.get('leancloud', 'appid'), cp.get('leancloud', 'appkey')) logger.setLevel(logging.INFO) #print args.photofiles if os.path.isfile(args.photofiles[0]): totalfilename = args.photofiles[0] p, photofile = os.path.split(totalfilename) if not isphototype(totalfilename): logger.error('Not photo : ' + photofile) sys.exit(0)
def __init__(self, parent=None): super(Window, self).__init__(parent) self.setupUi(self) QObject.connect(self.pushButton_prev, SIGNAL("clicked()"), self.change_pb_prev) QObject.connect(self.pushButton_next, SIGNAL("clicked()"), self.change_pb_next) QObject.connect(self.pushButton_auto, SIGNAL("clicked()"), self.change_pb_auto) QObject.connect(self.pushButton_myrating, SIGNAL("clicked()"), self.change_pb_myrating) QObject.connect(self.pushButton_comment, SIGNAL("clicked()"), self.change_pb_comment) QObject.connect(self.pushButton_delete, SIGNAL("clicked()"), self.change_pb_delete) QObject.connect(self.comboBox_viewtype, SIGNAL('activated(int)'), self.onActivatedViewtype) self.current_viewtype = 1 # 2 - Best Love Only, 1 - Normal, 0 - All self.comboBox_viewtype.setCurrentIndex(self.current_viewtype) # self.label.setScaledContents(True) # self.label.resize(self.widget.size()) # self.label.setSizePolicy(QSizePolicy.Ignored,QSizePolicy.Ignored) # self.setCentralWidget(self.label) self.dateedit_start.setDisplayFormat('yyyy MM dd') self.qdate_start = QDate(2003, 7, 1) self.dateedit_start.setDate(self.qdate_start) self.dateedit_start.dateChanged.connect(self.startDateChanged) self.dateedit_end.setDisplayFormat('yyyy MM dd') # self.qdate_end=QDate.currentDate() self.qdate_end = QDate(2005, 10, 1) self.dateedit_end.setDate(self.qdate_end) self.dateedit_end.dateChanged.connect(self.endDateChanged) # self.currentyear = self.qdate_start.year() # self.currentmonth = self.qdate_start.month() self.label_dbinfo.setWordWrap(True) # self.checkBox_bestloveonly.toggled.connect(self.bestloveonlySetValue) #cloud album self.cp = ConfigParser.SafeConfigParser() self.cp.read('cloud_album.conf') logging.basicConfig( #filename = "D:\\tmp\\cloud_album_log.txt", level=logging.WARNING, format='%(asctime)s %(levelname)s %(message)s', datefmt='%Y:%m:%d %H:%M:%S', filemode='w') self.logger = logging.getLogger('mylogger') self.gpgkeyname = self.cp.get('gnupg', 'keyname') self.gpg = gnupg.GPG(gnupghome=self.cp.get('gnupg', 'home')) self.passphrase = self.cp.get('gnupg', 'passphrase') appid = int(self.cp.get('cos', 'appid')) secretid = unicode(self.cp.get('cos', 'secretid'), "utf-8") secretkey = unicode(self.cp.get('cos', 'secretkey'), "utf-8") self.cos_client = qcloud_cos.CosClient(appid, secretid, secretkey) self.bucketname = unicode(self.cp.get('cos', 'bucketname'), "utf-8") self.file_folder_ret_data_context = None self.file_folder_ret_data_has_more = True leancloud.init(self.cp.get('leancloud', 'appid'), self.cp.get('leancloud', 'appkey')) self.pictureDB = leancloud.Object.extend('PictureDB')() self.query = leancloud.Query('PictureDB') self.logger.setLevel(logging.INFO) self.first_run_flag = 1 self.all_path_list = [] self.scan_all_path() print self.all_path_list self.all_path_list_count = len(self.all_path_list) print self.all_path_list_count self.current_index = 0 self.order = 2 # 0 -- next, 1 -- prev, 2 -- N/A self.view_count_in_folder = 0 self.auto_flag = False # False: stop, True: auto self.myratingStr = ['NotLove', 'Normal', 'Love'] self.processThread = processorThread() self.processThread.processSignal.connect(self.auto_show_slot, Qt.QueuedConnection) self.processThread.start()