Flask

  • Flask is a popular Python framework for developing web applications.
  • Classified as a microframework, it comes with minimal built-in components and requirements, making it easy to get started and flexible to use.
  • The developer has the liberty to choose which tools and libraries they want to utilize.
  • Flask is capable of creating both static websites as well as more complex apps that involve database integration, accounts and authentication, and more.
  • The Python module that contains all the classes and functions needed for building a Flask app is called flask.
  • When creating a Flask object, we need to pass in the name of the application. We can do that with python's special variable __name__.
  • In our Flask app. we can create endpoints to handle the various requests. Requests from different URLs can be directed to different endpoints in a process called routing.
  • To build a route, we need to first define a function, known as a view function, that contains the code for processing the request and generating a response.
  • We can use the route() decorator to bind a URL to the view function such that the function will be triggered when the URL is visited. It takes the URL path as a parameter. All URL paths must start with a leading slash ('/')
  • Multiple URLs can also be bound to the same view function.
  • We can use variable rules to allow for dynamic URLs. These variable parts will then be passed to the view function. Example: /orders/<user_name>
  • We can also optionally enforce the type of the variable being accepted using the syntax: <converter:variable_name> with the possible types as - string, int, float, path, uuid.
  • Template refers to an HTML file that can represent multiple web pages with the same structure and functionality.
  • Flask uses the Jinja2 template engine to render HTML files that include application variables and control structures.
  • Containing our HTML in separate files is the standard and more organized approach for structuring our web app.
  • We use the render_template() method to render HTML templates in flask which we have to import. It looks from templates inside a directory called templates.
  • Template Variables, After the filename argument in render_template() we can add keyword arguments to be used as variables within the templates. To access the variable inside our templates we need to use the expression delimiter {{}}.
  • Filters are used by the template engine to act on template variables. To use them simply follow the variable with the filter name inside the delimiter and separate them with | character.
    1. The filter title acts on a string variable and capitalizes the first letter in every word.
    2. The filter capitalize, capitalizes the first character of a string.
    3. The default filter will output the text in its argument when a variable isn't passed in the template. Does not work on an empty string.
    4. lowercase/uppercase, Makes all the characters in a string to lowercase or uppercase.
    5. int/float, changes any number variable to integer/float
    6. The filter length, Calculates the length of a string, list, or dictionary variable.
  • Using if statements in a template happen inside a statement delimiter block {% %}. To close it you need the {% endif %}
  • To use for loop inside a template we have to use {% for %} and {% endfor %} and put the HTML between them.
  • We can inherit a template from another template by using the code: {% extends "base.html" %}.
  • By default, our flask routes only support GET requests. These are the requests for data such as what to display in the browser window.
  • When submitting a form through a website, the form data is sent as a POST request. This type of request wants to add data to the app. Routes can handle POST requests if it is specified in the method's argument of the route() decorator.
  • Flask provides access to the data in the request through the request object. When data is sent via form submission it can be accessed using the form attribute of the request object which is a dictionary.
  • As sites get larger their file structure becomes more complex and the paths of Flask routes may change. FLask solves this problem with url_for('view_function_name', Variables to pass). It also has arguements _external=True, _scheme ='https'
  • FlaskForm Class:
    1. Flask provides an alternative to web forms by creating a from class in the application, implementing the fields in the template, and handling the data back in the application.
    • It inherits from the class FlaskForm which allows us to implement the form as a template variable and then collect the data once submitted. Flaskform is a part of flask_wtf.
    • The StringField, SubmitField, etc. classes are the part of the WTForms library.
    • app.config["SECRET_KEY] = "my_secret" is done to protect against CRSF.
    • Creating a form in the template is done by accessing attributes of the form passed to the template.
    • {{ template_form.hidden_tag() }} is the other end of the CRSF protection.
    • You can access the form fields by {{ form.textField.label }} and {{ form
    • .teaxtField() }} in the template.
    • The data can be directly accessed by using the data attribute associated with each field in the class in the app. form_data = flask_form.my_text.data
    • Validation is when form fields must contain data or a certain format of data in order to move forward with submission.
    • We enable validation in our form class using the validators parameter in the form field definitions. They come from the wtform.validators module. validators=[DataRequired()]
    • The DataRequired() validator simply requires a field to have something in it before the form is submitted.
    • The FlaskForm class also provides a method called validate_on_submit(), which we can use in our route to check for a valid form submission. It returns True when there is a POST request.
    • There are more fields like TextAreaField, BooleanField, RadioField(contains tuples that represent a button in the group and contains the button identifier string and the button label string.)
  • Redirecting, We use the function redirect("url_string")
  • Flask-SQLAlchemy is an extension for flask that supports the use of a Python SQL toolkit called SQL Alchemy.  from flask_sqlalchemy import SQLAlchemy
  • To enable communication with a database, the Flask-SQLAlchemy extension takes the location of the application's database from the SQLALCHEMY_DATABASE_URI configuration variable to sqlite:///database.db
  • app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False to disable a feature that signals the application every time a change is about to be made in the db.
  • We create an SQLAlchemy object and bind it to our app. db = SQLAlchemy(app) finally.

Comments