Today, the most vital task is considered to be web development, and Python, with all its advantages, is a great language for constructing sites. Out of the many frameworks available for Python, Flask is quite famous due to its simplicity and flexibility. The framework is quite simple and, with little effort from the developer, allows one to create great site applications. This article will provide further detail on the main concepts related to web applications with the Flask framework including the creation of a simple application in Flask, the use of templates, and routing.
Flask supports the WSGI (Web Server Gateway Interface) specification, which allows Python-based web applications to interact with web servers. It also supports the Jinja2 template engine which is useful in rendering dynamic HTML content.
After the Flask framework is installed, you can commence web application development. Create a Python file such as app.py where you will write your code. So the first thing you'd do is import the Flask class, and then create an instance of the class:
The core of the application is the `Flask` class, and the parameter `__name__` allows Flask to locate the application. Once the application instance is created, you are ready to implement routes and views.
For how a route can be set in Flask, consider the following:
In the example above, the `@app.route('/')` decorator maps the home url '(') which is also the base url of the application to the function home. Therefore, whenever a user goes to the base address of your application, the home function will be invoked and it shall output on the browser `Hello, World!`.
Routes can also be made additionally by writing a new function which has a new url:
Because the `debug=True` flag is on, I can gain insights into what went wrong while also being able to make changes and automatically reload the application.
The code specified will execute on port 5000, to check whether the application has worked I can visit `http://127.0.0.1:5000/` which is the output location of the routes seeded earlier.
Of note, an important aspect in regard to templates would be the prerequisite of creating a `templates` folder that will contain files pertaining to the above context. As an instance make an `index.html` file under the templates folder as follows:
Bartering string with '{{ name }}' is a feature in the HTML file above that can be replaced by the python application with a value that has been programmed in.
Next, update your code by modifying the function as follows:
Keep in mind that `name` can be any name that is suitable in your context as `render_template` replaces it with the actual name provided in the template. Therefore, upon calling the above function flask will load an index.html file passing the value name as "John Doe" to this particular template.
The action which is a tag attribute `/submit` defines the endpoint to which the form data will be directed on submitting the form and how it will be sent across, in this case it will be directed to the submit route and the data will be sent as a POST request.
In your code written in Python, at the time of form submission, you can perform the following actions:
So here with the help of `request.form['name']` the data that is filled out in that form is called. This means that the user's provided name is included in the response.
The Flask Application
Flask is a web framework for the Python programming language, which has the main goal to be user-friendly and easy to extend. In a distinct variety of other frameworks, Flask does not consist of many tools or libraries integrated within the framework. Instead, it contains many basic features which enable users to develop web apps and then users can build on top of them according to their promotion goals. Thus, Flask is great for small scale applications as well as for different developers that wish to make use of a lot of components for their applications.Flask supports the WSGI (Web Server Gateway Interface) specification, which allows Python-based web applications to interact with web servers. It also supports the Jinja2 template engine which is useful in rendering dynamic HTML content.
Getting Started with Flask
You can use Flask by first installing it. You can install Flask in the simplest way through Python's package manager `pip`. In case you don't have Flask on your machine you can install it by running one of the commands below. pip install flask
from flask import Flask
app = Flask(__name__)
Routing in Flask
Routing is arguably one of the most crucial aspects of web development as it is the process of linking URLs with specific functions of your application. Flask makes creating routes very simple, the routes can be created using the routing mechanism which utilizes the `@app.route` decorator to link the function which is to be called when a user visits the link with the link itself.For how a route can be set in Flask, consider the following:
@app.route('/')
def home():
return "Hello, World!"
Routes can also be made additionally by writing a new function which has a new url:
@app.route('/about')
def about():
return "This is the About page."
Running the Application
With your routes set, you will now need to run the application using the run method on the app object to start the Flask application. Calling that method will run a dev web server on your PC and it will allow you to test the web app on your web browser. if __name__ == '__main__':
app.run(debug=True)
The code specified will execute on port 5000, to check whether the application has worked I can visit `http://127.0.0.1:5000/` which is the output location of the routes seeded earlier.
Flask allows the use of Templates
Thus serving web pages that vary in content ('of different data or variables from users' input)' is the norm in a 'web development' context. Rather more useful is the feature that allows for the generation of multiple webpages that are instead solely based on a few templates. Jinja2 is the templating engine for flask, meaning it provides the capability to write python code within an HTML file.Of note, an important aspect in regard to templates would be the prerequisite of creating a `templates` folder that will contain files pertaining to the above context. As an instance make an `index.html` file under the templates folder as follows:
<!DOCTYPE html>
<html>
<head>
<title>My Flask App</title>
</head>
<body>
<h1>Welcome to my Flask app, {{ name }}!</h1>
</body>
</html>
Next, update your code by modifying the function as follows:
from flask import render_template
@app.route('/')
def home():
return render_template('index.html', name="John Doe")
Keep in mind that `name` can be any name that is suitable in your context as `render_template` replaces it with the actual name provided in the template. Therefore, upon calling the above function flask will load an index.html file passing the value name as "John Doe" to this particular template.
Processing Forms and User Commends
In addition, when a request is made and it is accompanied by form data, the flasks request object will have the form data. The following example will show you how to incorporate that feature. For example, you might have a form that requests a user's name, in which case you could implement it with an HTML form as follows: <form action="/submit" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<input type="submit" value="Submit">
</form>
In your code written in Python, at the time of form submission, you can perform the following actions:
from flask import request
@app.route('/submit', methods = ['POST'])
def submit():
name = request.form['name']
return f"Hello, {name}!"
Conclusion
Using Flask makes it easy and comfortable for you to create web applications using Python. It provides developers with efficient means for defining routes, rendering templates and obtaining input from the users. The simple structure of Flask makes it suitable for different types of applications but especially small and medium projects where developers need the flexibility to implement only the required components. Hence, you are armed with the basic knowledge of Flask and would now very easily be able to create applications using Python and the web.
Article
Be the first comment