Skip to content

Commit 7f6699b

Browse files
Merge pull request flaskcwg#83 from mmdbalkhi/pr
lint the code and add logging to static.py
2 parents 8a20120 + ce63d97 commit 7f6699b

File tree

8 files changed

+206
-163
lines changed

8 files changed

+206
-163
lines changed

CONTRIBUTING.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,3 @@
5252
```
5353

5454
* Add your fork as a remote to push your work to. Replace {username} with your username. This names the remote "fork", the default Pallets remote is "origin".
55-

docs/serve.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,15 @@
44

55
# tasklist
66
# /IM py37.exe /F
7-
#
7+
#
88
hostname = socket.gethostname()
99
PORT = 8000
1010
IP = socket.gethostbyname(hostname)
1111

1212
Handler = http.server.SimpleHTTPRequestHandler
13-
with socketserver.TCPServer(('', PORT), Handler) as httpd:
13+
with socketserver.TCPServer(("", PORT), Handler) as httpd:
1414
print(f"Serving on: {IP}:{PORT}")
1515
try:
1616
httpd.serve_forever()
1717
except KeyboardInterrupt:
1818
print("Shutting down serve.py...")
19-

info.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,9 +169,11 @@
169169
"retired": "n"
170170
},
171171
"mmdbalkhi":{
172-
"name": "Mohamad Balkhi ",
172+
"name": "Komeil Parseh",
173173
"bio": [],
174+
"links": {"GitHub":"https://github.com/mmdbalkhi", "twitter":"https://twitter.com/mmdbalkhi"},
174175
"volunteer": {
176+
"code": {},
175177
"translation":{
176178
"lang": "persian",
177179
"coordinator": "y"

manager.py

Lines changed: 69 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,105 +1,119 @@
11
import datetime
2+
import ntpath
23
import shutil
34

45
import markdown
5-
import ntpath
66
from flask import Flask, redirect, render_template, request, url_for
7+
78
from manager_utils import *
89
from settings import BLOG_CATEGORIES
910

10-
app = Flask(__name__, template_folder='manager_app/templates', static_folder='manager_app/static')
11+
app = Flask(
12+
__name__,
13+
template_folder="manager_app/templates",
14+
static_folder="manager_app/static",
15+
)
1116
app.config.update(
12-
DEBUG=True,
13-
SECRET_KEY=b'sC&wJQ35C3jR',
14-
SQLALCHEMY_TRACK_MODIFICATIONS = False
17+
DEBUG=True, SECRET_KEY=b"sC&wJQ35C3jR", SQLALCHEMY_TRACK_MODIFICATIONS=False
1518
)
1619

20+
1721
@app.route("/")
1822
def index():
1923
posts = get_posts()
20-
resources = info['resources']
24+
resources = info["resources"]
2125
current_day = datetime.date.today()
2226
today = datetime.date.strftime(current_day, "%B %d, %Y")
2327

24-
return render_template("index.html", today=today,
25-
b_categories=BLOG_CATEGORIES,
26-
posts=posts,
27-
resources=resources)
28+
return render_template(
29+
"index.html",
30+
today=today,
31+
b_categories=BLOG_CATEGORIES,
32+
posts=posts,
33+
resources=resources,
34+
)
35+
2836

29-
@app.route("/save_post", methods=['POST'])
37+
@app.route("/save_post", methods=["POST"])
3038
def save_post():
3139
# Validate empty fields?
32-
post_type = request.form['post-type']
33-
if request.form['post-type'] == 'blog':
40+
post_type = request.form["post-type"]
41+
if request.form["post-type"] == "blog":
3442
data = {
35-
'title' : request.form['b_title'],
36-
'summary' : request.form['b_summ'],
37-
'authors' : get_comma_separated(request.form['b_authors']),
38-
'date' : request.form['b_date'],
39-
'tags' : get_comma_separated(request.form['b_tags']),
40-
'slug' : request.form['b_slug'],
41-
'post_content' : request.form['post_content'],
42-
'category' : request.form['b_category']
43+
"title": request.form["b_title"],
44+
"summary": request.form["b_summ"],
45+
"authors": get_comma_separated(request.form["b_authors"]),
46+
"date": request.form["b_date"],
47+
"tags": get_comma_separated(request.form["b_tags"]),
48+
"slug": request.form["b_slug"],
49+
"post_content": request.form["post_content"],
50+
"category": request.form["b_category"],
4351
}
4452

45-
ensure_authors(data['authors'])
53+
ensure_authors(data["authors"])
4654
save_md_file(post_type, data)
4755

4856
else:
4957
data = {
50-
'slug' : request.form['f_slug'],
51-
'tags' : get_comma_separated(request.form['f_tags']),
52-
'title' : request.form['f_title'],
53-
'post_content' : request.form['post_content']
58+
"slug": request.form["f_slug"],
59+
"tags": get_comma_separated(request.form["f_tags"]),
60+
"title": request.form["f_title"],
61+
"post_content": request.form["post_content"],
5462
}
5563
save_md_file(post_type, data)
56-
64+
5765
return 'Post saved! Remember re-build the site to see the changes. <a href="/">Return</a>'
58-
59-
@app.route("/action/<string:ptype>/<string:option>/<string:post>", methods=['GET'])
66+
67+
68+
@app.route("/action/<string:ptype>/<string:option>/<string:post>", methods=["GET"])
6069
def postman(ptype, option, post):
61-
if option == 'edit':
70+
if option == "edit":
6271
posts = get_posts()
6372

64-
if ptype == 'blog':
65-
filename, category = post.split('@')
66-
blog_post_path = os.path.join('data', 'blog', category, filename)
67-
73+
if ptype == "blog":
74+
filename, category = post.split("@")
75+
blog_post_path = os.path.join("data", "blog", category, filename)
76+
6877
body, metadata = parse_file(blog_post_path)
6978

7079
postdata = {
71-
"title" : metadata["title"][0],
72-
"summary" : metadata["summary"][0],
73-
"authors" : ','.join(metadata["authors"]),
74-
"date" : metadata["date"][0],
75-
"tags" : ','.join(metadata["tags"]),
76-
"slug" : metadata["slug"][0],
77-
"category" : category,
78-
"content": body
80+
"title": metadata["title"][0],
81+
"summary": metadata["summary"][0],
82+
"authors": ",".join(metadata["authors"]),
83+
"date": metadata["date"][0],
84+
"tags": ",".join(metadata["tags"]),
85+
"slug": metadata["slug"][0],
86+
"category": category,
87+
"content": body,
7988
}
80-
81-
return render_template("edit_page.html", postdata=postdata, posts=posts, edit_type='blog')
89+
90+
return render_template(
91+
"edit_page.html", postdata=postdata, posts=posts, edit_type="blog"
92+
)
8293
else:
83-
faq_post_path = os.path.join('data', 'faq', post)
94+
faq_post_path = os.path.join("data", "faq", post)
8495
body, metadata = parse_file(faq_post_path)
8596

8697
postdata = {
87-
"title" : metadata["title"][0],
88-
"tags" : ','.join(metadata["tags"]),
89-
"slug" : metadata["slug"][0],
90-
"content": body
98+
"title": metadata["title"][0],
99+
"tags": ",".join(metadata["tags"]),
100+
"slug": metadata["slug"][0],
101+
"content": body,
91102
}
92-
93-
return render_template("edit_page.html", postdata=postdata, posts=posts, edit_type='faq')
103+
104+
return render_template(
105+
"edit_page.html", postdata=postdata, posts=posts, edit_type="faq"
106+
)
94107

95108
else:
96-
if ptype == 'blog':
97-
filename, category = post.split('@')
98-
delete_post(os.path.join('data', 'blog', category, filename), docs_dir='b')
109+
if ptype == "blog":
110+
filename, category = post.split("@")
111+
delete_post(os.path.join("data", "blog", category, filename), docs_dir="b")
99112
else:
100-
delete_post(os.path.join('data', 'faq', post), docs_dir='faq')
113+
delete_post(os.path.join("data", "faq", post), docs_dir="faq")
101114

102115
return 'Post deleted! Do not forget to rebuild the site to remove the remaining references. <a href="/">Return</a>'
103116

117+
104118
if __name__ == "__main__":
105119
app.run()

manager_utils.py

Lines changed: 52 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2,87 +2,94 @@
22
import shutil
33

44
import markdown
5+
56
from settings import info
67

78

89
class AuthorNotFound(Exception):
910
def __init__(self, author, message="Author not found"):
1011
self.author = author
11-
self.message = f'{message}: {author}'
12+
self.message = f"{message}: {author}"
1213
super().__init__(self.message)
1314

15+
1416
def get_posts():
15-
'''Get blog and faq post'''
16-
blogs_dir = os.listdir('data/blog')
17-
faqs = os.listdir('data/faq')
17+
"""Get blog and faq post"""
18+
blogs_dir = os.listdir("data/blog")
19+
faqs = os.listdir("data/faq")
1820

1921
blogs = []
2022
for category in blogs_dir:
21-
bposts = os.listdir(os.path.join('data', 'blog', category))
23+
bposts = os.listdir(os.path.join("data", "blog", category))
2224
for post in bposts:
2325
blogs.append([post, category])
2426

25-
data = {'blogs':blogs, 'faqs':faqs}
26-
27+
data = {"blogs": blogs, "faqs": faqs}
28+
2729
return data
2830

31+
2932
def delete_post(filePath, docs_dir):
30-
'''Delete post .md file and rendered files in docs'''
33+
"""Delete post .md file and rendered files in docs"""
3134
# First, delete main .md file (in data folder)
32-
os.remove(filePath)
33-
35+
os.remove(filePath)
36+
3437
# Second, delete folder from docs folder
35-
shutil.rmtree(os.path.join('docs', docs_dir, ntpath.basename(filePath)[:-3]))
38+
shutil.rmtree(os.path.join("docs", docs_dir, ntpath.basename(filePath)[:-3]))
39+
3640

3741
def format_authors_tags(items):
38-
'''Format authors and tags to be compatible with Markdown metadata'''
39-
s = ''
42+
"""Format authors and tags to be compatible with Markdown metadata"""
43+
s = ""
4044
count = 0
4145
for item in items:
4246
count += 1
4347
if count > 1:
4448
# More than one author
45-
s += f' {item}\n'
49+
s += f" {item}\n"
4650
else:
47-
s += f'{item}\n'
48-
51+
s += f"{item}\n"
52+
4953
return s.strip()
5054

55+
5156
def get_comma_separated(string):
52-
'''Get items in comma separated string and clean whitespaces'''
53-
result = [x.strip() for x in string.split(',')]
57+
"""Get items in comma separated string and clean whitespaces"""
58+
result = [x.strip() for x in string.split(",")]
5459
return result
5560

61+
5662
def get_md_template(post_type):
57-
'''Return given template content'''
58-
with open(f'manager_app/templates/post.{post_type}.md') as f:
63+
"""Return given template content"""
64+
with open(f"manager_app/templates/post.{post_type}.md") as f:
5965
content = f.read()
6066
return content
6167

68+
6269
def ensure_authors(authors):
63-
'''Verify if given authors are valid flaskcwg members'''
70+
"""Verify if given authors are valid flaskcwg members"""
6471
for author in authors:
6572
if author not in info["profiles"]:
6673
raise AuthorNotFound(author)
6774

6875

6976
def get_file_body(file_lines):
70-
'''Get body of file content without metadata'''
77+
"""Get body of file content without metadata"""
7178
indicestoremove = []
7279
for n, line in enumerate(file_lines):
7380
indicestoremove.append(n)
74-
if 'slug:' in line:
81+
if "slug:" in line:
7582
break
7683

7784
for index in sorted(indicestoremove, reverse=True):
7885
file_lines.pop(index)
7986

80-
body = ''.join(file_lines)
87+
body = "".join(file_lines)
8188
return body
8289

8390

8491
def parse_file(file_path):
85-
'''Open, get and return conntent of given file'''
92+
"""Open, get and return conntent of given file"""
8693
with open(file_path, encoding="utf-8") as f:
8794
text = f.read()
8895
with open(file_path, encoding="utf-8") as f2:
@@ -98,27 +105,28 @@ def parse_file(file_path):
98105

99106

100107
def save_md_file(post_type, data):
101-
'''Save post to respective category (blog, faq)'''
108+
"""Save post to respective category (blog, faq)"""
102109
template = get_md_template(post_type)
103-
slug = data['slug']
104-
105-
if post_type == 'blog':
106-
category = data['category']
107-
post = template.format(data['title'],
108-
data['summary'],
109-
format_authors_tags(data['authors']),
110-
data['date'],
111-
format_authors_tags(data['tags']),
112-
slug,
113-
data['post_content'])
114-
115-
with open(f'data/blog/{category}/{slug}.md', 'w') as f:
110+
slug = data["slug"]
111+
112+
if post_type == "blog":
113+
category = data["category"]
114+
post = template.format(
115+
data["title"],
116+
data["summary"],
117+
format_authors_tags(data["authors"]),
118+
data["date"],
119+
format_authors_tags(data["tags"]),
120+
slug,
121+
data["post_content"],
122+
)
123+
124+
with open(f"data/blog/{category}/{slug}.md", "w") as f:
116125
f.write(post)
117126
else:
118-
post = template.format(data['title'],
119-
format_authors_tags(data['tags']),
120-
slug,
121-
data['post_content'])
127+
post = template.format(
128+
data["title"], format_authors_tags(data["tags"]), slug, data["post_content"]
129+
)
122130

123-
with open(f'data/faq/{slug}.md', 'w') as f:
131+
with open(f"data/faq/{slug}.md", "w") as f:
124132
f.write(post)

0 commit comments

Comments
 (0)