Home  >  Article  >  Backend Development  >  Application examples of flask in python (code)

Application examples of flask in python (code)

不言
不言forward
2018-11-15 14:36:245358browse

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'
# 主程序
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'))

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="https://img.php.cn//upload/image/567/623/726/1542263688275968.png" title="1542263688275968.png" alt="Application examples of flask in python (code)"></p>
<p class="comments-box-content"></p></int></user_id>

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:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete