Passed
Pull Request — main (#4)
by Bartosz
01:15
created

build.modules.pull_config.pull_config.get_config()   B

Complexity

Conditions 7

Size

Total Lines 65
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 45
dl 0
loc 65
rs 7.4
c 0
b 0
f 0
cc 7
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
import pandas as pd
2
import os.path
3
from googleapiclient.discovery import build
4
from google_auth_oauthlib.flow import InstalledAppFlow
5
from google.auth.transport.requests import Request
6
from google.oauth2.credentials import Credentials
7
import json
8
from modules import get_settings
9
10
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
11
SAMPLE_RANGE_NAME = 'A1:AA68'
12
CREDENTIALS_FILE = 'pull_config/credentials/client_secret.com.json '
13
14
SAMPLE_SPREADSHEET_ID_input = get_settings.get_settings("EXCEL_ID")
15
16
17
def import_from_sheets():
18
    """
19
20
    :return:
21
    :rtype:
22
    """
23
    creds = None
24
    # The file token.json stores the user's access and refresh tokens, and is
25
    # created automatically when the authorization flow completes for the first time
26
    if os.path.exists('token.json'):
27
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
28
    # If there are no (valid) credentials available, let the user log in
29
    if not creds or not creds.valid:
30
        if creds and creds.expired and creds.refresh_token:
31
            creds.refresh(Request())
32
        else:
33
            flow = InstalledAppFlow.from_client_secrets_file(
34
                CREDENTIALS_FILE, SCOPES)
35
            creds = flow.run_local_server(port=0)
36
        # Save the credentials for the next run
37
        with open('token.json', 'w') as token:
38
            token.write(creds.to_json())
39
40
    service = build('sheets', 'v4', credentials=creds)
41
42
    # Call the Sheets API
43
    sheet = service.spreadsheets()
44
    result_input = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID_input, range=SAMPLE_RANGE_NAME).execute()
45
    values_input = result_input.get('values', [])
46
47
    if not values_input:
48
        print('No data found.')
49
    return values_input
50
51
52
def get_config():
53
    """
54
55
    :return:
56
    :rtype:
57
    """
58
    pd.set_option('mode.chained_assignment', None)
59
    print("Loading data")
60
    values_input = import_from_sheets()
61
    df = pd.DataFrame(values_input[1:], columns=values_input[0])
62
63
    print("Transforming data")
64
    monsters_df = df[["name", "type"]]
65
    monsters_df["type"] = pd.to_numeric(df["type"])
66
67
    triggers = df.drop(['name', 'role', 'type', 'id'], axis=1)
68
    triggers = triggers.applymap(lambda s: s.lower() if type(s) == str else s)
69
    # triggers = triggers.applymap(lambda s: unidecode.unidecode(s) if type(s) == str else s)
70
71
    triggers_list = []
72
    for row in triggers.itertuples(index=False):
73
        helpt = pd.Series(row)
74
        helpt = helpt[~helpt.isna()]
75
        # Drop empty strings
76
        helpt = pd.Series(filter(None, helpt))
77
        # Copy strings with spaces without keeping them
78
        for trigger in helpt:
79
            trigger_nospace = trigger.replace(' ', '')
80
            helpt = helpt.append(pd.Series(trigger_nospace))
81
        helpt = helpt.drop_duplicates()
82
        triggers_list.append(helpt)
83
84
    print("Creating trigger structure")
85
    triggers_def = []
86
    for i in triggers_list:
87
        triggers_def.append(list(i))
88
    triggers_def_series = pd.Series(triggers_def)
89
    monsters_df.insert(loc=0, column='triggers', value=triggers_def_series)
90
91
    print("Creating output")
92
93
    types = {'id': [4, 3, 2, 1, 0], 'label': ["Common", "Event0", "Event1", "Legendary", "Rare"]}
94
    types_df = pd.DataFrame(data=types)
95
    milestones = {'total': [150, 1000, 2000, 3000, 4000, 5000],
96
                  'name': ["Rare Spotter", "Pepega Spotter", "Pog Spotter", "Pogmare Spotter", "Legendary Spotter",
97
                           "Mythic Spotter"]}
98
    milestones_df = pd.DataFrame(data=milestones)
99
    json_final = {'milestones': milestones_df, 'types': types_df, 'commands': monsters_df}
100
101
    # convert dataframes into dictionaries
102
    data_dict = {
103
        key: json_final[key].to_dict(orient='records')
104
        for key in json_final
105
    }
106
107
    # write to disk
108
    with open('server_files/config.json', 'w', encoding='utf8') as f:
109
        json.dump(
110
            data_dict,
111
            f,
112
            indent=4,
113
            ensure_ascii=False,
114
            sort_keys=False
115
        )
116
    print(".json saved")
117
118
119
if __name__ == "__main__":
120
    get_config()
121