Flask
Flask
html page
Flask :
-pip install flask
-set FLASK_APP=file.py
-flask run
~if __name__=="__main__":
app.run(debug=True)
//Alternative for setting up all environment variables, with this we can directly run with the
command “python file.py”
~app=Flask(__name__)
~app.route(‘./’)
def fun() //return type a html
Templates:
To add html pages
~return render_template(“home.html”, arguments) //from flask import render_template
//Flask uses Jinja templating engine = to write python code inside webpage
Syntax =
{% ‘codeblock’ %}
{{ ‘variable’ }}
Example
{% for i in nums %}
<h1>{{ i }}</h1>
{% end for %}
home.html =
{% extends “source.html” %}
{% block content %}
Your content
{% endblock content %}
//In flask static files like CSS, Javascript need to be placed in a static folder
Extension for working with forms and validations WT forms = pip install flask-wtf
app.config['SECRET_KEY'] = 'text’' //creating token for the session to protect from cookies
Example
forms.py =
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo
class RegistrationForm(FlaskForm):
username = StringField('Username',
validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email',
validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password',
validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Sign Up')
proj.py=
from forms import RegistrationForm
register.html=
{% extends "layout.html" %}
{% block content %}
<div class="content-section">
<form method="POST" action=""> //action=”” means it will redirect to this page only
{{ form.hidden_tag() }} //to add token
<fieldset class="form-group">
<legend class="border-bottom mb-4">Join Today</legend>
<div class="form-group">
{{ form.username.label(class="form-control-label") }}
{% if form.username.errors %} //If there exists some error, check error
{{ form.username(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.username.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.username(class="form-control form-control-lg") }}
{% endif %}
</div>
</fieldset>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</form>
</div>
{% endblock content %}
layout.html =
{% with messages = get_flashed_messages(with_categories=true) %}
//To show the flashed message on template
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}