示例#1
0
def b_auth(b_app_key,b_app_secret):
	global b_access_token
	print 'Authenticating with Baidu'
	if not b_access_token
		code_url = 'https://openapi.baidu.com/oauth/2.0/device/code?'
		code_url += 'client_id=' + b_app_key
		code_url += '&response_type=device_code'
		code_url += '&scope=basic netdisk'
		response = urllib2.urlopen(code_url)
		data = json.load(response)
		reply = raw_input("Enter 'y' here when you have submitted the user code '" + data['user_code'] + "' at " + data['verification_url']).strip()
		if reply == 'y':
			code_url = 'https://openapi.baidu.com/oauth/2.0/token?'
			code_url += 'grant_type=device_token' 
			code_url += '&code=' + data['device_code']
			code_url += '&client_id=' + b_app_key
			code_url += '&client_secret=' + b_app_secret
			response1 = urllib2.urlopen(code_url)
			data1 = json.load(response1)
			if not ('error' in data1):
				b_access_token = data1['access_token']
				cfg = ConfigParser.ConfigParser()
				cfg.set('Baidu',b_access_token)
				cfgfile = open('Dropbox2BaiduPCS.cfg','w')
				config.write(cfgfile)
				cfgfile.close()
			else:
				reply = raw_input("Authentication failed.  Do you wish to try again? (y/n)").strip()
				if reply == 'y':
					b_auth(b_app_key,b_app_secret)
				else:
					print 'OK, bye!'
					sys.exit()

		else:
			reply = raw_input("Do you wish to try to authorise with Baidu again? (y/n)").strip()
			if reply == 'y':
				b_auth(b_app_key,b_app_secret)
			else:
				print 'OK, bye!'
				sys.exit()
	if(b_access_token != ''):
		pcs = PCS(b_access_token)
		qresponse = pcs.info()
		qdata = qresponse.json()
		print 'Baidu Quota: ' + sizeof_fmt(float(qdata["quota"]))
		print 'Baidu Used: ' + sizeof_fmt(float(qdata['used']))
		qdata = pcs.meta('/apps/mygreater/dropbox').json();
		if ('error_code' in qdata):
			print 'Creating Dropbox folder on Baidu...'
			qdata = pcs.mkdir(bpath)
			print 'Baidu Ready!'
		else:
			print 'Baidu Ready!'
		return pcs
示例#2
0
 def connPCS(self):
     try:
         pcs = PCS(self.baidu_accesstoken)
         reponse = pcs.info()
         if reponse.ok:
             self.pcsflag = True
             self.pcs = pcs
         else:
             self.pcsflag = False
     except InvalidToken, ex:
         print InvalidToken, ":", ex
示例#3
0
 def connPCS(self):
      try:
           pcs = PCS(self.baidu_accesstoken)
           reponse = pcs.info()
           if reponse.ok:
                self.pcsflag = True
                self.pcs = pcs
           else:
                self.pcsflag = False
      except InvalidToken, ex:
           print InvalidToken,":",ex
def test_invalidtoken():
    try:
        PCS('abc').info()
    except InvalidToken:
        assert True
    else:
        assert False
示例#5
0
class BaiDuFuse(LoggingMixIn, Operations):
    def __init__(self, accessToken, basedir):
        self.pcs = PCS(accessToken)
        self.appdir = "/apps/" + basedir + "/"

    def statfs(self, path):
        disk_info = self.pcs.info().json()
        bsize = 4096
        total = disk_info['quota'] / bsize
        used = disk_info['used'] / bsize
        free = total - used

        free_files = 1024
        return dict(f_bsize=bsize, f_frsize=bsize, f_blocks=total, f_bavail=free, f_bfree=free,
                    f_files=free_files, f_ffree=free_files, f_favail=free_files)

    def readdir(self, path, fh):
        dirpath = normpath(self.appdir + path)
        filelist = self.pcs.list_files(dirpath).json()['list']

        files = ['.', '..']
        for file in filelist:
            files.append(basename(file['path']))

        return files

    def getattr(self, path, fh=None):
        print path

        dir_attr = dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
        if path == '/':
            return dir_attr

        filelist = self.pcs.list_files(normpath(self.appdir + dirname(path))).json()['list']

        for file in filelist:
            file_path = file['path']
            if file_path != normpath(self.appdir + "/" + path):
                continue

            if file['isdir'] == 1:
                return dir_attr

            return dict(st_mode=(S_IFREG | 0777), st_nlink=1, st_size=file['size'])

        raise FuseOSError(ENOENT)
