ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Flask介绍,新手四件套,session使用

2022-08-05 17:00:15  阅读:165  来源: 互联网

标签:__ 四件套 return index Flask app session


web框架介绍, Flask介绍和安装

介绍:
    Flask是一个基于Python开发并且依赖jinja2模板(DTL)和Werkzeug WSGI(符合wsgi协议的web服务器,wsgiref)服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后触发Flask框架,开发人员基于Flask框架提供的功能对请求进行相应的处理,并返回给用户,如果要返回给用户复杂的内容时,需要借助jinja2模板来实现对模板的处理,即:将模板和数据进行渲染,将渲染后的字符串返回给用户浏览器。
    
安装Flask
	pip install flask
    
'''
基本样式
from flask import Flask

# app=Flask(__name__)
app = Flask('lqz')

@app.route('/')
def index():
    return 'hello  world'


if __name__ == '__main__':
    app.run()
'''

jsonify, render_template, redirect,session

return 字符串

@app.route('/index',methods=['GET'])
def index():
    return 'aaa'

'''
相当于django中的HttpResponse('字符串')
直接在浏览器中显示字符串
'''

jsonify

@app.route('/index',methods=['GET'])
def index():
    return jsonify({key:value})
'''
	返回json格式的字符串
'''

render_template

@app.route('/index',methods=['GET'])
def index():
    context = {
        'username':'张三',
        'age':20,
    }
    return render_template(模板文件名,**context)
	# return render_template('index.html',**context)
	# return render_template(模板文件名,username='张三',age=20)

'''
返回一个页面
两种传值效果一样
context 向模板传递参数
'''

redirect

@app.route('/index',methods=['GET'])
def index():
    return redirect('/home')

'''
重定向
'''

session

1.使用前需要先配置secret_key
    from flask import Flask,request
    app = Flask(__name__)
    app.secret_key = 'adasdasdasdzxocim' # 如果要使用session,必须写秘钥,可以随便写

2.使用session
from flask import session # (1)导入session
'''
POST请求,请求体中的数据都在request.from中
'''
@app.route('/login',methods=['POST'])
def login():
    username = request.from.get('username')
    password = request.from.get('password')
    if username == '春游去动物园' and password == '123456':
        session['username'] = username # (2)设置session即可
        return redirect('/home')
    else:
        return render_template('login.html',errors='用户名或密码错误')
    
    
3.从session中获取值
from flask import session
@app.route('/home',methods=['GET','POST'])
def home():
	if session.get('username') == '春游去动物园': # 从session中取出值
        context = {
            ....
        }
        return render_template('home.html',**context)
    else:
        return redirect('/login')

标签:__,四件套,return,index,Flask,app,session
来源: https://www.cnblogs.com/chunyouqudongwuyuan/p/16555002.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有