Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Some Drive API code #32

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,81 @@
#from __future__ import print_function
from flask import Flask, render_template, request, json
#from flask_mysqldb import MySQL
import studentData

import httplib2
import os
import io

from apiclient import discovery
from apiclient.http import MediaFileUpload
from apiclient.http import MediaIoBaseDownload
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

#The code below gives an argument passing error that needs to be fixed due to which quickstart.py first needs to be run before app.py the first time the system is started or SCOPE is changed
"""try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None"""
#flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/drive-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Math Web'

def get_credentials():
"""Gets valid user credentials from storage.

If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.

Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'drive-python-quickstart.json')

print(credential_path);

store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials

def returnFileList(parent1, parent2, parent3):
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
parentid2 = service.files().list(q="name contains 'DAA'", pageSize=500,fields="nextPageToken, files(id, name)").execute().get('files', [])[0]['id'];
print parentid2
print "me"
parentid2 = "'" + parentid2 + "'"
results = service.files().list(q=parentid2+" in parents",pageSize = 100, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print('{0} ({1})'.format(item['name'], item['id']))
return json.dumps(items)

app = Flask(__name__)
#mysql = MySQL(app)

Expand Down Expand Up @@ -34,6 +108,13 @@ def searchQuery():
return "Hello "+request.form["query"];
#return ['query'];

@app.route("/listdrivefiles", methods=["POST"])
def listDriveFiles():
commandarr = request.form["commandarr"]
print commandarr;
return returnFileList("Hello", "Tata", "Bye Bye")


@app.route("/signup")
def signUp():
#conn = MySQL.connect(host="localhost", user="root", passwd="", db="mathletesdb")
Expand All @@ -60,5 +141,19 @@ def signUpFeed():
def announcement():
return render_template("pages/announcements.html");

@app.route("/makeannouncement", methods=["POST"])
def makeAnnouncement():
heading = request.form['heading'];
description = request.form['description'];
announcefile = open("static/announcements.html");
initial = announcefile.read();
announcefile.close();
announcefile = open("static/announcements.html", "w");
prepend = "<br/><h1>"+heading+"</h1><p>"+description+"</p>";
final = prepend+initial;
announcefile.write(final);
announcefile.close();
return "Go Back (and press Ctrl+F5) to see announcement";

if __name__ == "__main__":
app.run(debug=True);
1 change: 1 addition & 0 deletions client_secret.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"installed":{"client_id":"927147348913-iuimukf225lkbiobne5mtmus1oq20ug2.apps.googleusercontent.com","project_id":"mathweb-2k15","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://accounts.google.com/o/oauth2/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"jzaCkVEv3iUKgqFcOnNdT15Y","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}
91 changes: 91 additions & 0 deletions quickstart.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
from __future__ import print_function
import httplib2
import os
import io

from apiclient import discovery
from apiclient.http import MediaFileUpload
from apiclient.http import MediaIoBaseDownload
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/drive-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Math Web'


def get_credentials():
"""Gets valid user credentials from storage.

If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.

Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'drive-python-quickstart.json')

print(credential_path);

store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials

def main():
"""Shows basic usage of the Google Drive API.

Creates a Google Drive API service object and outputs the names and IDs
for up to 10 files.
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)

results = service.files().list(
pageSize=500,fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print('{0} ({1})'.format(item['name'], item['id']))

"""file_metadata = {'name':'photo.jpg'} #Uploaded a photo in images folder
media = MediaFileUpload('files/photo.jpg', mimetype='image/jpeg')
file = service.files().create(body=file_metadata,media_body=media,fields='id').execute()
print ("File ID: %s"%file.get('id'));"""

"""file_id = "0BwWAtSE3W46ZdjNDNmVHQjN0eVE";
request = service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
#print ("Download %d%%.")%int(status.progress() * 100)"""

if __name__ == '__main__':
main()
12 changes: 12 additions & 0 deletions static/announcements.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<br/>
<h1>Reporting Date</h1>
<p>The reporting date for all students is 16<sup>th</sup>July, 2017. Students are advised to come at the earliest so that they ensure proper settlements.</p>
<br/>
<h1>T-Shirts</h1>
<p>We have come up with new T-shirt design for Mathletes. You can have a look here. Orders can be placed by contacting (person_name) or through the site.</p>
<br/>
<h1>T-Shirts</h1>
<p>We have come up with new T-shirt design for Mathletes. You can have a look here. Orders can be placed by contacting (person_name) or through this site.</p>
<br/>
<h1>Reporting Date</h1>
<p>The reporting date for all students is 16<sup>th</sup>July, 2017. Students are advised to come at the earliest so that they ensure proper settlements.</p>
14 changes: 14 additions & 0 deletions static/layout/scripts/announcements.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
$(document).ready(function(){
$("#announcebutton").click(function(){
$(".makeannouncement").show();
$(".showannouncement").hide();
});
$.ajax({
type:"GET",
url:"static/announcements.html",
success: function(data){
$(".showannouncement").prepend(data);
},
cache: false
});
});
48 changes: 42 additions & 6 deletions static/layout/scripts/semmaterials.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ $(document).ready(function(){
});

var buttoncontent;
var commandarr = ["null", "null", "null", "false"]; //An array whose JSON instance will be sent to backend to decide what specific action to be taken
var commandarrjson = JSON.stringify(commandarr);

