flask基本使用

 

flask是基于python开发并且依赖jinja2模版和werkzeug WSGI服务的一个微型框架(django使用的前端是自己的DTL)

 

安装flask

pip install flask

 

 

使用例一:

走的是http协议,新建一个py文件:

复制代码
from flask import Flask

app=Flask(__name__)

@app.route('/')  #配路由的,先去执行了函数的返回结果放在这里
def index():
    return 'hello world'

if __name__ == '__main__':
    app.run()
复制代码

 

 

 

 

 

例二:

复制代码
from flask import Flask,request


app=Flask(__name__)

@app.route('/')   # 装饰器加括号和不加括号的区别
def index():
    # 当前请求地址,当前请求携带过来的数据
    print(request.path)
    return 'hello world'

@app.route('/hello')
def hello():

    print(request.path)
    return 'hello hellohello'
if __name__ == '__main__':
    app.run()
    # 请求来了,会执行 app(request),会触发谁?触发__call__方法
复制代码

 

 

例三:三板斧(使用返回字符串、重定向、返回页面)

flask中返回字符串直接return '中间写字符串即可'

-return 字符串
-return render_template('index.html')
-return redirect('/login')

 

 

复制代码
from flask import Flask,request,render_template,redirect

app=Flask(__name__)

@app.route('/')
def index():

    # return render_template('index.html')
    # return redirect('http://www.baidu.com')
    return redirect('hello')


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

if __name__ == '__main__':
    app.run()
复制代码

 

 

 

登录,显示用户信息-小案例

路由写法(路径,支持的请求方式,别名)

@app.route('/login',methods=['GET','POST'],endpoint='l1')

 

 

模板语言渲染
-同dtl,但是比dtl强大,支持加括号执行,字典支持中括号取值和get取值


 分组(django中的有名分组)

 @app.route('/detail/<int:nid>',methods=['GET'])
    def detail(nid):

 

反向解析

-url_for('别名')

 

 

获取前端传递过来的数据

# get 请求
        request.query_string
      # post请求
      user = request.form.get('user')
      pwd = request.form.get('pwd')

 

main.py

复制代码
from flask import Flask,render_template,request,redirect,session,url_for
app = Flask(__name__)
app.debug = True
app.secret_key = 'sdfsdfsdfsdf'

USERS = {
    1:{'name':'张三','age':18,'gender':'','text':"道路千万条"},
    2:{'name':'李四','age':28,'gender':'','text':"安全第一条"},
    3:{'name':'王五','age':18,'gender':'','text':"行车不规范"},
}

@app.route('/detail/<int:nid>',methods=['GET'])
def detail(nid):
    user = session.get('user_info')
    if not user:
        return redirect('/login')

    info = USERS.get(nid)
    return render_template('detail.html',info=info)


@app.route('/index',methods=['GET'])
def index():
    user = session.get('user_info')
    if not user:
        # return redirect('/login')
        url = url_for('l1')
        return redirect(url)
    return render_template('index.html',user_dict=USERS)


@app.route('/login',methods=['GET','POST'],endpoint='l1')
def login():
    if request.method == "GET":
        return render_template('login.html')
    else:
        # request.query_string
        user = request.form.get('user')
        pwd = request.form.get('pwd')
        if user == 'zs' and pwd == '123':
            session['user_info'] = user
            return redirect('http://www.baidu.com')
        return render_template('login.html',error='用户名或密码错误')

if __name__ == '__main__':
    app.run()
复制代码

 

 

detail.html

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>用户列表</h1>
    <table>
        {% for k,v in user_dict.items() %}
        <tr>
            <td>{{k}}</td>
            <td>{{v.name}}</td>
            <td>{{v['name']}}</td>
            <td>{{v.get('name')}}</td>
            <td><a href="/detail/{{k}}">查看详细</a></td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>
复制代码

 

 

