Marthee commited on
Commit
0b9e59d
·
1 Parent(s): 0aba0d5

Upload API.py

Browse files
Files changed (1) hide show
  1. API.py +185 -0
API.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ # !pip install requests
3
+
4
+ # %%
5
+ # pip install pygsheets
6
+
7
+ # %%
8
+ import requests
9
+ import json
10
+ import pandas as pd
11
+
12
+ # %% [markdown]
13
+ # ## GoogleSheet
14
+
15
+ # %%
16
+ # from __future__ import print_function
17
+ from googleapiclient.discovery import build
18
+ from google.oauth2 import service_account
19
+ import pygsheets
20
+ def AuthorizeGoogleSheets():
21
+ SCOPES = [
22
+ 'https://www.googleapis.com/auth/spreadsheets',
23
+ 'https://www.googleapis.com/auth/drive'
24
+ ]
25
+ credentials = service_account.Credentials.from_service_account_file('credentials.json', scopes=SCOPES)
26
+ spreadsheet_service = build('sheets', 'v4', credentials=credentials)
27
+ drive_service = build('drive', 'v3', credentials=credentials)
28
+ gc = pygsheets.authorize(custom_credentials=credentials, client_secret='credentials.json')
29
+ return spreadsheet_service,drive_service,gc
30
+
31
+ # %%
32
+ def createSheet():
33
+ spreadsheet_service,drive_service,gc=AuthorizeGoogleSheets()
34
+ #create sheet
35
+ titles=gc.spreadsheet_titles()
36
+ if 'API tables Output' in titles:
37
+ ws=gc.open(str('API tables Output'))
38
+ spreadsheetId=ws.id
39
+ else:
40
+ spreadsheet_details = {
41
+ 'properties': {
42
+ 'title': 'API tables Output'
43
+ }
44
+ }
45
+ sheet = spreadsheet_service.spreadsheets().create(body=spreadsheet_details,
46
+ fields='spreadsheetId').execute()
47
+
48
+ spreadsheetId = sheet.get('spreadsheetId')
49
+ permission1 = {
50
+ 'type': 'anyone',
51
+ 'role': 'writer',
52
+ # 'emailAddress': 'marthe.adr@gmail.com'
53
+ }
54
+ drive_service.permissions().create(fileId=spreadsheetId, body=permission1).execute()
55
+
56
+ ws = gc.open_by_key(spreadsheetId)
57
+ projectNamesSheet = ws.worksheet(0)
58
+
59
+ projectNamesSheet.title='Project Names'#first sheet
60
+ ws.add_worksheet("Project Parts") # secondsheet
61
+ ws.add_worksheet("Sections") # thirdsheet
62
+ print('SPREADHSEET IDDDD=====',spreadsheetId)
63
+ return ws,gc,spreadsheetId
64
+
65
+
66
+ # %% [markdown]
67
+ # # **New** API
68
+
69
+ # %%
70
+ def APIValues():
71
+ query={'loginname':'adr','password':'Tameen'}
72
+ #token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiQURSIiwibmJmIjoiMTY4MDg1OTgzMyIsImV4cCI6IjE2ODA5MDMwMzMifQ.-FULhKD_M-cyIdSMMIYDlEo9DoZtc00yIlyXIPuyLZI"
73
+ head={'Content-Type':'application/json'}
74
+ response=requests.post(url="https://consoletest.trevorsadd.co.uk/account/login",json=query,headers=head)
75
+ key=response.text
76
+
77
+ head={'Content-Type':'application/json;charset=UTF-8',"Authorization":'Bearer {}'.format(key)}
78
+ response=requests.post(url="https://consoletest.trevorsadd.co.uk/project/getprojectslist",json=query,headers=head)
79
+ dict1=response.json()
80
+ return dict1
81
+
82
+ # %% [markdown]
83
+ # ### Generate Tables
84
+
85
+ # %%
86
+ def GenerateTables():
87
+ dict1=APIValues()
88
+ ##First table should ONLY contain: All project Ids and names
89
+ #Second table should contain ProjId,ProjectPartId,ProjectPart
90
+ #Third table should contain ProjId,ProjectPartId,ProjectSection
91
+ table1=pd.DataFrame(columns= ['ProjectId','ProjectName'])
92
+ table2=pd.DataFrame(columns= ['ProjectId','ProjectPartId','ProjectPart'])
93
+ table3=pd.DataFrame(columns= ['ProjectId','ProjectPartId','ProjectSection'])
94
+ for item in dict1:
95
+ table1 = pd.concat([table1, pd.DataFrame([[item.get('id'),item.get('projectname')]], columns=table1.columns)], ignore_index=True)
96
+ projectPartsList=item.get('projectparts')
97
+ for part in projectPartsList:
98
+ table2= pd.concat([table2,pd.DataFrame([[item.get('id'),part.get('id'),part.get('name')]], columns=table2.columns)], ignore_index=True)
99
+ sections=part.get('projectsections')
100
+ for section in sections:
101
+ table3= pd.concat([table3,pd.DataFrame([[item.get('id'),section.get('projectPartId'),section.get('section')]], columns=table3.columns)], ignore_index=True)
102
+ return table1,table2,table3
103
+
104
+ # %% [markdown]
105
+ # Set Tables to Sheets
106
+
107
+ # %%
108
+
109
+ def AppendtablestoSheets(ws):
110
+
111
+ table1,table2,table3= GenerateTables()
112
+ projectNamesSheet=ws.worksheet_by_title('Project Names')
113
+ projectPartsSheet=ws.worksheet_by_title('Project Parts')
114
+ projectSectionsSheet=ws.worksheet_by_title('Sections')
115
+ projectNamesSheet.clear()
116
+ projectPartsSheet.clear()
117
+ projectSectionsSheet.clear()
118
+ #append tables to google sheets
119
+ projectNamesSheet.set_dataframe(start='A1',df=table1)
120
+ projectPartsSheet.set_dataframe(start='A1',df=table2)
121
+ projectSectionsSheet.set_dataframe(start='A1',df=table3)
122
+
123
+ # %%
124
+ #-------------------------------------------------------------------------------CALL THIS FUNCTION TO BEGIN----------------------------------------------------------------------
125
+ #--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
126
+ def getPrjNames():
127
+ ws,gc,spreadsheetId=createSheet()
128
+ AppendtablestoSheets(ws)
129
+ projectNamesSheet=ws.worksheet_by_title('Project Names')
130
+ prjnamesfromSheet=projectNamesSheet.get_col(2, returnas='matrix', include_tailing_empty=False)
131
+ # print(prjnamesfromSheet[2])
132
+ return prjnamesfromSheet[1:]
133
+
134
+ # %%
135
+ def getprjParts(chosenprjname):
136
+ #Get projectName Id
137
+ ws,gc,spreadsheetId=createSheet()
138
+ projectNamesSheet=ws.worksheet_by_title('Project Names')
139
+ prjnamesfromSheet= getPrjNames()
140
+ index=prjnamesfromSheet.index(chosenprjname.replace('"', ''))
141
+ # index,indexE = [o for o, x in prjnamesfromSheet if x == str(chosenprjname)] #==clicked value
142
+ prjnameId=projectNamesSheet.cell((index+2 ,1)).value #retrieved Id
143
+ print('iddd',prjnameId)
144
+ #Get projectParts
145
+ projparts=[]
146
+ projectPartsSheet=ws.worksheet_by_title('Project Parts')
147
+ prjpartsfromSheet=projectPartsSheet.get_col(1, returnas='matrix', include_tailing_empty=False)
148
+
149
+ indices = [o for o, x in enumerate(prjpartsfromSheet[1:]) if x == prjnameId] #==clicked value
150
+ print('ind',indices)
151
+ for index in indices:
152
+ projparts.append([projectPartsSheet.cell((index+2 ,3)).value, projectPartsSheet.cell((index+2 ,2)).value]) #retrieved Id
153
+ return projparts
154
+
155
+ # %%
156
+ def getprjSections(chosenpart):
157
+ #GetprojectSections
158
+ ws,gc,spreadsheetId=createSheet()
159
+ projsections=[]
160
+ projectSectionsSheet=ws.worksheet_by_title('Sections')
161
+ prjsectionsfromSheet=projectSectionsSheet.get_col(2, returnas='matrix', include_tailing_empty=False)
162
+ chosenpart=chosenpart.replace('"', '')
163
+ indices2 = [o for o, x in enumerate(prjsectionsfromSheet) if x == chosenpart] #part clicked on
164
+ print('indices2',indices2)
165
+ for index in indices2:
166
+ projsections.append(projectSectionsSheet.cell((index+2 ,3)).value) #retrieved Id
167
+ return projsections
168
+
169
+ # %%
170
+ # tableTrial=pd.DataFrame(data=[[0,'0x','part1'],[0,'1x','part2']],columns= ['ProjectId','ProjectPartId','ProjectPart'])
171
+ # tableTrial3=pd.DataFrame(data=[[0,'0x','0.0'],[0,'0x','1.0'],[1,'1x','3.1']],columns= ['ProjectId','ProjectPartId','ProjectSection'])
172
+
173
+
174
+ # %%
175
+ #Ex: proj 1 ekhtrnah fl dropdown-->go search in table where column of names has the name proj 1 , get id of this proj1 (same row and return it to this line)
176
+ #get parts
177
+ # partsList=list(tableTrial.loc[tableTrial['ProjectId'].isin([id])].get('ProjectPart'))
178
+ #get sections
179
+ # sectionsList=list(tableTrial3.loc[tableTrial3['ProjectId'].isin([projid]) & tableTrial3['projpartid'].isin(['0x'])].get('ProjectSection'))
180
+ # tableTrial3
181
+
182
+ # %%
183
+
184
+
185
+