Python Flask基础到登录功能的实现代码
视频教程教学地址:https://www.bilibili.com/video/BV18441117Hd?p=1
0x01路由
from flask import Flask app = Flask(__name__) # flask对象实例化 @app.route('/index') #定义首页 @app.route('/') #设置默认index def index(): return 'hello world!' @app.route('/home/<string:username>') # 生成home路由,单一传参 def home(username): print(username) return '<h1>欢迎回家</h1>' @app.route('/main/<string:username>/<string:password>') #多个参数传递 def main(username,password): print(username) print(password) return '<h1>welcome</h1>' def about(): return 'about page' app.add_url_rule(rule='/about',view_func=about) #另一种添加路由的方式 if __name__ == '__main__': app.debug = True #开启debug模式 app.run()
0x02 模版和静态文件
2.1 文件结构
2.2代码
#app.py #app.py from flask import Flask,render_template #倒入模版 app = Flask(__name__) #声明模版文件夹 @app.route(('/index')) def index(): return render_template('index.html') #返回模版 if __name__ == '__main__': app.run(debug=True)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>hello hello</h1> <img src="/static/imgs/1.png"> </body> </html>
2.3 运行效果
0x03 json
from flask import Flask,jsonify app = Flask(__name__) @app.route('/') def index(): user = {'name':'李三','password':'123'} return jsonify(user) if __name__ == '__main__': app.run(debug=True)
3.1运行效果
0x04 重定向
4.1 访问跳转
from flask import Flask, redirect #导入跳转模块 app = Flask(__name__) @app.route('/index') def index(): return redirect('https://www.baidu.com') #指定跳转路径,访问/index目录即跳到百度首页 @app.route('/home') def home(): return 'home page' if __name__ == '__main__': app.run(debug=True)
4.2 打印路由
from flask import Flask,url_for #导入模块 app = Flask(__name__) @app.route('/index') def index(): return 'test' @app.route('/home') def home(): print(url_for('index')) 打印 index路由 return 'home page' if __name__ == '__main__': app.run(debug=True)
4.3 跳转传参
# 访问home,将name带入index并显示在页面 from flask import Flask,url_for,redirect #导入模块 app = Flask(__name__) @app.route('/index<string:name>') def index(name): return 'test %s' % name @app.route('/home') def home(): return redirect(url_for('index',name='admin')) if __name__ == '__main__': app.run(debug=True)
0x05 jinjia2模版
5.1代码
from flask import Flask,render_template #倒入模版 app = Flask(__name__) #声明模版文件夹 @app.route(('/index')) def index(): user = 'admin' data = ['111',2,'李三'] userinfo = {'username':'lisan','password':'12333'} return render_template('index.html',user=user,data=data,userinfo=userinfo) #返回模版,传入数据 if __name__ == '__main__': app.run(debug=True)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>11111</h1> {{user}} {{data}} #直接传入 {% if user == 'admin'%} #简单逻辑判断 <h1 style="color:red">管理员</h1> {% else %} <h1 style="color:green">普通用户</h1> {% endif %} <hr> {% for item in data %} # for循环 <li>{{item}}</li> {% endfor %} <hr> {{ userinfo['username'] }} {{ userinfo['password'] }} <hr> {{ user | upper }} #字母大写(更多可查阅jinjia2过滤器) </body> </html>
5.2 运行效果
0x06 蓝图
目的是为了更好的细分功能模块
6.1代码结构
├── admin │ └── admin.py └── app.py
6.2 代码
#admin.py from flask import Blueprint 导入蓝图模块 admin = Blueprint('admin',__name__,url_prefix='/admin') #对象实例化,url_prefix添加路由前缀,表示若想访问本页相关路由,只能通过形如 xxx/admin/login 访问,不能 xxx/login访问 @admin.route('/register') def register(): return '欢迎注册' @admin.route('/login') def login(): return '欢迎登录'
#app.py from flask import Flask from admin.admin import admin as admin_blueprint # 导入蓝图 app = Flask(__name__) #声明模版文件夹 app.register_blueprint(admin_blueprint) #注册蓝图 @app.route(('/index')) def index(): return 'index page' if __name__ == '__main__': app.run(debug=True)
0x07 登录
7.1结构
7.2代码
#web.py from flask import Flask,render_template,request,redirect,flash,url_for,session from os import urandom app = Flask(__name__) app.config['SECRET_KEY'] = urandom(50) @app.route('/index') def index(): if not session.get('user'): flash('请登录后操作','warning') return redirect(url_for('login')) return render_template('index.html') @app.route('/login',methods=['GET','POST']) def login(): if request.method == 'GET': return render_template('login.html') elif request.method == 'POST': username = request.form.get('username') password = request.form.get('password') if username == 'admin' and password == '888888': flash('登录成功','success') session['user'] = 'admin' return redirect(url_for('index')) else: flash('登录失败','danger') return redirect(url_for('login')) if __name__ == '__main__': app.run(debug=True)
# index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script> </head> <body> <h1>欢迎你,管理员</h1> {% for color, message in get_flashed_messages(with_categories=True) %} <div class="alert alert-{{color}} alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <p>{{message}}</p> </div> {% endfor %} </body> </html>
#login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>login</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script> </head> <body> <form action="/login" method="post"> <div class='form-group'> <input type="text" name="username" placeholder="请输入用户名" class="form-control"> </div> <div class='form-group'> <input type="password" name="password" placeholder="请输入密码" class="form-control"> </div> <div class="form-group"> <input type="submit" value= "submit" class="btn btn-primary"> </div> </form> {% for color, message in get_flashed_messages(with_categories=True) %} <div class="alert alert-{{color}} alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <p>{{message}}</p> </div> {% endfor %} </body> </html>
7.3实现效果
7.3.1未登录默认跳转到登录页面
7.3.2登录成功跳转到index页面
账户密码:admin/888888
7.3.2登录失败效果
到此这篇关于Python Flask基础到登录功能的实现的文章就介绍到这了,更多相关Python Flask登录内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)