Skip to content

Commit a96d082

Browse files
authored
Added export to Yandex Disk (#33)
* added export to yandex disk * fixed
1 parent 62c10e9 commit a96d082

File tree

15 files changed

+104
-23
lines changed

15 files changed

+104
-23
lines changed

checker_export/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,5 @@
33
## Инструкция по запуску скрипта
44

55
```bash
6-
python3 exporter.py [-h] [--google_token GOOGLE_TOKEN] --checker_token CHECKER_TOKEN [--checker_filter CHECKER_FILTER] --table_id TABLE_ID --sheet_id SHEET_ID
6+
python3 exporter.py [-h] [--google_token GOOGLE_TOKEN] --checker_token CHECKER_TOKEN [--checker_filter CHECKER_FILTER] --table_id TABLE_ID --sheet_id SHEET_ID [--yandex_token YANDEX_TOKEN --yandex_path YANDEX_PATH]
77
```

checker_export/exporter.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import requests
66
from io import StringIO
77
import urllib.parse
8-
8+
import yadisk
99

1010
INT_MASS = [{
1111
"one": 1,
@@ -24,10 +24,12 @@ def parse_args():
2424
parser.add_argument('--checker_filter', type=str, required=False, help='Specify filter for slides-checker')
2525
parser.add_argument('--table_id', type=str, required=True, help='Specify Google sheet document id (can find in url)')
2626
parser.add_argument('--sheet_id', type=str, required=True, help='Specify title for a sheet in a document in which data will be printed')
27+
parser.add_argument('--yandex_token', type=str, required=False, help='Specify Yandex token from https://oauth.yandex.ru/client/new application')
28+
parser.add_argument('--yandex_path', type=str, required=False, help='Specify output filename on Yandex Disk')
2729
args = parser.parse_args()
2830
return args
2931

30-
def write_data_to_table(checker_token, checker_filter, google_token, table_id, sheet_id):
32+
def write_data_to_table(checker_token, checker_filter, google_token, table_id, sheet_id, yandex_token=None, yandex_path=None):
3133
if google_token and sheet_id and table_id:
3234
gc = pygsheets.authorize(service_file=google_token)
3335
sh = gc.open_by_key(table_id)
@@ -44,11 +46,18 @@ def write_data_to_table(checker_token, checker_filter, google_token, table_id, s
4446
else:
4547
content = pd.DataFrame(INT_MASS)
4648
wk_content.set_dataframe(content, 'A1', copy_head=True)
49+
if yandex_token and yandex_path:
50+
try:
51+
client = yadisk.YaDisk(token=yandex_token)
52+
client.upload(str(csv_path), yandex_path)
53+
print(f'Check data in your disk! Path to the table is: {yandex_path}')
54+
except Exception as e:
55+
print(f'Saving data to Yandex Disk failed. Error message: {e}')
4756

4857

4958
def main():
5059
args = parse_args()
51-
write_data_to_table(args.checker_token, args.checker_filter, args.google_token, args.table_id, args.sheet_id)
60+
write_data_to_table(args.checker_token, args.checker_filter, args.google_token, args.table_id, args.sheet_id, args.yandex_token, args.yandex_path)
5261

5362

5463
if __name__ == "__main__":

checker_export/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ requests==2.27.1
22
requests-oauthlib==1.3.1
33
pygsheets==2.0.5
44
pandas==1.4.3
5+
yadisk==1.2.19

moodle_export/README.md

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,20 @@
99
Чтобы получить данные в файл csv следует прописать:
1010

1111
``` python3 grades_parser.py --moodle_token "your token" --url http://e.moevm.info --course_id "your course id"[,"id",..] --csv_path "name of file" [--percentages] [--options github]```
12-
```
12+
1313

1414
Если хотите получить не баллы за задания, а проценты, то нужно добавить параметр ``` --percentages ```.
1515

1616
Также в таблицу можно добавить опциональные графы по тегу ``` --options ``` без пробелов через запятую.
1717
Пока из доступных есть опциональное поле ``` github ```.
1818

19-
Получение данных и в файл и в Google таблицу:
19+
Получение данных и в файл, и в Google таблицу:
20+
21+
```python3 grades_parser.py grades_parser --moodle_token "your token" --url http://e.moevm.info --course_id "your course id"[,"id",..] --csv_path "name of file" [--percentages] [--options github] --google_token "your google token" --table_id "your table id"[,"id",..] [--sheet_id "name of sheet"[,"name",..]] ```
2022

21-
``` python3 grades_parser.py grades_parser --moodle_token "your token" --url http://e.moevm.info --course_id "your course id"[,"id",..] --csv_path "name of file" [--percentages] [--options github] --google_token "your google token" --table_id "your table id"[,"id",..] [--sheet_id "name of sheet"[,"name",..]] ```
22-
```
23+
Получение данных и в файл, и на Яндекс Диск:
24+
25+
```python3 grades_parser.py grades_parser --moodle_token "your token" --url http://e.moevm.info --course_id "your course id"[,"id",..] --csv_path grades --yandex_token "Your yandex token" --yandex_path grades```
2326

2427
Получение ``` .json ``` файла для google_token будет описано ниже.
2528

@@ -56,6 +59,15 @@
5659

5760
В таблице Service Accounts будет запись, нажимаем на нее. Сверху будет вкладка keys. Add key -> Create new key -> json -> create. Получаем нужный json файл.
5861

62+
63+
## Получение токена для работы с Yandex Disk.
64+
65+
1. Необходимо создать приложение на [Yandex Приложения](https://oauth.yandex.ru/client/new).
66+
В доступе к данным необходимо указать "Чтение всего диска" и "Запись в любом месте на диске", поле URL заполнить произвольно, например: ```http://127.0.0.1:123/test```.
67+
2. Чтобы получить токен, необходимо скопировать client_id и перейти по ссылке вида
68+
```https://oauth.yandex.ru/authorize?response_type=token&client_id=<идентификатор приложения>``` и скопировать access_token из появившегося на экране запроса.
69+
70+
5971
## Как подключиться к таблице, которая может дать права редактора для определенной почты.
6072

6173
В полученном json файле есть почта некоторого формата, если в гугл таблице дать право редактора этой почте, приложение будет сохранять данные в таблицу.

moodle_export/args_parser.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ def arg_parser():
1010
parser.add_argument('--google_token', type=str, required=False, help='Specify path to google token file')
1111
parser.add_argument('--table_id', type=lambda s: [i for i in s.split(',')], required=False, help='Specify Google sheet document id (can find in url)')
1212
parser.add_argument('--sheet_id', type=lambda s: [i for i in s.split(',')], required=False, help='Specify title for a sheet in a document in which data will be printed')
13+
parser.add_argument('--yandex_token', type=str, required=False, help='Specify Yandex token from https://oauth.yandex.ru/client/new application')
14+
parser.add_argument('--yandex_path', type=str, required=False, help='Specify output filename on Yandex Disk')
1315
parser.add_argument('--percentages', required=False, action='store_true', help='If set then grades will be printed as percentages')
1416
parser.add_argument('--options', type=lambda s: [i for i in s.split(',')], required=False, help='Specify options for column names')
1517
args = parser.parse_args()

moodle_export/grades_parser.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import datetime
66
import csv
77
import args_parser
8+
import yadisk
89

910
HEADERS = {
1011
"Content-Type": "charset=iso-8859"
@@ -146,7 +147,17 @@ def main():
146147
sheet_id = 'course ' + course_id
147148

148149
sheets.write_data_to_table(csv_path, args.google_token, table_id, sheet_id)
149-
150+
151+
# write data to yandex disk
152+
if args.yandex_token and args.yandex_path:
153+
yandex_path = args.yandex_path + '_' + args.course_id + '.csv'
154+
try:
155+
client = yadisk.YaDisk(token=args.yandex_token)
156+
client.upload(csv_path, yandex_path)
157+
print(f'Course {args.course_id} saved to Disk! Path to the table is: {yandex_path}')
158+
print('********************************************************')
159+
except Exception as e:
160+
print(f'Course {args.course_id}: saving data to Yandex Disk failed. Error message: {e}')
150161

151162
if __name__ == "__main__":
152163
main()

moodle_export/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ requests==2.27.1
22
requests-oauthlib==1.3.1
33
pygsheets==2.0.5
44
pandas==1.4.3
5+
yadisk==1.2.19

stepik_export/README.md

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,13 @@
1111
``` python3 stepik_parser.py --client_id "Your client id" --client_secret "Your client secret" --url https://stepik.org:443/api --course_id "Your course id" --class_id "Your class id" --csv_path grades ```
1212

1313

14-
Получение данных и в файл и в Google таблицу:
14+
Получение данных и в файл, и в Google таблицу:
1515

1616
``` python3 stepik_parser.py --client_id "Your client id" --client_secret "Your client secret" --url https://stepik.org:443/api --course_id "Your course id" --class_id "Your class id" --csv_path grades --google_token "Path to your google token" --table_id "Your table id" [--sheet_id "Name of sheet"] ```
1717

18+
Получение данных и в файл, и на Яндекс Диск:
19+
20+
```python3 grades_parser.py grades_parser --moodle_token "your token" --url http://e.moevm.info --course_id "your course id"[,"id",..] --csv_path grades --yandex_token "Your yandex token" --yandex_path grades```
1821

1922
Получение ``` .json ``` файла для google_token будет описано ниже.
2023

@@ -53,6 +56,15 @@
5356

5457
В таблице Service Accounts будет запись, нажимаем на нее. Сверху будет вкладка keys. Add key -> Create new key -> json -> create. Получаем нужный json файл.
5558

59+
60+
## Получение токена для работы с Yandex Disk.
61+
62+
1. Необходимо создать приложение на [Yandex Приложения](https://oauth.yandex.ru/client/new).
63+
В доступе к данным необходимо указать "Чтение всего диска" и "Запись в любом месте на диске", поле URL заполнить произвольно, например: ```http://127.0.0.1:123/test```.
64+
2. Чтобы получить токен, необходимо скопировать client_id и перейти по ссылке вида
65+
```https://oauth.yandex.ru/authorize?response_type=token&client_id=<идентификатор приложения>``` и скопировать access_token из появившегося на экране запроса.
66+
67+
5668
## Как подключиться к таблице, которая может дать права редактора для определенной почты.
5769

5870
В полученном json файле есть почта некоторого формата, если в гугл таблице дать право редактора этой почте, приложение будет сохранять данные в таблицу.

stepik_export/args_parser.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ def arg_parser():
1212
parser.add_argument('--google_token', type=str, required=False, help='Specify path to google token file')
1313
parser.add_argument('--table_id', type=str, required=False, help='Specify Google sheet document id (can find in url)')
1414
parser.add_argument('--sheet_id', type=str, required=False, help='Specify title for a sheet in a document in which data will be printed')
15+
parser.add_argument('--yandex_token', type=str, required=False, help='Specify Yandex token from https://oauth.yandex.ru/client/new application')
16+
parser.add_argument('--yandex_path', type=str, required=False, help='Specify output filename on Yandex Disk')
1517
args = parser.parse_args()
1618
return args
1719

stepik_export/requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@ requests==2.27.1
22
requests-oauthlib==1.3.1
33
pygsheets==2.0.5
44
pandas==1.4.3
5-
5+
yadisk==1.2.19

stepik_export/stepik_parser.py

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import json
55
import requests
66
import csv
7-
7+
import yadisk
88

99
# check status code and if request is valid
1010
def check_access(response):
@@ -124,17 +124,27 @@ def main():
124124
print(f'Saved to csv file: {csv_path}')
125125

126126
# write data to sheets document
127-
if args.google_token:
128-
if args.table_id:
129-
print('Send data to Google Sheets')
130-
if args.sheet_id:
131-
sheet_id = args.sheet_id
132-
else:
133-
sheet_id = 'course ' + args.course_id
134-
sheets.write_data_to_table(csv_path, args.google_token, args.table_id, sheet_id)
135-
print(f'Check data in your table! List name is: {sheet_id}')
127+
if args.google_token and args.table_id:
128+
print('Send data to Google Sheets')
129+
if args.sheet_id:
130+
sheet_id = args.sheet_id
131+
else:
132+
sheet_id = 'course ' + args.course_id
133+
sheets.write_data_to_table(csv_path, args.google_token, args.table_id, sheet_id)
134+
print(f'Check data in your table! List name is: {sheet_id}')
135+
print('********************************************************')
136+
137+
# write data to yandex disk
138+
if args.yandex_token and args.yandex_path:
139+
yandex_path = args.yandex_path + '_' + args.course_id + '.csv'
140+
try:
141+
client = yadisk.YaDisk(token=args.yandex_token)
142+
client.upload(csv_path, yandex_path)
143+
print(f'Check data in your disk! Path to the table is: {yandex_path}')
136144
print('********************************************************')
137-
145+
except Exception as e:
146+
print(f'Saving data to Yandex Disk failed. Error message: {e}')
147+
exit(1)
138148

139149
if __name__ == "__main__":
140150
main()

stepik_progress_export/README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,12 @@
1313
- `course_id` - ID курса (отсюда: https://stepik.org/course/63054/syllabus)
1414
- `class_id` - ID класса (отсюда: https://stepik.org/class/33587/gradebook)
1515
- `csv_path` - путь до CSV
16+
- `yandex_token` - токен доступа Yandex App (отсюда: https://oauth.yandex.ru/client/new)
17+
- `yandex_path` - путь до CSV на Диске
1618

1719
Например:
1820
```bash
19-
docker-compose run parser --client_id xxx --client_secret xxx --course_id 63054 --class_id 33587 --csv_path ./results/kek.csv
21+
docker-compose run parser --client_id xxx --client_secret xxx --course_id 63054 --class_id 33587 --csv_path ./results/kek.csv --yandex_token xxx --yandex_path kek.csv
2022
```
2123

2224
Будет создан CSV-файл со следующим форматов:

stepik_progress_export/args_parser.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,12 @@ def arg_parser():
1616
parser.add_argument(
1717
"--csv_path", type=str, required=True, help="Specify path to output csv file"
1818
)
19+
parser.add_argument(
20+
'--yandex_token', type=str, required=False,
21+
help='Specify Yandex token from https://oauth.yandex.ru/client/new application'
22+
)
23+
parser.add_argument(
24+
'--yandex_path', type=str, required=False, help='Specify output filename on Yandex Disk'
25+
)
1926
args = parser.parse_args()
2027
return args

stepik_progress_export/main.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import numpy as np
55
import pandas as pd
66
import requests
7+
import yadisk
78
from tqdm import tqdm
89

910
from args_parser import arg_parser
@@ -173,10 +174,20 @@ def postprocess_df(df):
173174

174175
return new_df
175176

177+
def load_to_yandex_disk(csv_path, dest_path, token):
178+
try:
179+
client = yadisk.YaDisk(token=token)
180+
client.upload(csv_path, dest_path)
181+
print(f'Check data in your disk! Path to the table is: {dest_path}')
182+
except Exception as e:
183+
print(f'Saving data to Yandex Disk failed. Error message: {e}')
184+
return
176185

177186
if __name__ == "__main__":
178187
args = arg_parser()
179188
token = get_access_token(client_id=args.client_id, client_secret=args.client_secret)
180189
df = get_info(access_token=token, course_id=args.course_id, class_id=args.class_id)
181190
new_df = postprocess_df(df)
182191
new_df.to_csv(args.csv_path, index=False)
192+
if args.yandex_token and args.yandex_path:
193+
load_to_yandex_disk(args.csv_path, args.yandex_path, args.yandex_token)

stepik_progress_export/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ pandas==1.4.2
22
numpy==1.22.3
33
tqdm==4.64.0
44
requests==2.27.1
5+
yadisk==1.2.19

0 commit comments

Comments
 (0)