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'))
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/imghwm/default1.png" data-src="https://img.php.cn//upload/image/567/623/726/1542263688275968.png?x-oss-process=image/resize,p_40" class="lazy" 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!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.