$(".materialselect button").hover(function(){
buttoncontent = $(this).html();
Expand All @@ -43,17 +45,28 @@ $(document).ready(function(){
$(".level1 button").css({"backgroundColor":"#562351", "borderStyle":"none", "color":"white"});
$(".materialselect .level3").hide();
$(".materialselect .level2").hide();
$(this).parent().css({"backgroundColor":"white", "border":"1px solid rgb(71,71,71)", "color":"rgb(71,71,71)"});
$(this).parent().css({"backgroundColor":"white", "border":"1px solid rgb(71,71,71)", "color":"rgb(71,71,71)"});
commandarr = ["null", "null", "null", "false"];
commandarr[0] = buttoncontent;
commandarrjson = JSON.stringify(commandarr);
//send a download request
}
else if (buttoncontent=="Assignments"||buttoncontent=="Books"||buttoncontent=="Notes"||buttoncontent=="Question Papers"){
$(".level3 button").css({"backgroundColor":"#562351", "borderStyle":"none", "color":"white"});
$(this).parent().css({"backgroundColor":"white", "border":"1px solid rgb(71,71,71)", "color":"rgb(71,71,71)"});
commandarr[2] = buttoncontent; commandarr[3] = "false";
commandarrjson = JSON.stringify(commandarr);
//send a download request
}
else{
$(".level3 button").css({"backgroundColor":"#562351", "borderStyle":"none", "color":"white"});
$(".level2 button").css({"backgroundColor":"#562351", "borderStyle":"none", "color":"white"});
$(this).parent().css({"backgroundColor":"white", "border":"1px solid rgb(71,71,71)", "color":"rgb(71,71,71)"});
$(".materialselect .level3").hide();
commandarr[2] = "null"; commandarr[3] = "false";
commandarr[1] = buttoncontent;
commandarrjson = JSON.stringify(commandarr);
//send a download request
}
}
else{
Expand All @@ -73,26 +86,49 @@ $(document).ready(function(){
}
}

/*$.ajax({
type:"GET",
url:"static/subjectlist/sem"+sublistno+".html",
$.ajax({
type:"GET",
url:"static/subjectlist/sem"+sublistno+".json",
success: function(data){
$(".level2").html(data);
}});*/
var sublist = JSON.parse(data);
var buttonlist = document.getElementsByClassName("level2")[0].childNodes;
var i=0, k=sublist.length, m=buttonlist.length;
for (i=0; i<k; i++){
buttonlist[i].innerHTML = sublist[i];
buttonlist[i].style.display = "inline-block"
}
for (i=k; i<m; i++){
buttonlist[i].style.display = "none";
}
}});

$(".materialselect .level2").show();
$(".materialselect .level3").hide();
commandarr = ["null", "null", "null", "false"];
commandarr[0] = buttoncontent;
}
else{
if(buttoncontent=="Assignments"||buttoncontent=="Books"||buttoncontent=="Notes"||buttoncontent=="Question Papers"){
$(".level3 button").css({"backgroundColor":"#562351", "borderStyle":"none", "color":"white"});
$(this).parent().css({"backgroundColor":"white", "border":"1px solid rgb(71,71,71)", "color":"rgb(71,71,71)"});
commandarr[2] = buttoncontent;
commandarr[3] = "true";
commandarrjson = JSON.stringify(commandarr);
$.ajax({
type:"POST",
data:{'commandarr':commandarrjson},
url:"/listdrivefiles",
success: function(data){
alert(data);
}});
}
else{
$(".level2 button").css({"backgroundColor":"#562351", "borderStyle":"none", "color":"white"});
$(".level3 button").css({"backgroundColor":"#562351", "borderStyle":"none", "color":"white"});
$(this).parent().css({"backgroundColor":"white", "border":"1px solid rgb(71,71,71)", "color":"rgb(71,71,71)"});
$(".materialselect .level3").show();
commandarr[2] = "null";
commandarr[1] = buttoncontent;
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions static/layout/styles/announcements.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.makeannouncement{
display:none;
}
1 change: 1 addition & 0 deletions static/subjectlist/sem1.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
["Chemistry","Electrical Eng.","English","Chemistry Lab","Mathematics I","Electrical Eng. Lab","Manufacturing Processes Lab"]
1 change: 1 addition & 0 deletions static/subjectlist/sem10.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
["Computer Network","NTP","MLP","Topology"]
7 changes: 7 additions & 0 deletions static/subjectlist/sem2.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
["PDS",
"Physics I",
"Mathematics II",
"Mechanics",
"PDS Lab",
"Physics Lab",
"Engineering Drawing"]
6 changes: 6 additions & 0 deletions static/subjectlist/sem3.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
["DAA",
"Economics",
"Transform Calculus",
"PDE",
"BS",
"EVS"]
2 changes: 1 addition & 1 deletion static/subjectlist/sem4.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
<button>NSOPDE</button>
<button>Basic EC</button>
<button>Soft Computing</button>
<button>Rural Development</button>
<button>Rural Development</button>
6 changes: 6 additions & 0 deletions static/subjectlist/sem4.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
["Probablity Stats",
"Discrete",
"NSOPDE",
"Basic EC",
"Soft Computing",
"Rural Development"]
6 changes: 6 additions & 0 deletions static/subjectlist/sem5.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
["Computer Organisation and Architechure",
"eltpd",
"Linear Algebra",
"Mathematical Methods",
"Object Oriented Prog.",
"Real Analysis"]
6 changes: 6 additions & 0 deletions static/subjectlist/sem6.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
["Advanced Numerical Tech.",
"Measure Theory and Integration",
"Modern Algebra",
"OR",
"OR Lab",
"Switching and Finite Automata"]
Loading