Lab Objectives
Cardiff University
School of Computer Science & Informatics Dr
CMT302 EC &Innovation
Copyright By PowCoder代写 加微信 powcoder
SPRING – SESSION 3 LAB
Form Validation. Cart. Deployment.
Objectives of this lab are to complete developing essential functionality for our Online Bookstore, by:
• adding validation to user authentication functionality; • implementing Shopping Cart functionality;
• deploying our website on OpenShift
NB: As for all labs, it is advisable to do all the work with your virtual environment activated.
General Comments
As before, this exercise is not assessed. If you do not manage to finish all the tasks in the lab, please attempt to finish them in your own time.
Use the suggested resources and links, provided throughout this document and on the last page, to help you understand the code. A snapshots of the state of the project is available on Learning Central (FLASK_labs_snapshot_4.zip). You can download this to help you if you are stuck, to check your progress (and, perhaps, at times to save your typing *from scratch*). However, please make sure you understand each line of the code!
If you get stuck – raise your hand and ask for advice from the lecturer and TA. It is also okay to discuss the solutions with your peers (these labs are not assessed!), however, make sure you understand everything by yourself.
IMPORTANT!! The labs will give you some basic understanding of how to develop a website in Flask. To get more comprehensive understanding of how this ’stuff’ works, it is strongly advised that you read the recommended book, suggested documentation and ’quickstarts’, as well as complete few tutorials. However, the suggested resources are just suggestions and the list is non-exhaustive! There are lots of other tutorials and resources on the Web.
Abbreviations used in this document
• dir – directory (folder) • db – database
• NB – Nota bene
FORM VALIDATION 1
In our previous lab we practice developing Flask forms. However, we assumed that the users would only provide input that is valid. If they don’t, the system will behave unexpectedly and possibly crash. For example, if a user tries to register with a username that already exist, we would get a SQLAlchemy’s ’database integrity error’. To avoid issues like this, we need to validate the users’ input and provide them with hints and help, e.g. we want to reinforce the rule that the username and email is unique and inform the user if this username and email are already taken.
In this section, we will work on the following files: forms.py to define functions for user input validation, appropriate templates (e.g. register.html to tell the server how to render the content), and routes.py to bind specific URLs to our functions.
1. Let’s check username already exists. In forms.py, we would specify this rule as:
def validate_username(self, username):
user = User.query.filter_by(username=username.data).first() if user:
raise ValidationError(‘Username already exist. \
Please choose a different one.’)
NB: The above code requires an import of ValidationError from wtforms.validators. 2. Still in forms.py, create a similar validation for the users’ emails, i.e.
def validate_email(self, email):
3. We could also specify certain rules for passwords. Suppose we want to reinforce the following rule: a password must be between 6 and 8 characters long (any characters, e.g. abcde1 will be valid, but not abc1).2
We can use a regular expression (regex) for this. Update password in forms.py, as follows:
password = PasswordField(‘Password’, validators=[DataRequired(),
Regexp(‘^.{6,8}$’, message=’Your password \ should be between 6 and 8 characters long.’)])
NB: Don’t forget to import Regexp from wtforms.validators.
NB: Consult the lecture slides for a range of regular expressions. For more in- formation and practice, visit: https://www.w3schools.com/python/python_regex.asp
4. Next, implement appropriate validation for the log in functionality.
1 NB: In this lab, we will be using Flask to validate the forms. Alternatively, you might want to look into using
JavaScript to achieve this – see the examples given in the lecture.
2 This, of course, is a simple requirement for the password. If we want to make the rule more complicate, we would need to use a more complicated regex. For instance if we want to make sure that a user’s password must be between 6 and 8 characters long AND contain at least one numeric digit, the regex for this would be: ^(?=.*\d).{6,8}$
5. After we specified the logic, we need to change our code to check the form is valid when it is submitted, so in routes.py instead of using
if request.method == ‘POST’: we need to to use:
if form.validate_on_submit():
in the appropriate @app.route(..) decorators.
Error Messages
Any good system should provide its user with feedback. We have already encountered that we can specify a message to the user during form validation (Task 3). We can also use a messaging system provided by Flask, called ’flashing system’.
NB: This functionality requires an import of flash from flask in routes.py.
6. The following is an example of a flash message, which we can add to routes.py: …
flash(‘Invalid username or password.’) …
7. To enable the ’flashing system’, we need to add code to the templates to instruct the server to display the messages:
(a) site-wide, by adding the following to layout.html:
{% with messages = get_flashed_messages() %} {% if messages %}
-
{% for message in messages %}
- {{ message }}
{% endfor %}
{% endif %} {% endwith %}