CMT302 E-commerce & Innovation
Session 2:
Modern E-Commerce Development
Dr Natasha Edwards
Copyright By PowCoder代写 加微信 powcoder
Office: C/2.02
Spring Semester: Plan
• Sessions 1, 2, 3
– ModernECdevelopment
– Backenddevelopmentfundamentals:design patterns, frameworks (Flask), DBs, Version Control with git
• Session 3
– Strategicandmanagerialaspects,challengesand
– Competitiveadvantage;valuechainand
supply chain management, marketing; CRM
• Session 4
– Launchinge-business:economicsand
justification. Security. Privacy. Legal and ethical.
Learning objectives
Understand web development using frameworks Examine essential principles of using Flask
– Project vs app
– Basic workflow
– Good practices: venv, git, commenting – Project organisation
– Templating with Jinja
– Database, ORM, models
Learn how to use forms (WTFForms for Flask)
– Workflow
– Files involved
– Creation and update – Form Validation
Independent Study: Alternatives: JavaScript, Regex
Putting it together
Design Code Build Deploy
Technologies/Tools: Flask, MySQL, git, OpenShift
Flask and Django
Flask is a micro, lightweight web framework;
Django is a full-stack web framework
Who uses Flask?
According to https://stackshare.io/flask 746 companies reportedly use it.
Terminology: Projects vs Apps
Project is the entire ‘program’ (e.g. the whole website); can be viewed as a collection of apps and configurations to create a ‘website experience’.
App is a module, which provides some specific functionality.
Apps can be reused in other projects.
e.g. a blog, user authentication, social media integration, user polls/ surveys, …
NB: Can’t run an app without a project
Flask/Django Web Dev project: basic workflow
Create app
Define models (db)
Edit/ review settings (settings.py)
Create project
Create template
Push to git
Build & Deploy
Define views
Good practice: virtual environment (pipenv/venv)
pipenv and venv is used to manage Python packages for a project (‘sandbox’)
Install packages, libraries, etc. without affecting the overall system
Several project = several venvs
Activate before you start working; deactivate when finish.
pip is used to install packages you want
$ pip install
package you want to install)
pip can also help gather the list of packages used in the project so that this info can be passed on, e.g. to deployment system
using requirements.txt:
$ pip freeze > requirements.txt
you can then use to install the packages in venv:
$ pip install -r requirements.txt
https://pip.pypa.io/en/stable/reference/pip_freeze/
Good practice: git, comments, readme
Put your project folder under git at the beginning of the project:
Please complete the git lab sheet to ensure you can connect to the remote repo!
put your project dir under git control from the start of the project
Create .gitignore and specify files you do not want to pus to the remote (e.g. .pyc)
Push often
Comment your code diligently, particularly important for working in a team
Create a meaningful readme file
Example structure of project
If you do not have files located in the expected directories, Flask would not know where to look for them!
Minimal application
To run an application
On Windows
Templating
with Jinja
https://jinja.palletsprojects.com/en/2.11.x/
What is templating?
• A tool that constructs html pages.
• Can get server side and client side templating. • Jinja is Server side.
• It turns:
this into this
{%for value in nums
%}
{% endfor %}
What is templating: dynamic data
• Thepythonlist‘nums’:
Can be created in the server and passed to the templating engine
This can be done when the page is requested.
{%for value in nums %}
{% endfor %}
Simple home.html and layout.html
layout.html
Rendering a template
• Template files must be in the template directory.
• https://flask.palletsprojects.com/en/1.1.x/ quickstart/#rendering-templates
from flask import Flask, request,
render_template
@app.route(“/Basic”, methods=[‘GET’])
def returnFirst():
if request.method == ‘GET’:
return render_template(‘0_Basic.html’,
data=’Hello World’)
Jinja Basics:
{{ data }}
{% command %} If
{%if data%} {{ data }}
{%endif%}
return render_template(‘0_Basic.html’, data = ‘Hello World’)
Dictionaries
We can access data from dictionaries
KEY – VALUE PAIR
{{ data.title }}
Hi this is a message from {{data.name}}.
{{data.message}}
…
messages = {‘title’:’HelloWorld’,
‘name’:’John’,
‘message’:‘more’}
return render_template(‘1_json.html’, data = messages)
Loops: lists
Looping through a list
{%for day in days %}
{% endfor %}
days = [‘mon’,’tues’,’wed’,’thurs’,’fri’]
return render_template(‘2_loops.html’, days = days) …
Loops: Dictionaries
data.items()
Single var vs two vars
{%for key,value in data.items() %}
{% endfor %}
data = {‘title’:’HelloWorld’, ‘name’:’Ian’,
‘message’:’hi!’,
‘days’: [‘mon’,’tues’,’wed’,’thurs’,’fri’] }
return render_template(‘3_dictionary.html’, data = data)
Inheritance
• A base file can be extended:
{%extends ‘base.html’%}
• Blocks can be overriden
{% block myBlock%} Bla
{%endblock%}
• Or Called…
{{ super() }}
https://flask.palletsprojects.com/en/1.1.x/patterns/templateinheritance/
Simple home.html and layout.html
layout.html
More functionality and options
• E.g. filters
https://jinja.palletsprojects.com/en/2.11.x/
https://jinja.palletsprojects.com/en/2.11.x/api/#writing-filters
• Seen routes before in the browser urls
• x.x.x.x:5000/Home.html
• x.x.x.x:5000/IMC/Home.html
• Routes lead to execution of code
• Go to the file system and retrieve page
• Routes could request data • or an action
use route() decorator
View decorators: https://flask.palletsprojects.com/en/1.1.x/patterns/viewdecorators/
Redirect a route to a static page
from flask import Flask, redirect
@app.route(“/redirect”) def redirectToStatic():
return redirect(“/static/hello.html”)
ORM – Object-relational mapping
converting data between different types of systems, which are not necessarily compatible with each other.
uses OO programming languages Flask-SQLAlchemy
https://flask-sqlalchemy.palletsprojects.com/
en/2.x/models/
Simple examples
One-to-many relationship
Many-to-many relationship
MySQL can’t deal with n:m relationship, so we
need to define a helper table
Define and access DB
Set up DB connections Create tables
Register with the application Initialise the DB File
>>> db.drop_all()
http://flask.pocoo.org/docs/1.0/tutorial/database/
https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/
Model for a typical e-commerce system
Discussion:
• Identify essential EC system entities and attributes within the Universe of discourse for a ‘Book Store’
Practical: FLASK 1, parts 1 and 2
Complete exercises:
[CMT302] LAB 2 – flask 1 – WORKSHEET.pdf
Way forward
Quickstart:
https://flask.palletsprojects.com/en/1.1.x/
quickstart/
Go through the slides and suggested links
Also, quite a few tutorials on the internet, find the one that ‘agrees’ with you.
Create Form
Update (or create) Model(s)
Flask Forms
Access and logic
Create or update templatе(s)
e.g. login.html
Update ‘config’
__init__.py
In no particular order…
Create form
Create Form Update (or create) Model(s)
forms.py models.py
Flask Forms
Access and logic
Create or update Update ‘config’ templatе(s)
e.g. login.html init .py
Update model
Create Form Update (or create) Model(s)
forms.py models.py
Flask Forms
Access and logic
Create or update Update ‘config’ templatе(s)
e.g. login.html init .py
Access and logic
Create Form Update (or create) Model(s)
forms.py models.py
Flask Forms
Access and logic
Create or update Update ‘config’ templatе(s)
e.g. login.html init .py
Create (or update) template(s)
Create Form Update (or create) Model(s)
forms.py models.py
Flask Forms
Access and logic
Create or update Update ‘config’ templatе(s)
e.g. login.html init .py
Update ‘config’
Create Form Update (or create) Model(s)
forms.py models.py
Flask Forms
Access and logic
Create or update Update ‘config’ templatе(s)
e.g. login.html init .py
WTForms: some standard fields
Source: https://www.tutorialspoint.com/flask/flask_wtf.htm
Practical: FLASK 1, part 3
Complete exercises:
[CMT302] LAB 2 – flask 1 – WORKSHEET.pdf
Useful links
WTForms Form Validation
https://flask.palletsprojects.com/en/1.1.x/patterns/wtforms/
Python RegEx
https://www.w3schools.com/python/python_regex.asp https://scotch.io/tutorials/an-introduction-to-regex-in-python
Flask messaging system (‘flashing’)
https://flask.palletsprojects.com/en/1.1.x/patterns/flashing/
Flask sessions
https://flask.palletsprojects.com/en/1.1.x/quickstart/#sessions
Jinja Template documentation
https://jinja.palletsprojects.com/en/2.11.x/templates/
Form Validation
WTForms: validators
Source: https://www.tutorialspoint.com/flask/flask_wtf.htm
Alternatives
Independent Study
Regular expressions
Regular expressions (=regex, or =regexp) is a language for defining patterns/templates for matching strings of text.
You have probably seen shell wildcards before: * and ?. Regexp is a far more advanced mechanism.
Given a regexp, we can test whether a particular string matches this regexp.
var pattern = /fish|steak/;
// or dynamically:
var pattern = new RegExp(“Kirk|Spock”);
Now we match a string against this regexp (=pattern):
var myString = “Spock has the conn.”; var results = pattern.exec(myString);
Intro Prelim JS Events Syntax Loops DOM Forms DOM Objects RegExp AJAX FW 48 61
Regex in Python
Need to import re module first Regex functions:
https://www.w3schools.com/python/python_regex.asp
Regex in Python: Metacharacters
… are characters with a special meaning:
https://www.w3schools.com/python/python_regex.asp
Regex in Python: Special Sequences
https://www.w3schools.com/python/python_regex.asp
Regex Examples
Regex Examples
In this section, we will work on the following files: forms.py to define functions for
NB: The above code requires an import of ValidationError from wtforms.validators
user input validation, appropriate templates (e.g. register.html to tell the server
and an import of User from blogs.models.
bind specific URLs to our functions.
user = User.query.filter_by(username=username.data).first()
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,
2. Still in forms.py, create a similar validation for the users’ emails, i.e.
1. Let’s check username already exists. In forms.py, we would specify this rule as: …
def validate_email(self, email):
def validate_username(self, username):
raise ValidationError(‘Username already exist. Please choose a e.g. abcde1 will be valid, but not abc1).1
Òæ different one.’)
We can use a regular expression (regex) for this. Update password in forms.py, as
NB: The above code requires an import of ValidationError from wtforms.validators follows:
and an import of User from blogs.models. …
2. Still in forms.py, create a similar validation for the users’ emails, i.e. password = PasswordField(‘Password’, validators=[DataRequired(),
Regexp(‘^.{6,8}$’, message=’Your password should be def validate_email(self, email):
Òæ between 6 and 8 characters long.’)])
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, NB: Don’t forget to import Regexp from wtforms.validators.
e.g. abcde1 will be valid, but not abc1).1
NB: Consult [CHECK] the handout that accompanies this lab for a range of
We can use a regular expression (regex) for this. Update password in forms.py, as regular expressions. For more information and practice, visit: https://www.w3schools.
com/python/python_regex.asp
From Lab Flask 3 Regexp(‘^.{6,8}$’, message=’Your password should be
0NB: In this lab, we will be using Flask to validate the forms. Alternatively, you might want to look
into using JavaScript to achieve tÒæhis –besteweetehne e6xamndple8s gcihvaernaicnttehreshlaonndgo.u’t)w]h)ich accompanies the lab. 1This, of course, is a simple requirement for the password. If we want to make the rule more complicated,
4. Next, implement appropriate validation for the log in functionality. password = PasswordField(‘Password’, validators=[DataRequired(),
Alternative Solution: Javascript
Lots of resources, e.g.
Tutorials on https://www.w3schools.com/js/
default.asp
Also: AJAX: https://www.w3schools.com/
xml/ajax_intro.asp
Lots of books
What is JavaScript useful for?
Add content to a web page dynamically (as the web page is loading).
Read and write HTML elements and hence change the content of an HTML element.
Manipulate the content of a web page in response to user actions (respond to “events”).
React to user generated events:
For example, validate the contents of a form prior to submission to the server, e.g. make sure all fields are filled in.
Provide help with input.
Turn on and o layers of a document.
Intro Prelim JS Events Syntax Loops DOM Forms DOM Objects RegExp AJAX FW56 12 Interact with frames.
Intro Prelim JS Events Syntax Loops DOM Forms DOM Objects RegExp AJAX FW 61 33
JavaScript: loops
Intro Prelim JS Events Syntax Loops DOM Forms DOM Objects RegExp AJAX FW 62 30
JavaScript: loops
The familiar while loop:
maxval = 5; count = 0; while(count < maxval) {
document.writeln("value is " + count);
document.writeln("
“);
count = count + 1;
And the do. . . while loop:
maxval = 5; count = 0; do {
document.writeln(“value is ” + count);
document.writeln(“
“);
count = count + 1;
} while (count < maxval);
Intro Prelim JS Events Syntax Loops DOM Forms DOM Objects RegExp AJAX FW 63 31
JavaScript: conditionals
var pints = 5; if (pints > 2) {
document.writeln(“You cannot drive a car!
“); if (pints > 6) {
document.writeln(“Call a cab!
“); } else {
document.writeln(“Ride your bicycle!
“);
} else if (pints > 0)
document.writeln(“Drive very cautiously!
“);
document.writeln(“It is ok to drive!
“);
Intro Prelim JS Events Syntax Loops DOM Forms DOM Objects RegExp AJAX FW 64 32
Manipulating DOM objects
Using DOM objects
Do not click here!
Intro Prelim JS Events Syntax Loops DOM Forms DOM Objects RegExp AJAX FW 5
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com