flask入门

1Flask介绍和安装

# Flask介绍
Flask是一个轻量级的可定制框架,使用Python语言编写,较其他同类型框架更为灵活、轻便、安全且容易上手。它可以很好地结合MVC模式进行开发,开发人员分工合作,小型团队在短时间内就可以完成功能丰富的中小型网站或Web服务的实现。另外,Flask还有很强的定制性,用户可以根据自己的需求来添加相应的功能,在保持核心功能简单的同时实现功能的丰富与扩展,其强大的插件库可以让用户实现个性化的网站定制,开发出功能强大的网站。
Flask是一个基于Python开发并且依赖jinja2模板(DTL)和Werkzeug WSGI(符合wsgi协议的web服务器,wsgiref)服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后触发Flask框架,开发人员基于Flask框架提供的功能对请求进行相应的处理,并返回给用户,如果要返回给用户复杂的内容时,需要借助jinja2模板来实现对模板的处理,即:将模板和数据进行渲染,将渲染后的字符串返回给用户浏览器。

# 安装 flask
pip install flask

# flask快速使用
from flask import Flask

app=Flask(__name__)
@app.route('/')
def index():
    return 'hello  flask'


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

2 flask展示用户信息案例

from flask import Flask, render_template, request, redirect, session

app = Flask('web_site')

app.secret_key = 'national unification'

app.config.from_object('settings.DevelopmentConfig')

user_info = {
    '1': {'name': 'tom', 'age': 20, 'detail': 'from usa'},
    '2': {'name': 'kangkang', 'age': 22, 'detail': 'from CN'},
    '3': {'name': 'jerry', 'age': 2, 'detail': 'from uk'},
}
from functools import wraps


def login_auth(func):
    # @wraps(func)
    def inner(*args, **kwargs):
        if session.get('username') == 'kevin':
            res = func(*args, **kwargs)
            return res
        return redirect('/login')

    return inner


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


@app.route('/home', endpoint='home')
@login_auth
def home():
    return render_template('home.html', user_dic=user_info)


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        username = request.form.get('username')
        password = request.form.get('password')
        if username == 'kevin' and password == '1234':
            session['username'] = 'kevin'
            return redirect('/home')
        return render_template('login.html', err='用户名或密码错误')


@app.route('/detail/<int:pk>', endpoint='detail')
@login_auth
def detail(pk):
    pk = str(pk)
    return render_template('detail.html', user_dic=user_info.get(pk))


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




login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body style="text-align: center">
<br><br><br>
<h2>登陆页面</h2>
<form action="" method="post">
    <input type="text" name="username">
    <br><br>
    <input type="password" name="password">
    <br><br>
    <input type="submit" value="登陆">{{ err }}
</form>
</body>
</html>

home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<br><br><br>
<h2>首页</h2>
<table>
    {% for k,v in user_dic.items() %}
    <tr>
        <td>{{ k }}</td>
        <td>{{ v.name }}</td>
        <td>{{ v['name'] }}</td>
        <td>{{ v.get('name') }}</td>
        <td>{{ v.age }}</td>
        <td><a href="/detail/{{ k }}">详情</a></td>
    </tr>
    {% endfor %}
</table>

</body>
</html>

detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<br><br><br>
<h2>详情</h2>
<table>
    <tr>
        <td>{{ user_dic.name}}</td>
        <td>{{ user_dic.detail }}</td>
    </tr>
</table>
</body>
</html>

3 Flask常见操作

# 响应
	return 字符串                 返回字符串  
    return render_template        x渲染模板    
    return redirect('/login')     重定向
    return jsonify(字典,列表)     返回json格式
# session
	from flask importsession
	session['']=赋值
        

4 配置文件配置

# flask配置文件有多种方式
# 方式一
app.config['DEBUG'] = True

# 方式二
app.secret_key = 'national unification'
app.debug = True


# 方式三:settings.py中(CONFIG_NAME=CONFIG_ATTR)
app.config.from_pyfile('settings.py')
print(app.config['CONFIG_NAME'])

# 方式四:settings.py中(类的方式)
app.config.from_object('settings.DevelopmentConfig')

# 方式五:
app.config.from_envvar("ENVIRON_VARIBLE")

# 方式六:
app.config.from_json("JSON_FILE_NAME")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值