Home  >  Article  >  Backend Development  >  Quick Start with Flask: Python Web Development Tool Installation Guide

Quick Start with Flask: Python Web Development Tool Installation Guide

WBOY
WBOYOriginal
2024-02-18 10:06:06932browse

Quick Start with Flask: Python Web Development Tool Installation Guide

Flask Installation Guide: Quickly Get Started with Python Web Development Tool

Overview:
Flask is a lightweight Python Web framework that is simple to use but functional Powerful and suitable for rapid development of web applications. This article will introduce how to install Flask and get started quickly, while providing specific code examples.

Install Flask:

  1. Make sure that the Python environment has been installed. It is recommended to use Python 3.x version.
  2. Open the command line tool and use the following command to install Flask:

    pip install flask

    pip is Python's package management tool. It will automatically download and install Flask and its dependent libraries.

Get started quickly:

  1. Create a new Python file and name it app.py (you can also give it another name).
  2. Edit the app.py file, use the following code to import the Flask module and create a Flask application instance:

    from flask import Flask
    
    app = Flask(__name__)
  3. Add a route to handle the user's ask. Routing refers to the URL path when accessing a web application in a browser. Each route corresponds to a function that is used to process requests for that URL path. For example, we add a simple route to handle requests to the root path and return a "Hello, Flask!" response:

    @app.route('/')
    def hello():
        return 'Hello, Flask!'
  4. If you need to run Flask in a development environment To apply, you need to add the following code at the end of the app.py file:

    if __name__ == '__main__':
        app.run(debug=True)

    The function of this code block is to determine whether the current file is run as an independent application. If so, start the application development server.

  5. Save and run the app.py file:

    python app.py

    The program will open the Flask development server and listen on the local port 5000.

  6. Visit http://localhost:5000 in the browser and you will see the "Hello, Flask!" response.

Further development:
In addition to simple routing processing, Flask also provides many feature-rich extensions to facilitate the development of various web applications. The following is sample code that demonstrates how to use some common functions of Flask:

  1. Template engine: Flask uses Jinja2 as the default template engine for generating dynamic HTML pages. The sample code is as follows:

    from flask import render_template
    
    @app.route('/user/<name>')
    def user(name):
        return render_template('user.html', name=name)

    Create a template file named user.html in the templates folder, and use the {{ name }} syntax for variable substitution.

  2. Form processing: Flask provides WTForms extension, which can easily process form data. The sample code is as follows:

    from flask import request
    from flask_wtf import FlaskForm
    from wtforms import StringField, SubmitField
    
    class MyForm(FlaskForm):
        name = StringField('Name')
        submit = SubmitField('Submit')
    
    @app.route('/form', methods=['GET', 'POST'])
    def form():
        form = MyForm()
        if form.validate_on_submit():
            return 'Hello, ' + form.name.data + '!'
        return render_template('form.html', form=form)

    Create the form.html template file in the templates folder, using {{ form.name }} and {{ form.submit }}Syntax rendering form.

  3. Database operation: Flask supports a variety of databases, such as MySQL, PostgreSQL, etc. The sample code is as follows:

    from flask_sqlalchemy import SQLAlchemy
    
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/db_name'
    db = SQLAlchemy(app)
    
    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))
    
    @app.route('/users')
    def users():
        users = User.query.all()
        return render_template('users.html', users=users)

    Create the users.html template file in the templates folder, using {% for user in users %}{{ user.name }}{% endfor %} Syntax displays a list of users.

Summary:
This article introduces the installation steps of Flask and provides some specific code examples to help readers quickly get started using Flask for Python web development. In addition to the functions introduced above, Flask also has many extensions to choose from, and readers can further learn and use them according to their own needs. As a simple and powerful tool, Flask will greatly improve development efficiency and bring a pleasant web development experience.

The above is the detailed content of Quick Start with Flask: Python Web Development Tool Installation Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn