-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHOWTOINITIALIZE.txt
More file actions
561 lines (451 loc) · 15.7 KB
/
Copy pathHOWTOINITIALIZE.txt
File metadata and controls
561 lines (451 loc) · 15.7 KB
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
Create three files :
routes.py
init.py
config.py
Create virtual environment:
python -m venv venv
Activate virtual environment:
.\venv\Scripts\Activate
Install flask:
pip install flask
app is instance of flask
/__init__.py:
```
from flask import Flask
app = Flask(__name__)
from Projectdir import routes
```
/PY2/Projectdir/PY2.py
from Projectdir import app
/routes.py
from Projectdir import app
$ pip install python-dotenv
create /PY2/.flaskenv
FLASK_APP=PY2.py
$ pip install flask-wtf
forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Sign In')
login.html:
{% extends "base.html" %}
{% block content %}
<h1>Sign In</h1>
<form action="" method="post" novalidate>
{{ form.hidden_tag() }}
<p>
{{ form.username.label }}<br>
{{ form.username(size=32) }}
</p>
<p>
{{ form.password.label }}<br>
{{ form.password(size=32) }}
</p>
<p>{{ form.remember_me() }} {{ form.remember_me.label }}</p>
<p>{{ form.submit() }}</p>
</form>
{% endblock %}
DATABASE:
pip install flask-sqlalchemy
pip install flask-migrate
AFTER THIS:
config.py:
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
SECRET_KEY= os.environ.get('SECRET_KEY') or 'you-will-never-guess-it'
SQLALCHEMY_DATABASE_URL= os.environ.get('DATABASE_URL') or 'sqlite:///'+ os.path.join(basedir,'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
__init__.py(add):
from flask_sqlalchemy import SQLalchemy
from flask_migrate import Migrate
app.config.from_object(Config)
db=SQLalchemy(app)
migrate = Migrate(app,db)
from app import routes,models
models.py:
from Projectdir import db
from flask_sqlalchemy import SQLAlchemy
class User(db.Model):
id = db.Column(db.Integer,primary_key = True)
username = db.Column(db.String(64),index=True,unique = True)
email = db.Column(db.String(120),index=True,unique=True)
password_hash = db.Column(db.String(120))
def __repr__(self):
return (f'User {self.username}')
$flask db init
$flask db upgrade
ONE TO MANY RELATIONSHIP
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer,primary_key = True)
username = db.Column(db.String(64),index=True,unique = True)
email = db.Column(db.String(120),index=True,unique=True)
password_hash = db.Column(db.String(120))
important >>>>posts = db.relationship('Post',backref = 'author ' ,lazy = 'dynamic')
>>> backref will add field to object of 'many' class and that will return the ONE
>>> post.author will return user
def __repr__(self):
return (f'User {self.username}')
class Post(db.Model):
id = db.Column(db.Integer , primary_key = True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime,index = True,default = datetime.utcnow)
user_id = db.Column(db.Integer , db.ForeignKey('user.id'))
def __repr__(self):
return (f'Post {self.body}')
EVERYTIME U MAKE CHANGES TO DB ,
$ flask db migrate
$ flask db upgrade
we can check:
$flask shell
>>> from Projectdir import db
>>> from PRojectdir.models import User,Post
>>> u = User(username='Nishant' , email = 'nishantborkar28@gmail.com')
>>> db.session.add(u)
and u can add several changes
>>>db.session.commit()
if there is an error , use
>>>db.session.rollback()
return all the users
>>> users = User.query.all()
>>> print(users)
>>> for user in users:
print(user.id , user.username)
if u know the id , here's how to query
>>>User.query.get(1)
TO DELETE SOMETHING FROM DATABASE:
db.session.delete(THAT object)
PASSWORD HASHING
from werkzeug import check_password_hash , generate_password_hash
generate_password_hash takes a string arg and hashes it
check_password_hash takes two args and cross checks each other and returns bool
$pip install flask-login
__init__.py:
from flask_login import LoginManager
login = LoginManager(app)
models.py:
from flask_login import UserMixin
class User(UserMixin,db)
models.py
from app import login
# ...
@login.user_loader
def load_user(id):
return User.query.get(int(id))
routes.py
from flask_login import current_user, login_user
from app.models import User
# ...
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is None or not user.check_password(form.password.data):
flash('Invalid username or password')
return redirect(url_for('login'))
login_user(user, remember=form.remember_me.data)
return redirect(url_for('index'))
return render_template('login.html', title='Sign In', form=form)
current_user returns the current user object that is signed in
is is_authenticated checks whether that user is logged in or not
if username exists and password for that is correct then we have to login
login_user takes two args , user and remember and some other too, (crtl + click)
routes.py
rom flask_login import logout_user
# ...
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('index'))
editing the base.html:
<div>
Microblog:
<a href="{{ url_for('index') }}">Home</a>
{% if current_user.is_anonymous %}
<a href="{{ url_for('login') }}">Login</a>
{% else %}
<a href="{{ url_for('logout') }}">Logout</a>
{% endif %}
</div
current_user.is_anonymous is true when user is not logged in
FORCING A USER TO Login
__init__.py:
login = LoginManager(app)
login.login_view = 'login'
login_view will take string that refers to view function of login page , here ,'login'
Protecting other view function against non logged in users
routes.py:
from flask_login import login_required
@app.route('/')
@app.route('/index')
@login_required
def index():
ADD @login_required decorator to protect view functions
NOW when the login required intercepts the page , we need to redirect the user , wherever he was
so we need to add extra info to url for example /login?next=/index
After ? there is a query which tells where to redirect next
from flask import request
from urllib.parse import urlparse
@app.route('/login',methods=['GET','POST'])
def login():
form = LoginForm()
if current_user.is_authenticated:
return redirect(url_for('index'))
if form.validate_on_submit():
user=User.query.filter_by(username=form.username.data).first()
if user is None or not user.check_password(form.password.data):
flash('INVALID USERNAME OR PASSWORD')
return redirect(url_for('login'))
login_user(user,remember=form.remember_me.data)
next_page = request.args.get('next')
if not next_page or urlparse(next_page).netloc !='':
next_page = url_for('index')
return redirect(next_page)
return render_template('login.html',form = form,title = 'Sign in')
it will redirect me to index if i originally landed on login (i.e. no query is loaded)
hence no next_page or urlparse(next_page).netloc!='' it means if the next_page is out of my website
i wont allow redirect and hence redirect to index (netloc means network location(search))
SHOWING THE LOGGED IN USER'S NAME
index.html
{% extends "base.html" %}
{% block content %}
<h1>Hi, {{ current_user.username }}!</h1>
{% for post in posts %}
<div><p>{{ post.author.username }} says: <b>{{ post.body }}</b></p></div>
{% endfor %}
{% endblock %}
User REGISTRATION
WE'LL make a form
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo
from app.models import User
# ...
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
password2 = PasswordField('Repeat Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Register')
def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user is not None:
raise ValidationError('Please use a different username.')
def validate_email(self, email):
user = User.query.filter_by(email=email.data).first()
if user is not None:
raise ValidationError('Please use a different email address.')
TO USE EMAIL() VALIDATOR OF FLASK U NEED TO USE
(venv) $ pip install email-validator
in case the email or username already exists we raise error which will be displayed below field
validate_<field> is one of the special method
USER REGISTRATION
from app import db
from app.forms import RegistrationForm
# ...
@app.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = RegistrationForm()
if form.validate_on_submit():
user = User(username=form.username.data, email=form.email.data)
user.set_password(form.password.data)
db.session.add(user)
db.session.commit()
flash('Congratulations, you are now a registered user!')
return redirect(url_for('login'))
return render_template('register.html', title='Register', form=form)
profile view
@app.route('/user/<username>')
@login_required
def user(username):
user = User.query.filter_by(username=username).first_or_404()
posts = [
{'author': user, 'body': 'Test post #1'},
{'author': user, 'body': 'Test post #2'}
]
return render_template('user.html', user=user, posts=posts)
user.html
{% extends "base.html" %}
{% block content %}
<h1>User: {{ user.username }}</h1>
<hr>
{% for post in posts %}
<p>
{{ post.author.username }} says: <b>{{ post.body }}</b>
</p>
{% endfor %}
{% endblock %}
base.html
(give the link to profile page)
<div>
Microblog:
<a href="{{ url_for('index') }}">Home</a>
{% if current_user.is_anonymous %}
<a href="{{ url_for('login') }}">Login</a>
{% else %}
>>>>>>>> MAIN LINE <a href="{{ url_for('user', username=current_user.username) }}">Profile</a>
<a href="{{ url_for('logout') }}">Logout</a>
{% endif %}
</div>
* EVERYTIME MODEL IS UPDATE USE $flask db migrate
$flask db update
last seen
MODELS.PY
class User(UserMixin, db.Model):
# ...
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime, default=datetime.utcnow)
user.html
{% extends "base.html" %}
{% block content %}
<table>
<tr valign="top">
<td><img src="{{ user.avatar(128) }}"></td>
<td>
<h1>User: {{ user.username }}</h1>
{% if user.about_me %}<p>{{ user.about_me }}</p>{% endif %}
{% if user.last_seen %}<p>Last seen on: {{ user.last_seen }}</p>{% endif
</td>
</tr>
</table>
...
{% endblock %}
RECORD TIME OF LAST SEEN
from datetime import datetime
@app.before_request
def before_request():
if current_user.is_authenticated:
current_user.last_seen = datetime.utcnow()
db.session.commit()
>>>>>> @app.before_request is decorator which allows a function to get called before every other method
forms.py
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import DataRequired, Length
# ...
class EditProfileForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
about_me = TextAreaField('About me', validators=[Length(min=0, max=140)])
submit = SubmitField('Submit')
edit_profile.html
{% extends "base.html" %}
{% block content %}
<h1>Edit Profile</h1>
<form action="" method="post">
{{ form.hidden_tag() }}
<p>
{{ form.username.label }}<br>
{{ form.username(size=32) }}<br>
{% for error in form.username.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ form.about_me.label }}<br>
{{ form.about_me(cols=50, rows=4) }}<br>
{% for error in form.about_me.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>{{ form.submit() }}</p>
</form>
{% endblock %}
editprofile view function routes.python
from app.forms import EditProfileForm
@app.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
form = EditProfileForm()
if form.validate_on_submit():
current_user.username = form.username.data
current_user.about_me = form.about_me.data
db.session.commit()
flash('Your changes have been saved.')
return redirect(url_for('edit_profile'))
elif request.method == 'GET':
form.username.data = current_user.username
form.about_me.data = current_user.about_me
return render_template('edit_profile.html', title='Edit Profile',
form=form
his view function processes the form in a slightly different way. If
validate_on_submit() returns True I copy the data from the form into
the user object and then write the object to the database. But when
validate_on_submit() returns False it can be due to two different
reasons. First, it can be because the browser just sent a GET request,
which I need to respond by providing an initial version of the form
template. It can also be when the browser sends a POST request with
form data, but something in that data is invalid. For this form, I need
to treat these two cases separately. When the form is being requested
for the first time with a GET request, I want to pre-populate the fields
with the data that is stored in the database, so I need to do the reverse
of what I did on the submission case and move the data stored in the
user fields to the form, as this will ensure that those form fields have
the current data stored for the user. But in the case of a validation
error I do not want to write anything to the form fields, because those
were already populated by WTForms. To distinguish between these
two cases, I check request.method, which will be GET for the initial
request, and POST for a submission that failed validation
user.html
{% if user == current_user %}
<p><a href="{{ url_for('edit_profile') }}">Edit your profile</a></p>
{% endif %}
DEBUG MODE
$env:FLASK_DEBUG = "1"
errors.py
from flask import render_template
from app import app, db
@app.errorhandler(404)
def not_found_error(error):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_error(error):
db.session.rollback()
return render_template('500.html'), 500
The error functions work very similarly to view functions. For these
two errors, I’m returning the contents of their respective templates.
Note that both functions return a second value after the template,
which is the error code number. For all the view functions that I
created so far, I did not need to add a second return value because the
default of 200 (the status code for a successful response) is what I
wanted. In this case these are error pages, so I want the status code of
the response to reflect that.
The error handler for the 500 errors could be invoked after a database
error, which was actually the case with the username duplicate above.
To make sure any failed database sessions do not interfere with any
database accesses triggered by the template, I issue a session rollback.
This resets the session to a clean state
404.html
{% extends "base.html" %}
{% block content %}
<h1>File Not Found</h1>
<p><a href="{{ url_for('index') }}">Back</a></p>
{% endblock %}
500.html
{% extends "base.html" %}
{% block content %}
<h1>An unexpected error has occurred</h1>
<p>The administrator has been notified. Sorry for the inconvenience!</p>
<p><a href="{{ url_for('index') }}">Back</a></p>
{% endblock %}
__init__.py
from app import routes, models, errors
SENDING ERROR EMAILS
config.py
class Config(object):
# ...
MAIL_SERVER = os.environ.get('MAIL_SERVER')
MAIL_PORT = int(os.environ.get('MAIL_PORT') or 25)
MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS') is not None
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
ADMINS = ['your-email@example.com']