示例#6
0
文件: baidu_pcs.py 项目: Tefx/turnip
class BaiduPCS(storage.DiskStorageBase):
	def _connect(self):
		self.pcs = PCS(self.config["access_token"])

	def _check_error(self, resp):
		if resp.ok:
			try:
				return resp.json()
			except:
				pass
		else:
			try:
				msg = resp.json()
			except:
				raise storage.StorageFail(resp.content)
			if "error_code" in msg:
				raise storage.StorageFail(msg["error_msg"])
			else:
				raise storage.StorageFail(resp.state)

	def free(self):
		resp = self.pcs.info()
		msg = self._check_error(resp)
		return msg["quota"] - msg["used"]

	def _upload(self, infile, path):
		return self.pcs.upload(path, infile, ondup="overwrite")

	def _download(self, path, outfile):
		resp = self.pcs.download(path)
		self._check_error(resp)
		for chunk in resp.iter_content(chunk_size=1024):
			if chunk:
				outfile.write(chunk)

	def _get_contents(self, resp):
		return resp["list"]

	def _is_dir(self, item):
		return item["isdir"]

	def _get_path(self, item):
		return item["path"]

	def _meta(self, path):
		return self.pcs.list_files(path)

	def _mkdir(self, path):
		return self.pcs.mkdir(path)

	def _delete(self, path):
		return self.pcs.delete(path)
示例#7
0
import json
import argparse
import os

parser = argparse.ArgumentParser(description='This is a simple \
                                 client of baiduyun')
parser.add_argument('-t', '--token',
                    default='token/access_token.txt',
                    help='access token file name')
parser.add_argument('filename',
                    help='final file name for all file blocks')
parser.add_argument('blocks',
                    nargs='+',
                    help='blocks need to join')
args = parser.parse_args()
print(args)

json_content = open(args.token).read()
json_content = json.loads(json_content)
token = json_content['access_token']
pcs = PCS(token, api_template='https://c.pcs.baidu.com/rest/2.0/pcs/{0}')

finalname = '/apps/gentoo/' + os.path.basename(args.filename)
blocks_md5 = []
for block in args.blocks:
    with open(block) as f:
        resp = pcs.upload_tmpfile(f)
        blocks_md5.append(resp.json()['md5'])
pcs.api_template = 'https://pcs.baidu.com/rest/2.0/pcs/{0}'
pcs.upload_superfile(finalname, blocks_md5)
示例#8
0
文件: cloud.py 项目: Amos-zq/justpic
import MySQLdb
db = MySQLdb.connect("localhost", "david", "david", "picturetoken")
cursor = db.cursor()

cursor.execute("select * from picturetoken")
rs = cursor.fetchone()
# cursor.close
print rs
print rs[2]
access_token = rs[1]
refresh_token = rs[2]
from baidupcs import PCS
# access_token = '21.9403b998cd9b271fa44a54199aad2949.2592000.1401980588.3875775130-1056026'
pcs = PCS(access_token)


def create_cache():
    pass


def test_thumbnail():
    response = pcs.thumbnail('/apps/justpic/5K/118000/118097.jpeg', 400, 400)
    print response.url
    # im = Image.open(StringIO(response.content))
    # im.show()
    print response.ok
    assert response.ok


test_thumbnail()
示例#9
0
文件: baidu_pcs.py 项目: Tefx/turnip
	def _connect(self):
		self.pcs = PCS(self.config["access_token"])
示例#10
0
 def __init__(self, accessToken, basedir):
     self.pcs = PCS(accessToken)
     self.appdir = "/apps/" + basedir + "/"
示例#11
0
 def test(self):
     pcs = PCS('access_token')
     response = pcs.info()
     print(response)
     if response.status_code == 200:
         print(response.content)