-
Notifications
You must be signed in to change notification settings - Fork 1
/
__init__.py
217 lines (170 loc) · 8.16 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
from flask import Flask, render_template, request, flash, redirect, url_for, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import or_
from werkzeug.utils import secure_filename
from markdown import markdown
import datetime, os, random
# todo: page logging pour acceder aux new author, category, article...
# todo: panel administrateur
# todo: ranger les auteurs et les catégories dans deux sections différentes du menu
# todo: page affichant tous les articles d'un auteur
PATH = os.path.abspath(os.path.dirname(__file__))
os.makedirs(os.path.join(PATH, "assets", "pictures"), exist_ok=True)
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.sqlite3'
app.config['SECRET_KEY'] = "HiiiiiiiiiMdR"
app.config['UPLOAD_FOLDER'] = os.path.join(PATH, "assets", "pictures")
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
db = SQLAlchemy(app)
class Article(db.Model):
id = db.Column('article_id', db.Integer, primary_key=True)
resume = db.Column(db.Text)
picture = db.Column(db.String(256))
title = db.Column(db.String(64))
content = db.Column(db.Text)
date = db.Column(db.DateTime)
source = db.Column(db.String(256))
category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
def __init__(self, title, content, category, author, source, picture, resume, date=None):
self.title = title
self.content = content
if date is None:
date = datetime.datetime.utcnow()
self.date = date
self.category_id = category
self.author_id = author
self.source = source
self.picture = picture
self.resume = resume
class Author(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
website = db.Column(db.String(256))
picture = db.Column(db.String(256))
articles = db.relationship('Article', backref='author', lazy='dynamic')
def __init__(self, name, website, picture):
self.name = name
self.website = website
self.picture = picture
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
articles = db.relationship('Article', backref='category', lazy='dynamic')
def __init__(self, name):
self.name = name
@app.route('/')
def show_all_articles():
active=None
articles = Article.query.order_by(Article.date.desc()).all()
categories = Category.query.all()
return render_template("blog.html",articles=articles,categories=categories,active=active)
@app.route('/article/<key>')
def get_article(key):
return render_template("blog.html", article=Article.query.get(key), categories=Category.query.all())
@app.route('/category/<key>')
def get_category(key):
active = int(key)
categories = Category.query.all()
articles = Article.query.filter_by(category_id=key).order_by(Article.date.desc()).all()
return render_template("blog.html",categories=categories,articles=articles,active=active)
@app.route('/newArticle', methods=["POST","GET"])
def create_article():
if request.method == 'POST':
if not request.form['title'] or not request.form['resume'] or not request.form['content'] or not \
request.form['category'] or not request.form['author']:
flash('Please enter all the fields', 'error')
else:
if not request.form['source']:
source = None
else:
source = request.form['source']
if not request.files['pic'] or request.files['pic'].filename == '' or not allowed_file(
request.files['pic'].filename):
pic = None
flash('No picture for this article', 'error')
else:
filename = secure_filename(request.files['pic'].filename)
while os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
rand = random.randint(0, 999999)
filename = filename.rsplit('.', 1)[0] + '-' + str(rand) + "." + filename.rsplit('.', 1)[1]
request.files['pic'].save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
pic = filename
content = markdown(request.form['content'])
article = Article(request.form['title'], content, request.form['category'],
request.form['author'], source, pic, request.form['resume'])
db.session.add(article)
db.session.commit()
flash('Record was successfully added')
return redirect(url_for('show_all_articles'))
return render_template('new_article.html',authors=Author.query.all(),categories=Category.query.all())
@app.route('/newAuthor', methods=["POST","GET"])
def create_author():
if request.method == 'POST':
if not request.form['name'] or not request.form['website']:
flash('Please enter all the fields', 'error')
else:
if not request.files['pic'] or request.files['pic'].filename == '' or not allowed_file(
request.files['pic'].filename):
pic = None
flash('No picture for this article', 'error')
else:
filename = secure_filename(request.files['pic'].filename)
while os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
rand = random.randint(0, 999999)
filename = filename.rsplit('.', 1)[0] + str(rand) + "." + filename.rsplit('.', 1)[1]
request.files['pic'].save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
pic = filename
author = Author(request.form['name'], request.form['website'], pic)
db.session.add(author)
db.session.commit()
flash('Record was successfully added')
return redirect(url_for('show_all_articles'))
return render_template('new_author.html', categories=Category.query.all())
@app.route('/newCategory', methods=["POST", "GET"])
def create_category():
if request.method == 'POST':
if not request.form['category']:
flash('Please enter all the fields', 'error')
else:
category = Category(request.form['category'])
db.session.add(category)
db.session.commit()
flash('Record was successfully added')
return redirect(url_for('show_all_articles'))
return render_template('new_category.html', categories=Category.query.all())
@app.route('/search', methods=["POST", "GET"])
def search():
if request.method == "POST" and request.form['search']:
search = request.form['search']
articles = Article.query.filter(or_(Article.title.like("%" + search + "%"),
Article.resume.like("%" + search + "%"),
Article.content.like("%" + search + "%"))). \
order_by(Article.date.desc()).all()
if len(articles) <= 0:
flash('Aucun article ne correspond à votre recherche.', 'error')
return redirect(url_for("show_all_articles"))
return render_template("blog.html", articles=articles, categories=Category.query.all())
return redirect(url_for("show_all_articles"))
@app.route('/test', methods=["POST", "GET"])
def test():
return render_template("test.html", articles=Article.query.order_by(Article.date.desc()).all(),
author=Author.query.all(), categories=Category.query.all())
@app.route('/assets/pictures/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.context_processor
def utility_author():
def get_obj_author(id):
return Author.query.get(id)
return dict(get_obj_author=get_obj_author)
@app.context_processor
def utility_category():
def get_obj_category(id):
return Category.query.get(id)
return dict(get_obj_category=get_obj_category)
if __name__ == '__main__':
db.create_all()
app.run(debug=True)