Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
matAlmeida committed Jul 16, 2018
0 parents commit d0cc891
Show file tree
Hide file tree
Showing 9 changed files with 337 additions and 0 deletions.
108 changes: 108 additions & 0 deletions .gitignore
@@ -0,0 +1,108 @@
# Google API Credentials
client_secret.json
credentials.json

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
21 changes: 21 additions & 0 deletions LICENSE.md
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 [Matheus Almeida](https://twitter.com/mat_almeida)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
7 changes: 7 additions & 0 deletions README.md
@@ -0,0 +1,7 @@
# GDrive Python

## by [Matheus Almeida](https://twitter.com/mat_almeida)

Use Google Drive API v3 with a python interface

# MIT License
4 changes: 4 additions & 0 deletions client_secret.example.json
@@ -0,0 +1,4 @@
{
"_comment":
"Enter on this site: https://developers.google.com/drive/api/v3/quickstart/python and follow the step 1 to download your client_secrets"
}
Binary file added files/test.pdf
Binary file not shown.
1 change: 1 addition & 0 deletions pygdrive3/__init__.py
@@ -0,0 +1 @@
name = "pygdrive3"
173 changes: 173 additions & 0 deletions pygdrive3/service.py
@@ -0,0 +1,173 @@
from __future__ import print_function
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from httplib2 import Http
from oauth2client import file, client, tools
import mimetypes
import os


class DriveService:
def __init__(self, driver=None):
if driver == None:
SCOPES = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets(
'client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
drive_service = build('drive', 'v3', http=creds.authorize(Http()))
else:
drive_service = driver

self.drive_service = drive_service

def create_folder(self, name, parent_id=None):
metadata = {
'name': name,
'mimeType': 'application/vnd.google-apps.folder',
'parents': [parent_id]
}

folder = self.drive_service.files().create(
body=metadata,
fields='id'
).execute()

return folder.get('id')

def upload_file(self, name, filePath, folder_id):
fileType = mimetypes.guess_type(filePath)[0]
if fileType == None:
raise NameError("Invalid type or missing suffix!")

file_metadata = {
'name': name + '.' + fileType.split('/')[-1],
'parents': [folder_id]
}
media = MediaFileUpload(filePath, mimetype=fileType)

file = self.drive_service.files().create(
body=file_metadata,
media_body=media,
fields='id webViewLink'
).execute()

return {
'id': file.get('id'),
'link': file.get('webViewLink')
}

def writer_permission(self, email, file_id):
batch = self.drive_service.new_batch_http_request(
callback=self.__callback)
permission = {
'type': 'user',
'role': 'writer',
'emailAddress': email
}
batch.add(self.drive_service.permissions().create(
fileId=file_id,
body=permission,
fields='id',
))
batch.execute()

return True

def anyone_permission(self, file_id):
batch = self.drive_service.new_batch_http_request(
callback=self.__callback)
permission = {
'type': 'anyone',
'role': 'reader'
}
batch.add(self.drive_service.permissions().create(
fileId=file_id,
body=permission,
fields='id',
))
batch.execute()

return {'link': 'https://drive.google.com/file/d/{0}/view?usp=sharing'.format(file_id)}

def list_folders_by_name(self, name):
return self.__list_items_by_name(name, "mimeType = 'application/vnd.google-apps.folder'")

def list_files_by_name(self, name):
return self.__list_items_by_name(name, "mimeType != 'application/vnd.google-apps.folder'")

def list_files_from_folder_id(self, folder_id):
itemsList = []

page_token = None
while True:
response = self.drive_service.files().list(
q="'" + folder_id + "' in parents",
spaces='drive',
fields='nextPageToken, files(id, name, modifiedTime, mimeType, size)',
pageToken=page_token
).execute()

for file in response.get('files', []):
# Process change
itemsList.append({
'id': file.get('id'),
'name': file.get('name'),
'modifiedTime': file.get('modifiedTime'),
'type': file.get('mimeType'),
'size': file.get('size')
})
page_token = response.get('nextPageToken', None)
if page_token is None:
break

return itemsList

def __list_items_by_name(self, name, extraQuery=None):
if len(name.split(' ')) > 1:
query = ''
for nm in name.split(' '):
query += 'name contains ' + nm + ' and '
query = query[:-5]
else:
query = name

if extraQuery != None:
query += " and " + extraQuery

itemsList = []

page_token = None
while True:
response = self.drive_service.files().list(
q=query,
spaces='drive',
fields='nextPageToken, files(id, name, modifiedTime, mimeType, size)',
pageToken=page_token
).execute()

for file in response.get('files', []):
# Process change
itemsList.append({
'id': file.get('id'),
'name': file.get('name'),
'modifiedTime': file.get('modifiedTime'),
'type': file.get('mimeType'),
'size': file.get('size')
})
page_token = response.get('nextPageToken', None)
if page_token is None:
break

return itemsList

def __callback(self, request_id, response, exception):
if exception:
# Handle error
print(exception)
else:
pass


2 changes: 2 additions & 0 deletions requeriments.txt
@@ -0,0 +1,2 @@
google-api-python-client==1.6.7
oauth2client==4.1.2
21 changes: 21 additions & 0 deletions setup.py
@@ -0,0 +1,21 @@
import setuptools

with open("README.md", "r") as fh:
long_description = fh.read()

setuptools.setup(
name="pygdrive3",
version="0.0.0",
author="Matheus Almeida",
author_email="mat.almeida@live.com",
description="Use Google Drive API v3 with a python interface",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/matalmeida/pygdrive3",
packages=setuptools.find_packages(),
classifiers=(
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
),
)

0 comments on commit d0cc891

Please sign in to comment.