Passed
Push — master ( 8b1b4c...c30160 )
by torrua
01:18
created

app.site.routes   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 217
Duplicated Lines 12.44 %

Importance

Changes 0
Metric Value
wmc 32
eloc 151
dl 27
loc 217
rs 9.84
c 0
b 0
f 0

16 Functions

Rating   Name   Duplication   Size   Complexity  
A submit_search() 0 3 1
A articles() 9 9 1
A texts() 9 9 1
A how_to_read() 0 3 1
A redirect_articles() 0 3 1
A search_log() 0 17 3
A columns() 9 9 1
A search_all() 0 9 3
A search_eng() 0 22 3
A dictionary() 0 11 2
A redirect_texts() 0 3 1
A home() 0 13 3
A strtobool() 0 7 3
A redirect_columns() 0 4 1
A generate_content() 0 20 4
A proxy() 0 18 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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