Passed
Push — master ( 8c7e96...605616 )
by torrua
01:16
created

app.site.generate_content()   C

Complexity

Conditions 10

Size

Total Lines 54
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 36
dl 0
loc 54
rs 5.9999
c 0
b 0
f 0
cc 10
nop 1

How to fix   Long Method    Complexity   

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:

Complexity

Complex classes like app.site.generate_content() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
# -*- coding: utf-8 -*-
2
# pylint: disable=C0116
3
4
"""
5
App's routes module
6
"""
7
8
import os
9
10
from flask import Blueprint, jsonify, render_template, request, redirect, url_for
11
from loglan_core import Event
12
13
from app.engine import Session
14
from app.site.compose.english_item import EnglishItem
15
from app.site.compose.loglan_item import LoglanItem, Composer
16
from app.site.functions import get_data
17
18
site_blueprint = Blueprint("site", __name__, template_folder="site/templates")
19
20
DEFAULT_SEARCH_LANGUAGE = os.getenv("DEFAULT_SEARCH_LANGUAGE", "log")
21
DEFAULT_HTML_STYLE = os.getenv("DEFAULT_HTML_STYLE", "normal")
22
MAIN_SITE = "http://www.loglan.org/"
23
24
25
@site_blueprint.route("/Articles/")
26
def redirect_articles():
27
    return redirect(url_for("articles"))
28
29
30
@site_blueprint.route("/Texts/")
31
def redirect_texts():
32
    return redirect(url_for("texts"))
33
34
35
@site_blueprint.route("/Sanpa/")
36
@site_blueprint.route("/Lodtua/")
37
def redirect_columns():
38
    return redirect(url_for("columns"))
39
40
41
@site_blueprint.route("/")
42
@site_blueprint.route("/home")
43
def home():
44
    article = get_data(MAIN_SITE).get("content").body.find("div", {"id": "content"})
45
    for bq in article.findAll("blockquote"):
46
        bq["class"] = "blockquote"
47
48
    for img in article.findAll("img"):
49
        img["src"] = MAIN_SITE + img["src"]
50
51
    return render_template("home.html", article="")
52
53
54
@site_blueprint.route("/articles")
55
def articles():
56
    article_block = get_data(MAIN_SITE).get("content")
57
    title = article_block.find("a", {"name": "articles"}).find_parent("h2")
58
    content = title.find_next("ol")
59
    return render_template("articles.html", articles=content, title=title.get_text())
60
61
62
@site_blueprint.route("/texts")
63
def texts():
64
    article_block = get_data(MAIN_SITE).get("content")
65
    title = article_block.find("a", {"name": "texts"}).find_parent("h2")
66
    content = title.find_next("ol")
67
    return render_template("articles.html", articles=content, title=title.get_text())
68
69
70
@site_blueprint.route("/columns")
71
def columns():
72
    article_block = get_data(MAIN_SITE)["content"]
73
    title = article_block.find("a", {"name": "columns"}).find_parent("h2")
74
    content = title.find_next("ul")
75
    return render_template("articles.html", articles=content, title=title.get_text())
76
77
78
@site_blueprint.route("/dictionary")
79
@site_blueprint.route("/dictionary/")
80
def dictionary():
81
    session = Session()
82
    events = session.query(Event).all()
83
    events = {event.id: event.name for event in reversed(events)}
84
    content = generate_content(request.args)
85
    return render_template("dictionary.html", content=content, events=events)
86
87
88
@site_blueprint.route("/how_to_read")
89
def how_to_read():
90
    return render_template("reading.html")
91
92
93
@site_blueprint.route("/submit_search", methods=["POST"])
94
def submit_search():
95
    return generate_content(request.form)
96
97
98
def strtobool(val):
99
    val = val.lower()
100
    if val in ("yes", "true", "t", "y", "1"):
101
        return True
102
    if val in ("no", "false", "f", "n", "0"):
103
        return False
104
    raise ValueError("Invalid boolean value")
105
106
107
def generate_content(data):
108
    word = data.get("word", str())
109
    search_language = data.get("language_id", DEFAULT_SEARCH_LANGUAGE)
110
    event_id = data.get("event_id", 1)
111
    is_case_sensitive = data.get("case_sensitive", False)
112
113
    if not word or not data:
114
        return jsonify(result="<div></div>")
115
116
    nothing = """
117
<div class="alert alert-secondary" role="alert" style="text-align: center;">
118
  %s
119
</div>
120
    """
121
122
    if isinstance(is_case_sensitive, str):
123
        is_case_sensitive = strtobool(is_case_sensitive)
124
125
    if search_language == "log":
126
        word_statement = LoglanItem.query_select_words(
127
            name=word, event_id=event_id, case_sensitive=is_case_sensitive
128
        )
129
        with Session() as session:
130
            word_result = session.execute(word_statement).scalars().all()
131
            result = Composer(
132
                words=word_result, style=DEFAULT_HTML_STYLE
133
            ).export_as_html()
134
135
        if not result:
136
            result = (
137
                nothing
138
                % f"There is no word <b>{word}</b> in Loglan. Try switching to English"
139
                f"{' or disable Case sensitive search' if is_case_sensitive else ''}."
140
            )
141
142
    elif search_language == "eng":
143
        definitions_statement = EnglishItem.select_definitions_by_key(
144
            key=word, event_id=event_id, case_sensitive=is_case_sensitive
145
        )
146
        with Session() as session:
147
            definitions_result = session.execute(definitions_statement).scalars().all()
148
149
            result = EnglishItem(
150
                definitions=definitions_result, key=word, style=DEFAULT_HTML_STYLE
151
            ).export_as_html()
152
        if not result:
153
            result = (
154
                nothing
155
                % f"There is no word <b>{word}</b> in English. Try switching to Loglan"
156
                f"{' or disable Case sensitive search' if is_case_sensitive else ''}."
157
            )
158
    else:
159
        result = nothing % f"Sorry, but nothing was found for <b>{word}</b>."
160
    return jsonify(result=result)
161
162
163
@site_blueprint.route("/<string:section>/", methods=["GET"])
164
@site_blueprint.route("/<string:section>/<string:article>", methods=["GET"])
165
def proxy(section: str = "", article: str = ""):
166
    url = f"{MAIN_SITE}{section}/{article}"
167
    content = get_data(url).get("content").body
168
169
    for bq in content.findAll("blockquote"):
170
        bq["class"] = "blockquote"
171
172
    for img in content.findAll("img"):
173
        img["src"] = MAIN_SITE + section + "/" + img["src"]
174
175
    name_of_article = content.h1.extract().get_text()
176
    return render_template(
177
        "article.html", name_of_article=name_of_article, article=content, title=section
178
    )
179