Home Backend Development Python Tutorial Python code example for displaying database information on a web page based on flask_sqlalchemy

Python code example for displaying database information on a web page based on flask_sqlalchemy

Nov 15, 2018 pm 02:09 PM
html5 mysql python windows

The content of this article is about the code example of displaying database information on a python web page based on flask_sqlalchemy. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Web page displays database information

Use the flask_sqlalchemy we just learned to display the data in the database table on the web page.
Before starting to run the program, make sure that the operations of creating tables and users have been executed in the database. For details, see Link description.

# 模板文件templates/list.html
{% extends 'base.html' %}
{% block title %}
    显示
{% endblock %}
{% block newcontent %}
Copy after login
                                                           {% for user  in users %}                                                                                        {% endfor %}
用户编号用户名称用户密码用户创建时间用户会员类型
{{ user.id }}{{ user.name }}{{ user.passwd }}{{ user.add_time }}{{ user.role.name }}
{% endblock %}
# 数据库操作文件zaj_sql_models.py
from datetime import datetime
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
import pymysql
from sqlalchemy import desc

app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:sheen@localhost/zaj_sql'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
bootstrap = Bootstrap(app)
# class Student(db.Model):
#     __tablename__ = 'students'
#     sid = db.Column(db.SMALLINT,primary_key=True)
#     sname = db.Column(db.String(50))
#     sage = db.Column(db.Integer)

class User(db.Model):
    id = db.Column(db.Integer,autoincrement=True,primary_key=True)
    name = db.Column(db.String(50),unique=True)
    passwd = db.Column(db.String(100))
    add_time = db.Column(db.DATETIME,default=datetime.now())
    gender = db.Column(db.BOOLEAN,default=True)
    role_id = db.Column(db.INTEGER,db.ForeignKey('role.id'))

    def __repr__(self):
        return '<user:>' %(self.name)

class Role(db.Model):
    id = db.Column(db.INTEGER,autoincrement=True,primary_key=True)
    name = db.Column(db.String(50),unique=True)
    users = db.relationship('User',backref='role')
    # 给Role模型添加users属性
    # backref 是定义反向引用,可以通过User.role访问User里面的数据
    def __repr__(self):
        return '<role:>' % (self.name)
if __name__ =='__main__':


    # 1. 创建数据库表
    db.drop_all()
    db.create_all()
    # 2. 创建role数据库表数据
    role_1 = Role(name='超级会员')
    role_2 = Role(name='普通会员')

    db.session.add(role_1)
    db.session.add(role_2)
    db.session.commit()

    # # # 3. 添加user表内数据,100个用户,50个为超级会员,50个为普通会员
    for i in range(1,13):
        if i%2 == 0:
            u = User(name='sheen'+str(i),passwd='sheen',role_id=1)
            db.session.add(u)
        else:
            u = User(name='star'+str(i),passwd='star',role_id=2)
            db.session.add(u)
    db.session.commit()</role:></user:>
Copy after login
#主程序
from flask import Flask,render_template
from zaj_sql_models import app

from zaj_sql_models import User
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/list/')
def list():
    users = User.query.all()
    return render_template('list.html',users=users)

if __name__ == '__main__':
    app.run()
Copy after login

Python code example for displaying database information on a web page based on flask_sqlalchemy

The above is the detailed content of Python code example for displaying database information on a web page based on flask_sqlalchemy. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

How to use VSCode How to use VSCode Apr 15, 2025 pm 11:21 PM

Visual Studio Code (VSCode) is a cross-platform, open source and free code editor developed by Microsoft. It is known for its lightweight, scalability and support for a wide range of programming languages. To install VSCode, please visit the official website to download and run the installer. When using VSCode, you can create new projects, edit code, debug code, navigate projects, expand VSCode, and manage settings. VSCode is available for Windows, macOS, and Linux, supports multiple programming languages ​​and provides various extensions through Marketplace. Its advantages include lightweight, scalability, extensive language support, rich features and version

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

What is the difference between vscode and pycharm What is the difference between vscode and pycharm Apr 15, 2025 pm 11:54 PM

The main differences between VS Code and PyCharm are: 1. Extensibility: VS Code is highly scalable and has a rich plug-in market, while PyCharm has wider functions by default; 2. Price: VS Code is free and open source, and PyCharm is paid for professional version; 3. User interface: VS Code is modern and friendly, and PyCharm is more complex; 4. Code navigation: VS Code is suitable for small projects, and PyCharm is more suitable for large projects; 5. Debugging: VS Code is basic, and PyCharm is more powerful; 6. Code refactoring: VS Code is basic, and PyCharm is richer; 7. Code

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

Understanding H5 Code: The Fundamentals of HTML5 Understanding H5 Code: The Fundamentals of HTML5 Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Difference between vscode and microsoft visual studio Difference between vscode and microsoft visual studio Apr 15, 2025 pm 08:39 PM

VS Code and Visual Studio are different IDEs: Visual Studio focuses on large and complex projects, especially for Microsoft-based languages, providing powerful debugging and code management capabilities. VS Code is lightweight and flexible, supports multiple languages, suitable for rapid development and prototyping, and has a wealth of extension plug-ins.

See all articles