Home Backend Development Python Tutorial Application examples of flask in python (code)

Application examples of flask in python (code)

Nov 15, 2018 pm 02:36 PM
mysql python

The content of this article is about the application examples (code) of flask in python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Bind user login information to the database

Requires the user's login information to be sent to the background for comparison with the database to determine whether the user can log in

#config.py文件,用来创建远程连接的类
class DB:
    HOST = '192.168.1.227'
    USER= 'root'
    PASSWD = 'sheen'
    PORT = 3306
    DBNAME = 'test'
Copy after login
# 主程序
import pymysql
from config import DB
# 1. 创建连接
conn = pymysql.connect(
    host=DB.HOST,
    user=DB.USER,
    passwd=DB.PASSWD,
    port=DB.PORT,
    db=DB.DBNAME,
)
cur = conn.cursor()

def isUserExist(username):
    """判断用户名是否存在"""
    sqli = "select * from users where name='%s'" %(username)
    res = cur.execute(sqli)
    # res返回的是sql语句查询结果的个数;
    #  如果为0, 没有查到。
    if res == 0:
        return  False
    else:
        return  True
def isPasswdOk(username, passwd):
    sqli = "select * from users where name='%s' and passwd='%s'" %(
        username, passwd)
    res = cur.execute(sqli)
    if res == 0 :
        return  False
    else:
        return  True
def addUser(username, passwd):
    """用户注册时, 添加信息到数据库中"""
    sqli = "insert into users(name, passwd) values('%s', '%s')" %(
        username, passwd)
    try:
        res = cur.execute(sqli)
        conn.commit()
    except Exception as e:
        conn.rollback()
        return e
# cur.close()
# conn.close()
if __name__ == "__main__":
    addUser('root', 'root')
    print(isUserExist('root'))
    print(isPasswdOk('root', 'root'))
Copy after login

Application examples of flask in python (code)

2607089714-5bd1811bc2a77_articlex (1).png

Determine whether the user is logged in

Parts of certain websites The content is only displayed to users who have logged in. At this time, we need to determine whether the user is logged in

import random
import os
from datetime import  datetime
import psutil
from flask import Flask, request, render_template, redirect, url_for, abort, session
from models import isPasswdOk, isUserExist, addUser
import platform
app = Flask(__name__)
app.config['SECRET_KEY'] =  random._urandom(24)

import  functools

def is_login(f):
    """判断用户是否登陆的装饰器"""
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        # run函数代码里面, 如果登陆, session加入user, passwd两个key值;
        # run函数代码里面, 如果注销, session删除user, passwd两个key值;
        # 如果没有登陆成功, 则跳转到登陆界面
        if 'user' not in session:
            return  redirect('/login/')
        # 如果用户是登陆状态, 则访问哪个路由, 就执行哪个路由对应的视图函数;
        return  f(*args, **kwargs)
    return  wrapper

# 用户主页
@app.route('/')
def index():
    return render_template('index.html')

# 用户登陆按钮
@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        print(request.form)
        # 1. 如何获取到用户提交的信息呢?
        user = request.form['user']
        passwd = request.form['passwd']

        # 2. 判断用户名和密码是否正确

        if isPasswdOk(user, passwd):
                # 将用户名和密码信息存储到session中;
                session['user'] = user
                session['passwd'] = passwd
                # 如果登陆成功, 跳转到主页;
                return redirect(url_for('index'))
        else:
            # 如果登陆失败, 重新登陆;
            return  render_template('login.html', message="用户名或者密码错误")

    else:
        # 用户是GET请求, 返回登陆的html页面
        # 1. 读取login.html文件的内容
        # 2. 将读取的内容返回给用户界面
        return render_template('login.html')

# 用户注销
@app.route('/logout/')
def logout():
    session.pop('user', None)
    session.pop('passwd', None)
    # 注销即删除用户的session信息, 注销成功, 跳转到首页;
    return  redirect(url_for('index'))
    # return  redirect('/')

# 用户注册# http方法: get, post(需要提交用户名和密码信息)
@app.route('/register/', methods=['GET', 'POST'])
def register():
    # 判断是否提交注册信息;
    if request.method == 'POST':
        user = request.form['user']
        passwd = request.form['passwd']
        if isUserExist(user):
            message = "用户已经存在"
            return  render_template('register.html', message=message)
        else:
            addUser(user, passwd)
            return  redirect(url_for('login'))
    else:
        return  render_template('register.html')

# 系统监控
@app.route('/sysinfo/')
@is_login
def sysinfo():
    info = platform.uname()
    # 获取开机时间的时间戳, 需要安装psutil模块;
    boot_time = psutil.boot_time()
    # 将时间戳转换为字符串格式, 两种方法, 任选一种l
    # print(time.ctime(boot_time))
    boot_time = datetime.fromtimestamp(boot_time)

    # 获取当前时间
    now_time = datetime.now()

    # 获取时间差
    delta_time = now_time - boot_time
    delta_time = str(delta_time).split('.')[0]
    return  render_template('sysinfo.html',
                        hostname = info.node,
                        sysname = info.system,
                        release = info.release,
                        machine = info.machine,
                        now_time =  now_time,
                        boot_time = boot_time,
                        delta_time = delta_time
                            )


# 404异常处理: 类似于捕获异常
@app.errorhandler(404)
def not_found(e):
    return  render_template('404.html')


# 抛出异常
@app.route('/user/<user_id>/')
def user(user_id):
    if 0<int app.run><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/567/623/726/1542263688275968.png" class="lazy" title="1542263688275968.png" alt="Application examples of flask in python (code)"></p>
<p class="comments-box-content"></p></int></user_id>
Copy after login

The above is the detailed content of Application examples of flask in python (code). 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

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.

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.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

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.

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 run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

See all articles