index.html

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>用户列表</h1>
    <table>
        {% for k,v in user_dict.items() %}
        <tr>
            <td>{{k}}</td>
            <td>{{v.name}}</td>
            <td>{{v['name']}}</td>
            <td>{{v.get('name')}}</td>
            <td><a href="/detail/{{k}}">查看详细</a></td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>
复制代码

 

 

login.html

复制代码
Copy<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>用户登录</h1>
    <form method="post">
        <input type="text" name="user">
        <input type="text" name="pwd">
        <input type="submit" value="登录">{{error}}
    </form>
</body>
</html>
复制代码

 

 

 

配置文件

我们这里指距离常用的三种方式

方式一

app.config['DEBUG'] = True
PS: 由于Config对象本质上是字典,所以还可以使用        app.config.update(...)

 

方式二

#通过py文件配置
app.config.from_pyfile("python文件名称")  #另开一个文件例如名字叫setting
如:
settings.py
DEBUG = True

 

方式三

复制代码
app.config.from_object('settings.TestingConfig')

class Config(object):
    DEBUG = False
    TESTING = False
    DATABASE_URI = 'sqlite://:memory:'


class ProductionConfig(Config):
    DATABASE_URI = 'mysql://user@localhost/foo'


class DevelopmentConfig(Config):
    DEBUG = True


class TestingConfig(Config):
    TESTING = True
复制代码

 

 

路由系统

基本使用

@app.route('/detail/<int:nid>',methods=['GET'],endpoint='detail')

 

转换器

复制代码
DEFAULT_CONVERTERS = {
    'default':          UnicodeConverter,
    'string':           UnicodeConverter,
    'any':              AnyConverter,
    'path':             PathConverter,
    'int':              IntegerConverter,
    'float':            FloatConverter,
    'uuid':             UUIDConverter,
}
复制代码

 

 

 

 

路由的本质

本质就是:app.add_url_rule()
endpoint:如果不写默认是函数名,endpoint不能重名

 

 

app.add_url_rule参数

复制代码
@app.route和app.add_url_rule参数:
rule, URL规则
view_func, 视图函数名称
defaults = None, 默认值, 当URL中无参数,函数需要参数时,使用defaults = {'k': 'v'}
为函数提供参数
endpoint = None, 名称,用于反向生成URL,即: url_for('名称')
methods = None, 允许的请求方式,如:["GET", "POST"]
#对URL最后的 / 符号是否严格要求,默认严格,False,就是不严格
strict_slashes = None
    '''
        @app.route('/index', strict_slashes=False)
        #访问http://www.xx.com/index/ 或http://www.xx.com/index均可
        @app.route('/index', strict_slashes=True)
        #仅访问http://www.xx.com/index
    '''
#重定向到指定地址
redirect_to = None, 
    '''
        @app.route('/index/<int:nid>', redirect_to='/home/<nid>')
    '''
复制代码

 

 

CBV

复制代码
from flask import Flask,request,render_template,redirect
from flask import views

app=Flask(__name__)


# class IndexView(views.View):
#     methods = ['GET']
#     # decorators = [auth, ]
#     def dispatch_request(self):
#         print('Index')
#         return 'Index!'

def auth(func):
    def inner(*args, **kwargs):
        print('before')
        result = func(*args, **kwargs)
        print('after')
        return result

    return inner
class IndexView(views.MethodView):
    methods = ['GET']  # 指定运行的请求方法
    # 登录认证装饰器加在哪?
    decorators = [auth, ]  #加多个就是从上往下的效果
    def get(self):
        print('xxxxx')
        return "我是get请求"
    def post(self):
       return '我是post请求'

# 路由如何注册?
# IndexView.as_view('index'),必须传name
app.add_url_rule('/index',view_func=IndexView.as_view('index'))

if __name__ == '__main__':
    app.run()
    
    
# 用的比较少
# 继承views.MethodView,只需要写get,post,delete方法
# 如果加装饰器decorators = [auth, ]
# 允许的请求方法methods = ['GET'] 
复制代码

 

posted @   朱饱饱  阅读(62)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示